merge admin changes into release/test
This commit is contained in:
@@ -60,13 +60,11 @@ function loginResponse(accessToken = token(), refreshToken = 'refresh-next') {
|
||||
expiresIn: 1800,
|
||||
refreshToken,
|
||||
refreshExpiresIn: 604800,
|
||||
overseasAccessToken: 'overseas-token',
|
||||
overseasExpiresIn: 900,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function domesticOnlyLoginResponse() {
|
||||
function unifiedLoginResponse() {
|
||||
return {
|
||||
code: '200',
|
||||
message: 'success',
|
||||
@@ -91,8 +89,8 @@ describe('admin auth session', () => {
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('accepts a domestic-only token response when the test environment has no overseas services', async () => {
|
||||
mocks.post.mockResolvedValue(domesticOnlyLoginResponse())
|
||||
it('accepts the unified access and refresh token response', async () => {
|
||||
mocks.post.mockResolvedValue(unifiedLoginResponse())
|
||||
mocks.listCurrentPlatformPermissionCodes.mockResolvedValue(['platform:warehouse:list'])
|
||||
const auth = useAuthStore()
|
||||
|
||||
@@ -116,8 +114,6 @@ describe('admin auth session', () => {
|
||||
expiresIn: '7200',
|
||||
refreshToken: 'refresh-serialized',
|
||||
refreshExpiresIn: '604800',
|
||||
overseasAccessToken: null,
|
||||
overseasExpiresIn: '0',
|
||||
},
|
||||
})
|
||||
mocks.listCurrentPlatformPermissionCodes.mockResolvedValue(['platform:warehouse:list'])
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type ApiEnvelope,
|
||||
} from '@/shared/api/http'
|
||||
import type { PlatformPermissionResource } from '@/shared/types/platformPermission'
|
||||
import { clearOverseasAccessToken, replaceOverseasAccessToken } from '@/shared/api/overseasHttp'
|
||||
import { decodeJwtClaims } from './jwt'
|
||||
import { listCurrentPlatformPermissionCodes } from './platformAuthorization'
|
||||
import { coordinateCrossTabRefresh } from './crossTabRefresh'
|
||||
@@ -24,8 +23,6 @@ interface LoginResponse {
|
||||
expiresIn: number | string
|
||||
refreshToken: string
|
||||
refreshExpiresIn: number | string
|
||||
overseasAccessToken?: string | null
|
||||
overseasExpiresIn?: number | string
|
||||
}
|
||||
|
||||
class ExpiredAccessTokenError extends Error {}
|
||||
@@ -100,10 +97,6 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
async function applySession(result: LoginResponse, expectedGeneration: number) {
|
||||
const session = sessionFromToken(result.accessToken)
|
||||
ensureCurrentGeneration(expectedGeneration)
|
||||
replaceOverseasAccessToken(
|
||||
result.overseasAccessToken ?? null,
|
||||
parseLifetimeSeconds(result.overseasExpiresIn ?? 0, 'overseasExpiresIn'),
|
||||
)
|
||||
token.value = result.accessToken
|
||||
refreshToken.value = result.refreshToken
|
||||
user.value = session.user
|
||||
@@ -123,7 +116,6 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
|
||||
function clearSession() {
|
||||
sessionGeneration += 1
|
||||
clearOverseasAccessToken()
|
||||
token.value = ''
|
||||
refreshToken.value = ''
|
||||
user.value = null
|
||||
@@ -151,7 +143,6 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
try {
|
||||
const session = sessionFromToken(storedToken)
|
||||
const cachedPermissions = JSON.parse(localStorage.getItem(PERMISSION_CODES_KEY) || '[]') as unknown
|
||||
if (token.value !== storedToken) clearOverseasAccessToken()
|
||||
token.value = storedToken
|
||||
refreshToken.value = storedRefreshToken
|
||||
user.value = session.user
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import test from 'node:test'
|
||||
|
||||
const script = (await readFile(new URL('../../scripts/deploy-production.sh', import.meta.url), 'utf8'))
|
||||
.replaceAll('\r\n', '\n')
|
||||
|
||||
test('production frontend starts and validates the candidate before switching nginx', () => {
|
||||
const start = script.indexOf('compose run -d --no-deps --name "$candidate"')
|
||||
const health = script.indexOf('docker exec "$candidate" wget')
|
||||
const nginx = script.indexOf('nginx -t || ! nginx -s reload')
|
||||
const stop = script.indexOf('docker stop --time 30 "$active_container"')
|
||||
const state = script.indexOf('mv -f "$state_file.tmp" "$state_file"')
|
||||
assert.ok(start >= 0 && start < health && health < nginx && nginx < stop && stop < state)
|
||||
})
|
||||
|
||||
test('production frontend supports both slots and restores nginx on failure', () => {
|
||||
assert.match(script, /target_port=\$\(\(base_port \+ 20000\)\)/)
|
||||
assert.match(script, /target_port=\$\(\(base_port \+ 10000\)\)/)
|
||||
assert.match(script, /00-blue-green-admin-web\.conf/)
|
||||
assert.match(script, /00-blue-green-client-web\.conf/)
|
||||
assert.doesNotMatch(script, /nginx_config=\/www\/server\/panel\/vhost\/nginx\/(?:admin|app)\.buggoglobal\.com\.conf/)
|
||||
assert.match(script, /cp -f "\$nginx_config" "\$backup"/)
|
||||
assert.match(script, /cp -f "\$backup" "\$nginx_config"/)
|
||||
assert.match(script, /docker rm -f "\$candidate"/)
|
||||
assert.match(script, /gateway-active:firstleg-production-gateway/)
|
||||
})
|
||||
@@ -1,85 +1,55 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync, existsSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { test } from 'vitest'
|
||||
|
||||
const config = readFileSync(resolve(process.cwd(), 'nginx/default.conf.template'), 'utf8')
|
||||
const testCompose = readFileSync(resolve(process.cwd(), 'docker-compose.test.yml'), 'utf8')
|
||||
const developmentCompose = readFileSync(resolve(process.cwd(), 'docker-compose.development.yml'), 'utf8')
|
||||
const productionCompose = readFileSync(resolve(process.cwd(), 'docker-compose.production.yml'), 'utf8')
|
||||
const jenkinsfile = readFileSync(resolve(process.cwd(), 'Jenkinsfile'), 'utf8')
|
||||
const dockerfile = readFileSync(resolve(process.cwd(), 'Dockerfile'), 'utf8')
|
||||
const root = process.cwd()
|
||||
const config = readFileSync(resolve(root, 'nginx/default.conf.template'), 'utf8')
|
||||
const compose = readFileSync(resolve(root, 'docker-compose.test.yml'), 'utf8')
|
||||
const jenkins = readFileSync(resolve(root, 'Jenkinsfile'), 'utf8')
|
||||
const vite = readFileSync(resolve(root, 'vite.config.ts'), 'utf8')
|
||||
|
||||
describe('admin nginx deployment config', () => {
|
||||
it('allows 50 MiB files plus multipart overhead through both bounded API proxies', () => {
|
||||
expect(config.match(/client_max_body_size 55m;/g)).toHaveLength(3)
|
||||
expect(config).not.toContain('client_max_body_size 12m;')
|
||||
expect(config).not.toContain('client_max_body_size 0;')
|
||||
})
|
||||
|
||||
it('prevents the application shell from retaining stale chunk references', () => {
|
||||
expect(config).toContain('location = /index.html')
|
||||
expect(config).toContain('Cache-Control "no-cache, no-store, must-revalidate"')
|
||||
})
|
||||
|
||||
it('serves hashed assets immutably and never falls back missing chunks to HTML', () => {
|
||||
expect(config).toContain('location /assets/')
|
||||
expect(config).toContain('try_files $uri =404;')
|
||||
expect(config).toContain('Cache-Control "public, max-age=31536000, immutable"')
|
||||
})
|
||||
|
||||
it('keeps Vue history routes on the application shell without caching them', () => {
|
||||
expect(config).toContain('try_files $uri $uri/ /index.html;')
|
||||
expect(config).toContain('Cache-Control "no-cache"')
|
||||
})
|
||||
|
||||
it('proxies overseas API requests to the gateway API prefix', () => {
|
||||
expect(config).toContain('location /overseas-api/')
|
||||
expect(config).toContain('rewrite ^/overseas-api/(.*)$ /api/$1 break;')
|
||||
expect(config).toContain('proxy_pass ${OVERSEAS_API_UPSTREAM};')
|
||||
})
|
||||
|
||||
it('declares an explicit overseas gateway upstream in container deployments', () => {
|
||||
expect(testCompose).toContain('- "host.docker.internal:host-gateway"')
|
||||
expect(testCompose).toContain('API_UPSTREAM: "${API_UPSTREAM:-http://host.docker.internal:9000}"')
|
||||
expect(testCompose).toContain('OVERSEAS_API_UPSTREAM: "${OVERSEAS_API_UPSTREAM:-http://host.docker.internal:9300}"')
|
||||
expect(testCompose).not.toContain('http://test-api-cn.buggoglobal.com')
|
||||
expect(testCompose).not.toContain('http://test-api-global.buggoglobal.com')
|
||||
expect(testCompose).toContain('CLIENT_WEB_URL: "${CLIENT_WEB_URL:-https://test-app.buggoglobal.com/}"')
|
||||
expect(testCompose).not.toContain('CLIENT_WEB_URL: "http://8.163.')
|
||||
expect(developmentCompose).toContain('CLIENT_WEB_URL: "${CLIENT_WEB_URL:-https://dev-app.buggoglobal.com/}"')
|
||||
expect(developmentCompose).toContain('OVERSEAS_API_UPSTREAM: "http://firstleg-development-gateway-overseas:9300"')
|
||||
expect(config).toContain('proxy_set_header Host $proxy_host;')
|
||||
})
|
||||
|
||||
it('keeps local environments on target nodes and uses credential-managed SSH for production', () => {
|
||||
expect(jenkinsfile).toContain("env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder'")
|
||||
expect(jenkinsfile).toContain("DEVELOPMENT_COMPOSE_PROJECT = 'admin-web'")
|
||||
expect(jenkinsfile).toContain('docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" up -d')
|
||||
expect(jenkinsfile).not.toContain('/var/jenkins_home/.ssh')
|
||||
expect(jenkinsfile).not.toContain('docker save')
|
||||
expect(jenkinsfile).toContain("credentialsId: 'firstleg-production-ssh'")
|
||||
expect(jenkinsfile).toContain('git rev-parse origin/main')
|
||||
expect(productionCompose).toContain('127.0.0.1:${HOST_PORT:-9001}:80')
|
||||
expect(productionCompose).toContain('API_UPSTREAM: "http://gateway-active:9000"')
|
||||
expect(productionCompose).toContain('OVERSEAS_API_UPSTREAM: "http://gateway-overseas-active:9300"')
|
||||
expect(productionCompose).toContain('name: firstleg-production-routing')
|
||||
expect(productionCompose).toContain('name: firstleg-prod-infra-network')
|
||||
})
|
||||
|
||||
it('uses authenticated internal base images in CI instead of pulling from Docker Hub', () => {
|
||||
expect(dockerfile).toContain('ARG NODE_IMAGE=node:22-alpine')
|
||||
expect(dockerfile).toContain('ARG NGINX_IMAGE=nginx:1.27-alpine')
|
||||
expect(dockerfile).toContain('FROM ${NODE_IMAGE} AS build')
|
||||
expect(dockerfile).toContain('FROM ${NGINX_IMAGE}')
|
||||
expect(jenkinsfile).toContain("NODE_BASE_IMAGE = '172.31.198.7:10082/java-project/node:22-alpine'")
|
||||
expect(jenkinsfile).toContain("NGINX_BASE_IMAGE = '172.31.198.7:10082/java-project/nginx:1.27-alpine'")
|
||||
expect(jenkinsfile).toContain('withCredentials([usernamePassword(')
|
||||
expect(jenkinsfile).toContain('export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"')
|
||||
expect(jenkinsfile).toContain('--build-arg VITE_CLIENT_WEB_URL="${CLIENT_WEB_URL:-https://dev-app.buggoglobal.com/}"')
|
||||
})
|
||||
|
||||
it('proxies Mojia measurement OpenAPI requests to the domestic gateway', () => {
|
||||
expect(config).toContain('location /openapi/')
|
||||
expect(config).toContain('location /openapi/ {\n client_max_body_size 55m;\n proxy_pass ${API_UPSTREAM};')
|
||||
})
|
||||
test('all business traffic uses one Gateway without rewriting API paths', () => {
|
||||
assert.match(config, /location \/api\//)
|
||||
assert.match(config, /proxy_pass \$\{API_UPSTREAM\};/)
|
||||
assert.doesNotMatch(config, /overseas-api|OVERSEAS_API_UPSTREAM|rewrite/)
|
||||
assert.match(config, /client_max_body_size 55m;/)
|
||||
assert.match(config, /proxy_set_header Host \$proxy_host;/)
|
||||
assert.doesNotMatch(vite, /OVERSEAS_API|AUTH_API_PROXY_TARGET|IAM_API_PROXY_TARGET|WAREHOUSE_API_PROXY_TARGET/)
|
||||
})
|
||||
|
||||
test('test deployment requires an explicit shared network, Gateway and version', () => {
|
||||
for (const key of ['IMAGE_TAG']) {
|
||||
assert.ok(compose.includes('${' + key + ':?'))
|
||||
}
|
||||
assert.ok(compose.includes('${API_UPSTREAM:-http://gateway:9000}'))
|
||||
assert.ok(compose.includes('${TEST_NETWORK:-firstleg-test-network}'))
|
||||
assert.match(compose, /external: true/)
|
||||
assert.match(compose, /127\.0\.0\.1:/)
|
||||
assert.doesNotMatch(compose, /overseas|host\.docker\.internal|production|development/)
|
||||
assert.match(jenkins, /label 'java-test'/)
|
||||
assert.match(jenkins, /docker compose -f docker-compose\.test\.yml config --quiet/)
|
||||
assert.match(jenkins, /docker network inspect/)
|
||||
assert.doesNotMatch(jenkins, /docker-compose\.(production|development)|deploy-production|sshUserPrivateKey/)
|
||||
for (const file of ['docker-compose.production.yml', 'docker-compose.development.yml', 'scripts/deploy-production.sh']) {
|
||||
assert.equal(existsSync(resolve(root, file)), false)
|
||||
}
|
||||
})
|
||||
|
||||
test('application shell is revalidated and missing chunks remain 404', () => {
|
||||
assert.match(config, /location = \/index\.html/)
|
||||
assert.match(config, /no-store/)
|
||||
assert.match(config, /max-age=31536000, immutable/)
|
||||
assert.match(config, /try_files \$uri =404;/)
|
||||
assert.match(config, /try_files \$uri \$uri\/ \/index\.html;/)
|
||||
})
|
||||
|
||||
|
||||
test('container build excludes local environment values and waits for Nginx health', () => {
|
||||
const ignore = readFileSync(resolve(root, '.dockerignore'), 'utf8')
|
||||
assert.match(ignore, /^\.env$/m)
|
||||
assert.match(ignore, /^\.env\.\*$/m)
|
||||
assert.match(compose, /healthcheck:/)
|
||||
assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
|
||||
assert.match(jenkins, /up -d --wait --wait-timeout 120/)
|
||||
})
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { listContainerArrivalTimes, updateContainerExpectedArrival } from './containerArrivalTimes'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { post: vi.fn(), put: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { post: vi.fn(), put: vi.fn() } }))
|
||||
|
||||
describe('container arrival-time overseas API', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('queries visible containers and updates the whole-container expected arrival', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: [{ sourceContainerBookingId: '9001', estimatedWarehouseArrivalAt: null, actualWarehouseArrivalAt: null, version: 0 }] })
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', data: { sourceContainerBookingId: '9001', estimatedWarehouseArrivalAt: '2026-09-25T15:31:00', actualWarehouseArrivalAt: null, version: 1 } } as never)
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: [{ sourceContainerBookingId: '9001', estimatedWarehouseArrivalAt: null, actualWarehouseArrivalAt: null, version: 0 }] })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', data: { sourceContainerBookingId: '9001', estimatedWarehouseArrivalAt: '2026-09-25T15:31:00', actualWarehouseArrivalAt: null, version: 1 } } as never)
|
||||
|
||||
await listContainerArrivalTimes(['9001'])
|
||||
await updateContainerExpectedArrival('9001', { estimatedWarehouseArrivalAt: '2026-09-25T15:31:00', expectedVersion: 0 })
|
||||
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-arrival-times/query', { sourceContainerBookingIds: ['9001'] })
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-summaries/9001/expected-arrival', { estimatedWarehouseArrivalAt: '2026-09-25T15:31:00', expectedVersion: 0 }, { headers: { 'Idempotency-Key': expect.stringContaining('container-expected-arrival-9001-') } })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-arrival-times/query', { sourceContainerBookingIds: ['9001'] })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-summaries/9001/expected-arrival', { estimatedWarehouseArrivalAt: '2026-09-25T15:31:00', expectedVersion: 0 }, { headers: { 'Idempotency-Key': expect.stringContaining('container-expected-arrival-9001-') } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
|
||||
export interface ContainerArrivalTime {
|
||||
sourceContainerBookingId: string
|
||||
@@ -16,7 +16,7 @@ function operationId(containerBookingId: string) {
|
||||
|
||||
export async function listContainerArrivalTimes(sourceContainerBookingIds: string[]) {
|
||||
if (!sourceContainerBookingIds.length) return []
|
||||
const response = await overseasHttp.post<ApiEnvelope<ContainerArrivalTime[]>, ApiEnvelope<ContainerArrivalTime[]>>(
|
||||
const response = await http.post<ApiEnvelope<ContainerArrivalTime[]>, ApiEnvelope<ContainerArrivalTime[]>>(
|
||||
queryPath,
|
||||
{ sourceContainerBookingIds },
|
||||
)
|
||||
@@ -27,7 +27,7 @@ export async function updateContainerExpectedArrival(
|
||||
sourceContainerBookingId: string,
|
||||
body: { estimatedWarehouseArrivalAt: string; expectedVersion: number; remark?: string },
|
||||
) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<ContainerArrivalTime>, ApiEnvelope<ContainerArrivalTime>>(
|
||||
const response = await http.put<ApiEnvelope<ContainerArrivalTime>, ApiEnvelope<ContainerArrivalTime>>(
|
||||
`/platform/v1/last-leg/orders/container-summaries/${encodeURIComponent(sourceContainerBookingId)}/expected-arrival`,
|
||||
body,
|
||||
{ headers: { 'Idempotency-Key': operationId(sourceContainerBookingId) } },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { adjustOverseasContainerFee, createOverseasContainerFee, listOverseasContainerCustomers, listOverseasContainerFees, reviewOverseasContainerFee, submitOverseasContainerFee, voidOverseasContainerFee, type OverseasContainerFeeSaveRequest } from './overseasContainerFees'
|
||||
|
||||
const raw = { id: 91, sourceFeeId: 81, sourceVersion: 2, customerId: 11, customerName: '客户A', sourceType: 'OVERSEAS_CONTAINER_FEE', businessType: 'OVERSEAS_CONTAINER', businessId: 99, businessNo: 'CONT-99', containerBookingId: 99, containerNo: 'CONT-99', feeItemCode: 'PORT_FEE', feeItemName: '港口费', direction: 'PAYABLE', amount: 300, currency: 'CNY', reviewStatus: 'DRAFT', sourceStatus: 'ACTIVE', businessDate: '2026-09-08' }
|
||||
@@ -7,14 +7,14 @@ const fee: OverseasContainerFeeSaveRequest = { customerId: '11', customerName: '
|
||||
describe('overseas container fees API', () => {
|
||||
beforeEach(() => vi.restoreAllMocks())
|
||||
it('loads all fees and customers with two container aggregate requests', async () => {
|
||||
const get = vi.spyOn(overseasHttp, 'get').mockResolvedValueOnce({ code: '200', data: [raw] }).mockResolvedValueOnce({ code: '200', data: [{ customerId: 11, customerName: '客户A' }] })
|
||||
const get = vi.spyOn(http, 'get').mockResolvedValueOnce({ code: '200', data: [raw] }).mockResolvedValueOnce({ code: '200', data: [{ customerId: 11, customerName: '客户A' }] })
|
||||
await expect(listOverseasContainerFees('99')).resolves.toMatchObject([{ sourceFeeId: '81', containerBookingId: '99', feeItemCode: 'PORT_FEE' }])
|
||||
await expect(listOverseasContainerCustomers('99')).resolves.toEqual([{ customerId: '11', customerName: '客户A' }])
|
||||
expect(get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/finance-fee-sources', { params: { containerBookingId: '99', businessType: 'OVERSEAS_CONTAINER' } })
|
||||
expect(get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/finance-fee-sources/container-customers', { params: { containerBookingId: '99' } })
|
||||
})
|
||||
it('uses the exact create and lifecycle action contracts', async () => {
|
||||
const post = vi.spyOn(overseasHttp, 'post').mockResolvedValue({ code: '200', data: raw })
|
||||
const post = vi.spyOn(http, 'post').mockResolvedValue({ code: '200', data: raw })
|
||||
await createOverseasContainerFee(fee, 'create-1'); await submitOverseasContainerFee('81', 'submit-1'); await reviewOverseasContainerFee('81', 'APPROVE', null, 'review-1'); await adjustOverseasContainerFee('81', 2, fee, 'adjust-1'); await voidOverseasContainerFee('81', 2, '重复费用', 'void-1')
|
||||
expect(post).toHaveBeenCalledWith('/platform/v1/last-leg/finance-fee-sources', fee, { headers: { 'Idempotency-Key': 'create-1' } })
|
||||
expect(post).toHaveBeenCalledWith('/platform/v1/last-leg/finance-fee-sources/81/submit', { idempotencyKey: 'submit-1' })
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
|
||||
const basePath = '/platform/v1/last-leg/finance-fee-sources'
|
||||
type RawResource = Record<string, unknown>
|
||||
@@ -42,25 +42,25 @@ function normalizeFee(raw: RawResource): OverseasContainerFeeSource {
|
||||
}
|
||||
}
|
||||
export async function listOverseasContainerFees(containerBookingId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<RawResource[]>, ApiEnvelope<RawResource[]>>(basePath, { params: { containerBookingId, businessType: 'OVERSEAS_CONTAINER' } })
|
||||
const response = await http.get<ApiEnvelope<RawResource[]>, ApiEnvelope<RawResource[]>>(basePath, { params: { containerBookingId, businessType: 'OVERSEAS_CONTAINER' } })
|
||||
return unwrapApiResponse(response).map(normalizeFee)
|
||||
}
|
||||
export async function listOverseasContainerCustomers(containerBookingId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<Array<{ customerId: unknown; customerName?: unknown }>>, ApiEnvelope<Array<{ customerId: unknown; customerName?: unknown }>>>(`${basePath}/container-customers`, { params: { containerBookingId } })
|
||||
const response = await http.get<ApiEnvelope<Array<{ customerId: unknown; customerName?: unknown }>>, ApiEnvelope<Array<{ customerId: unknown; customerName?: unknown }>>>(`${basePath}/container-customers`, { params: { containerBookingId } })
|
||||
return unwrapApiResponse(response).map((item) => ({ customerId: requiredText(item.customerId), customerName: text(item.customerName) }))
|
||||
}
|
||||
export async function createOverseasContainerFee(payload: OverseasContainerFeeSaveRequest, idempotencyKey: string) {
|
||||
return normalizeFee(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(basePath, payload, { headers: { 'Idempotency-Key': idempotencyKey } })))
|
||||
return normalizeFee(unwrapApiResponse(await http.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(basePath, payload, { headers: { 'Idempotency-Key': idempotencyKey } })))
|
||||
}
|
||||
export async function submitOverseasContainerFee(sourceFeeId: string, idempotencyKey: string) {
|
||||
return normalizeFee(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/submit`, { idempotencyKey })))
|
||||
return normalizeFee(unwrapApiResponse(await http.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/submit`, { idempotencyKey })))
|
||||
}
|
||||
export async function reviewOverseasContainerFee(sourceFeeId: string, decision: 'APPROVE' | 'REJECT', reason: string | null, idempotencyKey: string) {
|
||||
return normalizeFee(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/review`, { decision, reason, idempotencyKey })))
|
||||
return normalizeFee(unwrapApiResponse(await http.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/review`, { decision, reason, idempotencyKey })))
|
||||
}
|
||||
export async function adjustOverseasContainerFee(sourceFeeId: string, expectedVersion: number, fee: OverseasContainerFeeSaveRequest, idempotencyKey: string) {
|
||||
return normalizeFee(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/adjust`, { expectedVersion, fee, idempotencyKey })))
|
||||
return normalizeFee(unwrapApiResponse(await http.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/adjust`, { expectedVersion, fee, idempotencyKey })))
|
||||
}
|
||||
export async function voidOverseasContainerFee(sourceFeeId: string, expectedVersion: number, reason: string, idempotencyKey: string) {
|
||||
return normalizeFee(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/void`, { expectedVersion, reason, idempotencyKey })))
|
||||
return normalizeFee(unwrapApiResponse(await http.post<ApiEnvelope<RawResource>, ApiEnvelope<RawResource>>(`${basePath}/${encodeURIComponent(sourceFeeId)}/void`, { expectedVersion, reason, idempotencyKey })))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { recordClearanceResult, type DeclarationBatch } from './platformContainerCustoms'
|
||||
import { completeAllBuyContainerCustoms, downloadContainerCustomsReceipt, downloadContainerCustomsDocument, getContainerCustoms, sendContainerCustomsToBroker, startContainerCustoms, uploadContainerCustomsReceipt } from './platformContainerCustoms'
|
||||
|
||||
const customs = {
|
||||
@@ -14,6 +15,20 @@ const customs = {
|
||||
describe('platform container customs API', () => {
|
||||
beforeEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('records domestic customs time in Shanghai even when UTC falls on the previous day', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.setSystemTime(new Date('2026-09-29T16:30:00Z'))
|
||||
const post = vi.spyOn(http, 'post').mockResolvedValue({ code: '200', data: { id: '1' } })
|
||||
await recordClearanceResult({ id: '123', version: 1 } as DeclarationBatch, 'OTHER', 'test')
|
||||
expect(post).toHaveBeenCalledWith('/platform/v1/customs/loading-plans/declaration-batches/123/results',
|
||||
expect.objectContaining({ occurredAt: '2026-09-30T00:30:00', resultType: 'OTHER', resolution: 'test' }),
|
||||
expect.objectContaining({ headers: { 'Idempotency-Key': expect.any(String) } }))
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('uses the frozen customs-v1 paths and preserves long ids as strings', async () => {
|
||||
const get = vi.spyOn(http, 'get').mockResolvedValue({ code: '200', message: 'ok', data: customs })
|
||||
const result = await getContainerCustoms('2092438843630391402')
|
||||
|
||||
@@ -189,7 +189,13 @@ export async function submitDeclarationBatch(batch: DeclarationBatch, customsEnt
|
||||
}
|
||||
|
||||
export async function recordClearanceResult(batch: DeclarationBatch, resultType: ClearanceResultType, resolution?: string) {
|
||||
const response = await http.post<ApiEnvelope<ClearanceResult>, ApiEnvelope<ClearanceResult>>(`${basePath}/declaration-batches/${encodeURIComponent(batch.id)}/results`, { expectedVersion: batch.version, resultType, occurredAt: new Date().toISOString(), resolution: resolution?.trim() || null, evidenceFileId: null, resolved: false }, { headers: { 'Idempotency-Key': operationId('customs-clearance-result-record') } })
|
||||
// The domestic API stores LocalDateTime; send Shanghai wall time, not UTC with a discarded offset.
|
||||
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
|
||||
}).formatToParts(new Date()).map(({ type, value }) => [type, value]))
|
||||
const occurredAt = `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}`
|
||||
const response = await http.post<ApiEnvelope<ClearanceResult>, ApiEnvelope<ClearanceResult>>(`${basePath}/declaration-batches/${encodeURIComponent(batch.id)}/results`, { expectedVersion: batch.version, resultType, occurredAt, resolution: resolution?.trim() || null, evidenceFileId: null, resolved: false }, { headers: { 'Idempotency-Key': operationId('customs-clearance-result-record') } })
|
||||
return normalizeClearanceResult(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
import { ApiResponseError } from '@/shared/api/http'
|
||||
import type { ContainerCustomsStatus, ContainerCustomsView } from '../api/platformContainerCustoms'
|
||||
import type { ContainerCustomsStatus, ContainerCustomsView, DeclarationBatch, ClearanceResultType } from '../api/platformContainerCustoms'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
get: vi.fn(),
|
||||
@@ -77,6 +77,42 @@ describe('ContainerCustomsPanel', () => {
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
})
|
||||
|
||||
it('renders all customs result reasons in Chinese with the recorded remarks', async () => {
|
||||
const reasons: Array<[ClearanceResultType, string]> = [
|
||||
['INSPECTION', '查验'], ['SUPPLEMENT_REQUIRED', '补资料'],
|
||||
['DETAINED', '扣货'], ['RELEASED', '放行'], ['OTHER', '其他'],
|
||||
]
|
||||
const batch: DeclarationBatch = {
|
||||
id: '101', customsContainerId: '102', loadingPlanId: '2092438843630391402',
|
||||
batchNo: 'DEC-TEST-001', status: 'RESULT_PENDING', sourceVersion: 1,
|
||||
customsEntryNo: 'ENTRY-TEST-001', version: 1, submittedAt: null,
|
||||
submittedByName: null, acknowledgedAt: null, acknowledgedByName: null, remark: null,
|
||||
results: reasons.map(([resultType], index) => ({
|
||||
id: String(200 + index), declarationBatchId: '101', customsContainerId: '102',
|
||||
resultType, resultStatus: 'OPEN', customsEntryNo: 'ENTRY-TEST-001',
|
||||
occurredAt: '2026-09-29T10:00:00', resolution: `人工备注${index}`,
|
||||
evidenceFileId: null, recordedByName: '操作员', recordedAt: '2026-09-29T10:00:00',
|
||||
previousResultId: null,
|
||||
})),
|
||||
}
|
||||
api.getDeclarationBatches.mockResolvedValue([batch])
|
||||
api.get.mockResolvedValue({ ...customs('COMPLETED', true), brokerSubmittedAt: '2026-09-29T09:00:00' })
|
||||
const wrapper = mount(ContainerCustomsPanel, {
|
||||
props: { loadingPlanId: batch.loadingPlanId, canList: true, canManage: false, departureState: 'WAITING_OTHER_GATES' },
|
||||
global: { plugins: [ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
const rows = wrapper.findAll('.declaration-result-row')
|
||||
expect(rows).toHaveLength(reasons.length)
|
||||
for (const [index, [code, label]] of reasons.entries()) {
|
||||
expect(rows[index]!.text()).toContain(label)
|
||||
expect(rows[index]!.text()).toContain(`人工备注${index}`)
|
||||
expect(rows[index]!.text()).not.toContain(code)
|
||||
expect(rows[index]!.find('button').exists()).toBe(false)
|
||||
}
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('keeps READY_TO_START read-only while exposing source file name and download', async () => {
|
||||
const wrapper = await render('READY_TO_START')
|
||||
expect(wrapper.text()).toContain('开始报关')
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
type ContainerCustomsDocument,
|
||||
type ContainerCustomsStatus,
|
||||
type ContainerCustomsView,
|
||||
type ClearanceResultType,
|
||||
type DeclarationBatch,
|
||||
} from '../api/platformContainerCustoms'
|
||||
|
||||
@@ -46,6 +47,21 @@ const actionError = ref<ApiErrorDetails | null>(null)
|
||||
const downloadingKey = ref('')
|
||||
const receiptFiles = reactive<Record<string, File | null>>({})
|
||||
const finalFiles = reactive<Record<string, File | null>>({})
|
||||
const clearanceDialogVisible = ref(false)
|
||||
const clearanceBatch = ref<DeclarationBatch | null>(null)
|
||||
const clearanceResultType = ref<ClearanceResultType>('INSPECTION')
|
||||
const clearanceRemark = ref('')
|
||||
const clearanceResultOptions: Array<{ value: ClearanceResultType; label: string }> = [
|
||||
{ value: 'INSPECTION', label: '查验' },
|
||||
{ value: 'SUPPLEMENT_REQUIRED', label: '补资料' },
|
||||
{ value: 'DETAINED', label: '扣货' },
|
||||
{ value: 'RELEASED', label: '放行' },
|
||||
{ value: 'OTHER', label: '其他' },
|
||||
]
|
||||
|
||||
function clearanceResultLabel(value: ClearanceResultType) {
|
||||
return clearanceResultOptions.find((option) => option.value === value)?.label || '未知结果'
|
||||
}
|
||||
|
||||
const missingInbounds = computed(() => customs.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND' && !item.covered) || [])
|
||||
const missingCoverageCount = computed(() => Math.max(0, (customs.value?.taxRefundCount || 0) - (customs.value?.coveredTaxRefundCount || 0)))
|
||||
@@ -122,16 +138,27 @@ async function submitFormalDeclaration(batch: DeclarationBatch) {
|
||||
} finally { actionLoading.value = false }
|
||||
}
|
||||
|
||||
async function recordFormalResult(batch: DeclarationBatch) {
|
||||
function openFormalResultDialog(batch: DeclarationBatch) {
|
||||
clearanceBatch.value = batch
|
||||
clearanceResultType.value = 'INSPECTION'
|
||||
clearanceRemark.value = ''
|
||||
clearanceDialogVisible.value = true
|
||||
}
|
||||
|
||||
async function recordFormalResult() {
|
||||
const batch = clearanceBatch.value
|
||||
if (!batch) return
|
||||
if (clearanceResultType.value === 'OTHER' && !clearanceRemark.value.trim()) {
|
||||
ElMessage.warning('选择“其他”时请填写备注')
|
||||
return
|
||||
}
|
||||
actionLoading.value = true; actionError.value = null
|
||||
try {
|
||||
const answer = await ElMessageBox.prompt('可填写查验处理说明,没有说明可直接确认', '录入海关查验结果', { customClass: 'admin-density-confirm', inputPlaceholder: '处理说明(可选)', confirmButtonText: '确认录入' })
|
||||
actionLoading.value = true; actionError.value = null
|
||||
await recordClearanceResult(batch, 'INSPECTION', answer.value)
|
||||
await load(); ElMessage.success('海关结果已录入')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
actionError.value = getApiErrorDetails(error, '海关结果录入失败')
|
||||
} finally { actionLoading.value = false }
|
||||
await recordClearanceResult(batch, clearanceResultType.value, clearanceRemark.value.trim() || undefined)
|
||||
clearanceDialogVisible.value = false
|
||||
await load(); ElMessage.success('海关结果已记录')
|
||||
} catch (error) { actionError.value = getApiErrorDetails(error, '海关结果记录失败') }
|
||||
finally { actionLoading.value = false }
|
||||
}
|
||||
|
||||
async function resolveFormalResult(batch: DeclarationBatch, result: DeclarationBatch['results'][number]) {
|
||||
@@ -305,8 +332,8 @@ onMounted(load)
|
||||
<article v-for="batch in declarationBatches" :key="batch.id" class="declaration-batch-card">
|
||||
<div class="declaration-batch-main"><strong>{{ batch.batchNo }}</strong><span>报关单号:{{ batch.customsEntryNo || '—' }} · 版本 {{ batch.version }}</span></div>
|
||||
<el-tag size="small" :type="batch.status === 'CLOSED' ? 'success' : batch.status === 'CANCELLED' ? 'info' : 'warning'">{{ declarationStatusLabel(batch.status) }}</el-tag>
|
||||
<div class="declaration-batch-actions" v-if="canManage"><el-button v-if="batch.status === 'READY'" size="small" type="primary" :loading="actionLoading" @click="submitFormalDeclaration(batch)">提交正式申报</el-button><el-button v-if="['SUBMITTED','ACKNOWLEDGED','RESULT_PENDING'].includes(batch.status)" size="small" plain :loading="actionLoading" @click="recordFormalResult(batch)">录入查验结果</el-button></div>
|
||||
<div v-if="batch.results.length" class="declaration-result-list"><div v-for="result in batch.results" :key="result.id" class="declaration-result-row"><span>{{ result.resultType === 'INSPECTION' ? '查验' : result.resultType === 'SUPPLEMENT_REQUIRED' ? '补充资料' : result.resultType === 'RELEASED' ? '放行' : result.resultType }}</span><el-tag size="small" :type="result.resultStatus === 'RESOLVED' ? 'success' : 'warning'">{{ result.resultStatus === 'RESOLVED' ? '已处理' : result.resultStatus === 'OPEN' ? '待处理' : '已取消' }}</el-tag><small>{{ result.resolution || '—' }}</small><el-button v-if="canManage && result.resultStatus === 'OPEN'" link type="primary" size="small" :loading="actionLoading" @click="resolveFormalResult(batch, result)">处理</el-button></div></div>
|
||||
<div class="declaration-batch-actions" v-if="canManage"><el-button v-if="batch.status === 'READY'" size="small" type="primary" :loading="actionLoading" @click="submitFormalDeclaration(batch)">提交正式申报</el-button><el-button v-if="['SUBMITTED','ACKNOWLEDGED','RESULT_PENDING'].includes(batch.status)" size="small" plain :loading="actionLoading" @click="openFormalResultDialog(batch)">标记海关异常/结果</el-button></div>
|
||||
<div v-if="batch.results.length" class="declaration-result-list"><div v-for="result in batch.results" :key="result.id" class="declaration-result-row"><span>{{ clearanceResultLabel(result.resultType) }}</span><el-tag size="small" :type="result.resultStatus === 'RESOLVED' ? 'success' : 'warning'">{{ result.resultStatus === 'RESOLVED' ? '已处理' : result.resultStatus === 'OPEN' ? '待处理' : '已取消' }}</el-tag><small>{{ result.resolution || '—' }}</small><el-button v-if="canManage && result.resultStatus === 'OPEN'" link type="primary" size="small" :loading="actionLoading" @click="resolveFormalResult(batch, result)">处理</el-button></div></div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
@@ -314,9 +341,22 @@ onMounted(load)
|
||||
<div v-if="customs.status === 'COMPLETED'" class="departure-state"><strong>国内离仓状态:</strong><el-tag :type="departureState === 'DEPARTED' ? 'success' : 'warning'">{{ departureState === 'DEPARTED' ? '已自动离仓' : departureState === 'UNKNOWN' ? '离仓状态尚未读取' : '报关已完成,待其他离仓条件' }}</el-tag></div>
|
||||
</template>
|
||||
<el-empty v-else-if="canList" description="当前装柜计划尚未完成,完成装柜后可处理报关" :image-size="56" />
|
||||
<el-dialog v-model="clearanceDialogVisible" class="admin-density-dialog" title="标记海关异常/结果" width="460px" :close-on-click-modal="false">
|
||||
<el-form label-position="top" class="clearance-result-form">
|
||||
<el-form-item label="选择理由" required>
|
||||
<el-select v-model="clearanceResultType" class="clearance-result-select" placeholder="请选择理由">
|
||||
<el-option v-for="option in clearanceResultOptions" :key="option.value" :label="option.label" :value="option.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注" :required="clearanceResultType === 'OTHER'">
|
||||
<el-input v-model="clearanceRemark" type="textarea" :rows="4" maxlength="1000" show-word-limit :placeholder="clearanceResultType === 'OTHER' ? '请填写具体情况' : '可填写短信内容或人工处理说明(可选)'" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer><el-button @click="clearanceDialogVisible = false">取消</el-button><el-button type="primary" :loading="actionLoading" @click="recordFormalResult">确认标记</el-button></template>
|
||||
</el-dialog>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.container-customs{padding:0;border:0}.customs-header{display:flex;align-items:center;justify-content:space-between;gap:var(--admin-space-5)}.customs-header h2,.compact-table-wrap h3{margin:0;font-size:var(--admin-font-section)}.customs-header p{margin:3px 0 0;color:var(--cc-muted);font-size:var(--admin-font-caption)}.customs-actions{display:flex;align-items:center;gap:var(--admin-space-3)}.action-error{margin-top:var(--admin-space-3);padding:var(--admin-space-3) var(--admin-space-4);border:1px solid var(--el-color-danger-light-5);border-radius:var(--admin-radius);background:var(--el-color-danger-light-9);color:var(--el-color-danger);font-size:var(--admin-font-caption)}.action-error :deep(.api-error-meta){margin-top:5px}.customs-metrics{display:flex;gap:var(--admin-space-6);margin-top:var(--admin-space-4);padding:var(--admin-space-3) var(--admin-space-4);background:var(--cc-surface-muted);font-size:var(--admin-font-caption)}.customs-metrics strong{margin-left:var(--admin-space-1);font-size:var(--admin-font-body)}.customs-metrics .danger strong{color:var(--el-color-danger)}.compact-table-wrap{margin-top:var(--admin-space-4)}.compact-table-wrap h3{margin-bottom:var(--admin-space-2)}.compact-table{width:100%}.document-table th:first-child{width:270px}.document-actions,.file-cell{display:flex;align-items:center;gap:var(--admin-space-2)}.file-cell span{display:block;max-width:210px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.readonly-label{color:var(--cc-muted)}.departure-state{display:flex;align-items:center;gap:var(--admin-space-3);margin-top:var(--admin-space-4);padding-top:var(--admin-space-4);border-top:1px solid var(--cc-border);font-size:var(--admin-font-body)}.declaration-batches-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:var(--admin-space-4)}.declaration-batches-heading p{margin:3px 0 0;color:var(--cc-muted);font-size:var(--admin-font-caption)}.declaration-batch-list{display:grid;gap:var(--admin-space-3)}.declaration-batch-card{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--admin-space-2) var(--admin-space-4);padding:var(--admin-space-3) var(--admin-space-4);border:1px solid var(--cc-border);background:var(--cc-surface-muted)}.declaration-batch-main strong,.declaration-batch-main span{display:block}.declaration-batch-main span{margin-top:4px;color:var(--cc-muted);font-size:var(--admin-font-caption)}.declaration-batch-actions,.declaration-result-list{grid-column:1 / -1}.declaration-result-list{display:grid;gap:5px;padding-top:var(--admin-space-2);border-top:1px solid var(--cc-border)}.declaration-result-row{display:flex;align-items:center;gap:var(--admin-space-2);font-size:var(--admin-font-caption)}.declaration-result-row small{flex:1;color:var(--cc-muted)}
|
||||
.container-customs{padding:0;border:0}.customs-header{display:flex;align-items:center;justify-content:space-between;gap:var(--admin-space-5)}.customs-header h2,.compact-table-wrap h3{margin:0;font-size:var(--admin-font-section)}.customs-header p{margin:3px 0 0;color:var(--cc-muted);font-size:var(--admin-font-caption)}.customs-actions{display:flex;align-items:center;gap:var(--admin-space-3)}.action-error{margin-top:var(--admin-space-3);padding:var(--admin-space-3) var(--admin-space-4);border:1px solid var(--el-color-danger-light-5);border-radius:var(--admin-radius);background:var(--el-color-danger-light-9);color:var(--el-color-danger);font-size:var(--admin-font-caption)}.action-error :deep(.api-error-meta){margin-top:5px}.customs-metrics{display:flex;gap:var(--admin-space-6);margin-top:var(--admin-space-4);padding:var(--admin-space-3) var(--admin-space-4);background:var(--cc-surface-muted);font-size:var(--admin-font-caption)}.customs-metrics strong{margin-left:var(--admin-space-1);font-size:var(--admin-font-body)}.customs-metrics .danger strong{color:var(--el-color-danger)}.compact-table-wrap{margin-top:var(--admin-space-4)}.compact-table-wrap h3{margin-bottom:var(--admin-space-2)}.compact-table{width:100%}.document-table th:first-child{width:270px}.document-actions,.file-cell{display:flex;align-items:center;gap:var(--admin-space-2)}.file-cell span{display:block;max-width:210px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.readonly-label{color:var(--cc-muted)}.departure-state{display:flex;align-items:center;gap:var(--admin-space-3);margin-top:var(--admin-space-4);padding-top:var(--admin-space-4);border-top:1px solid var(--cc-border);font-size:var(--admin-font-body)}.declaration-batches-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:var(--admin-space-4)}.declaration-batches-heading p{margin:3px 0 0;color:var(--cc-muted);font-size:var(--admin-font-caption)}.declaration-batch-list{display:grid;gap:var(--admin-space-3)}.declaration-batch-card{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:var(--admin-space-2) var(--admin-space-4);padding:var(--admin-space-3) var(--admin-space-4);border:1px solid var(--cc-border);background:var(--cc-surface-muted)}.declaration-batch-main strong,.declaration-batch-main span{display:block}.declaration-batch-main span{margin-top:4px;color:var(--cc-muted);font-size:var(--admin-font-caption)}.declaration-batch-actions,.declaration-result-list{grid-column:1 / -1}.declaration-result-list{display:grid;gap:5px;padding-top:var(--admin-space-2);border-top:1px solid var(--cc-border)}.declaration-result-row{display:flex;align-items:center;gap:var(--admin-space-2);font-size:var(--admin-font-caption)}.declaration-result-row small{flex:1;color:var(--cc-muted)}.clearance-result-form{padding-top:var(--admin-space-2)}.clearance-result-select{width:100%}
|
||||
</style>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useAuthStore } from '@/core/auth/auth'
|
||||
import { listPlatformFeeItems } from '@/modules/fee-items/api/platformFeeItems'
|
||||
import FeeItemsView from './FeeItemsView.vue'
|
||||
|
||||
const source = readFileSync(join(process.cwd(), 'src/modules/fee-items/pages/FeeItemsView.vue'), 'utf8')
|
||||
const source = readFileSync(join(process.cwd(), 'src/modules/fee-items/pages/FeeItemsView.vue'), 'utf8').replace(/\r\n/g, '\n')
|
||||
|
||||
vi.mock('@/modules/fee-items/api/platformFeeItems', () => ({
|
||||
listPlatformFeeItems: vi.fn(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const overseas = vi.hoisted(() => ({ get: vi.fn(), patch: vi.fn(), post: vi.fn(), put: vi.fn() }))
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: overseas }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: overseas }))
|
||||
|
||||
import {
|
||||
createLocalLooseboardOrder, createUsTruckOrder, getLocalLooseboardOrder, getOverseasPurchase, getUsTruckOrder,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import type {
|
||||
CreateLocalLooseboardOrderRequest, CreateLocalTransportOrderRequest, LocalLooseboardDetail, LocalLooseboardOrder,
|
||||
LocalLooseboardQuery, LocalTransportDetail, LocalTransportOrder, LocalTransportPallet, LocalTransportQuery,
|
||||
@@ -57,67 +57,67 @@ function looseboardDetail(value: LooseboardDetailPayload): LocalLooseboardDetail
|
||||
}
|
||||
|
||||
export async function listOverseasPurchaseCustomerOptions(keyword = '', limit = 200) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPurchaseCustomerOption[]>, ApiEnvelope<OverseasPurchaseCustomerOption[]>>(`${procurementBasePath}/customer-options`, { params: { keyword: keyword.trim() || undefined, limit } })
|
||||
const response = await http.get<ApiEnvelope<OverseasPurchaseCustomerOption[]>, ApiEnvelope<OverseasPurchaseCustomerOption[]>>(`${procurementBasePath}/customer-options`, { params: { keyword: keyword.trim() || undefined, limit } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function listOverseasPurchaseWarehouseOptions() {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPurchaseWarehouseOption[]>, ApiEnvelope<OverseasPurchaseWarehouseOption[]>>(`${procurementBasePath}/warehouse-options`)
|
||||
const response = await http.get<ApiEnvelope<OverseasPurchaseWarehouseOption[]>, ApiEnvelope<OverseasPurchaseWarehouseOption[]>>(`${procurementBasePath}/warehouse-options`)
|
||||
return unwrapApiResponse(response).map((item) => ({ ...item, warehouseId: String(item.warehouseId) }))
|
||||
}
|
||||
export async function listOverseasPurchases(query: OverseasPurchaseQuery = {}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<PagePayload<ProcurementSummaryPayload>>, ApiEnvelope<PagePayload<ProcurementSummaryPayload>>>(procurementBasePath, { params: { ...query, customerId: query.customerId || undefined, orderNo: query.orderNo?.trim() || undefined, customerKeyword: query.customerKeyword?.trim() || undefined, purchaseCategory: query.purchaseCategory?.trim() || undefined, productName: query.productName?.trim() || undefined, status: query.status || undefined, purchaseWarehouseId: query.purchaseWarehouseId || undefined } })
|
||||
const response = await http.get<ApiEnvelope<PagePayload<ProcurementSummaryPayload>>, ApiEnvelope<PagePayload<ProcurementSummaryPayload>>>(procurementBasePath, { params: { ...query, customerId: query.customerId || undefined, orderNo: query.orderNo?.trim() || undefined, customerKeyword: query.customerKeyword?.trim() || undefined, purchaseCategory: query.purchaseCategory?.trim() || undefined, productName: query.productName?.trim() || undefined, status: query.status || undefined, purchaseWarehouseId: query.purchaseWarehouseId || undefined } })
|
||||
return normalizePage(unwrapApiResponse(response), procurementSummary)
|
||||
}
|
||||
export async function getOverseasPurchase(orderNo: string, customerId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<ProcurementDetailPayload>, ApiEnvelope<ProcurementDetailPayload>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}`, { params: { customerId } })
|
||||
const response = await http.get<ApiEnvelope<ProcurementDetailPayload>, ApiEnvelope<ProcurementDetailPayload>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}`, { params: { customerId } })
|
||||
return procurementDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function updateOverseasPurchase(orderNo: string, customerId: string, payload: UpdateOverseasPurchaseRequest) {
|
||||
const response = await overseasHttp.patch<ApiEnvelope<ProcurementDetailPayload>, ApiEnvelope<ProcurementDetailPayload>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}`, payload, { params: { customerId } })
|
||||
const response = await http.patch<ApiEnvelope<ProcurementDetailPayload>, ApiEnvelope<ProcurementDetailPayload>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}`, payload, { params: { customerId } })
|
||||
return procurementDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function reviewOverseasPurchase(orderNo: string, customerId: string, payload: ReviewOverseasPurchaseRequest) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<ProcurementDetailPayload>, ApiEnvelope<ProcurementDetailPayload>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}/review`, payload, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<ProcurementDetailPayload>, ApiEnvelope<ProcurementDetailPayload>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}/review`, payload, { params: { customerId } })
|
||||
return procurementDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function uploadOverseasPurchaseFile(orderNo: string, customerId: string, category: 'RECEIPT' | 'VOUCHER', file: File) {
|
||||
const body = new FormData(); body.append('file', file)
|
||||
const response = await overseasHttp.post<ApiEnvelope<OverseasPurchaseFile>, ApiEnvelope<OverseasPurchaseFile>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}/files/${category}`, body, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<OverseasPurchaseFile>, ApiEnvelope<OverseasPurchaseFile>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}/files/${category}`, body, { params: { customerId } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function createOverseasPurchaseFee(orderNo: string, customerId: string, payload: { feeItemCode: string; feeItemName: string; amount: number; voucherFileId: string; remark?: string }) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<OverseasPurchaseFee>, ApiEnvelope<OverseasPurchaseFee>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}/fees`, payload, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<OverseasPurchaseFee>, ApiEnvelope<OverseasPurchaseFee>>(`${procurementBasePath}/${encodeURIComponent(orderNo)}/fees`, payload, { params: { customerId } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function listUsTruckOrders(query: LocalTransportQuery = {}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<PagePayload<TruckSummaryPayload>>, ApiEnvelope<PagePayload<TruckSummaryPayload>>>(truckBasePath, { params: { ...query, orderNo: query.orderNo?.trim() || undefined, routeKeyword: query.routeKeyword?.trim() || undefined, status: query.status || undefined, transportType: query.transportType || undefined, customerId: query.customerId || undefined } })
|
||||
const response = await http.get<ApiEnvelope<PagePayload<TruckSummaryPayload>>, ApiEnvelope<PagePayload<TruckSummaryPayload>>>(truckBasePath, { params: { ...query, orderNo: query.orderNo?.trim() || undefined, routeKeyword: query.routeKeyword?.trim() || undefined, status: query.status || undefined, transportType: query.transportType || undefined, customerId: query.customerId || undefined } })
|
||||
return normalizePage(unwrapApiResponse(response), truckSummary)
|
||||
}
|
||||
export async function getUsTruckOrder(orderNo: string, customerId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<TruckDetailPayload>, ApiEnvelope<TruckDetailPayload>>(`${truckBasePath}/${encodeURIComponent(orderNo)}`, { params: { customerId } })
|
||||
const response = await http.get<ApiEnvelope<TruckDetailPayload>, ApiEnvelope<TruckDetailPayload>>(`${truckBasePath}/${encodeURIComponent(orderNo)}`, { params: { customerId } })
|
||||
return truckDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function createUsTruckOrder(customerId: string, payload: CreateLocalTransportOrderRequest) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<TruckDetailPayload>, ApiEnvelope<TruckDetailPayload>>(truckBasePath, payload, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<TruckDetailPayload>, ApiEnvelope<TruckDetailPayload>>(truckBasePath, payload, { params: { customerId } })
|
||||
return truckDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function updateUsTruckOrder(orderNo: string, customerId: string, payload: UpdateLocalTransportOrderRequest) {
|
||||
const response = await overseasHttp.patch<ApiEnvelope<TruckDetailPayload>, ApiEnvelope<TruckDetailPayload>>(`${truckBasePath}/${encodeURIComponent(orderNo)}`, payload, { params: { customerId } })
|
||||
const response = await http.patch<ApiEnvelope<TruckDetailPayload>, ApiEnvelope<TruckDetailPayload>>(`${truckBasePath}/${encodeURIComponent(orderNo)}`, payload, { params: { customerId } })
|
||||
return truckDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function listLocalLooseboardOrders(query: LocalLooseboardQuery = {}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<PagePayload<LooseboardSummaryPayload>>, ApiEnvelope<PagePayload<LooseboardSummaryPayload>>>(looseboardBasePath, { params: { ...query, customerId: query.customerId || undefined, orderNo: query.orderNo?.trim() || undefined, routeKeyword: query.routeKeyword?.trim() || undefined, status: query.status || undefined, transportMode: query.transportMode || undefined } })
|
||||
const response = await http.get<ApiEnvelope<PagePayload<LooseboardSummaryPayload>>, ApiEnvelope<PagePayload<LooseboardSummaryPayload>>>(looseboardBasePath, { params: { ...query, customerId: query.customerId || undefined, orderNo: query.orderNo?.trim() || undefined, routeKeyword: query.routeKeyword?.trim() || undefined, status: query.status || undefined, transportMode: query.transportMode || undefined } })
|
||||
return normalizePage(unwrapApiResponse(response), looseboardSummary)
|
||||
}
|
||||
export async function getLocalLooseboardOrder(orderNo: string, customerId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<LooseboardDetailPayload>, ApiEnvelope<LooseboardDetailPayload>>(`${looseboardBasePath}/${encodeURIComponent(orderNo)}`, { params: { customerId } })
|
||||
const response = await http.get<ApiEnvelope<LooseboardDetailPayload>, ApiEnvelope<LooseboardDetailPayload>>(`${looseboardBasePath}/${encodeURIComponent(orderNo)}`, { params: { customerId } })
|
||||
return looseboardDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function createLocalLooseboardOrder(customerId: string, payload: CreateLocalLooseboardOrderRequest) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<LooseboardDetailPayload>, ApiEnvelope<LooseboardDetailPayload>>(looseboardBasePath, payload, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<LooseboardDetailPayload>, ApiEnvelope<LooseboardDetailPayload>>(looseboardBasePath, payload, { params: { customerId } })
|
||||
return looseboardDetail(unwrapApiResponse(response))
|
||||
}
|
||||
export async function updateLocalLooseboardOrder(orderNo: string, customerId: string, payload: UpdateLocalLooseboardOrderRequest) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<LooseboardDetailPayload>, ApiEnvelope<LooseboardDetailPayload>>(`${looseboardBasePath}/${encodeURIComponent(orderNo)}`, payload, { params: { customerId } })
|
||||
const response = await http.put<ApiEnvelope<LooseboardDetailPayload>, ApiEnvelope<LooseboardDetailPayload>>(`${looseboardBasePath}/${encodeURIComponent(orderNo)}`, payload, { params: { customerId } })
|
||||
return looseboardDetail(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ApiResponseError } from '@/shared/api/http'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { ApiResponseError, http } from '@/shared/api/http'
|
||||
|
||||
import {
|
||||
changeExchangeRateStatus, changeQuoteStatus, changeVehicleStatus, createExchangeRate, createQuote, createVehicle,
|
||||
exportExchangeRates, exportQuotes, exportVehicles, getExchangeRate, getExchangeRateSummary, getQuote, getVehicle,
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type QuoteCreate, type QuoteUpdate,
|
||||
} from './overseasMasterData'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } }))
|
||||
const ok = (data: unknown) => ({ code: '200', message: 'success', data })
|
||||
const longId = '9223372036854775807'
|
||||
const quoteSummary = {
|
||||
@@ -29,7 +29,7 @@ beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
describe('overseas master data API', () => {
|
||||
it('normalizes quote page/detail decimals and preserves long string IDs', async () => {
|
||||
vi.mocked(overseasHttp.get)
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce(ok({ records: [quoteSummary], page: '1', size: '20', total: '1', pages: '1' }))
|
||||
.mockResolvedValueOnce(ok(quoteDetail))
|
||||
.mockResolvedValueOnce(ok([{ warehouseId: quoteSummary.warehouseId, warehouseCode: 'US-LAX', warehouseName: '洛杉矶合作仓', countryCode: 'US' }]))
|
||||
@@ -44,9 +44,9 @@ describe('overseas master data API', () => {
|
||||
expect(detail.transitPrices[0]).toMatchObject({ estimatedMiles: 12.5, price: 18.75, minimumCharge: null })
|
||||
await listQuoteWarehouseOptions()
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/master-data/overseas-quotes', { params: { page: 1, size: 20, keyword: 'V1' } })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, `/platform/v1/last-leg/master-data/overseas-quotes/${longId}`)
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(3, '/platform/v1/last-leg/master-data/overseas-quotes/warehouse-options')
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/master-data/overseas-quotes', { params: { page: 1, size: 20, keyword: 'V1' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, `/platform/v1/last-leg/master-data/overseas-quotes/${longId}`)
|
||||
expect(http.get).toHaveBeenNthCalledWith(3, '/platform/v1/last-leg/master-data/overseas-quotes/warehouse-options')
|
||||
})
|
||||
|
||||
it('keeps quote create/update DTOs distinct and sends recordVersion on writes', async () => {
|
||||
@@ -60,24 +60,24 @@ describe('overseas master data API', () => {
|
||||
name: '报价-编辑', providerName: '服务商', currency: 'USD', effectiveStart: '2026-08-01', effectiveEnd: '2026-12-31',
|
||||
warehouseFees: create.warehouseFees, transitPrices: [], remark: null, recordVersion: 7,
|
||||
}
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue(ok(quoteDetail))
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue(ok({ ...quoteDetail, summary: { ...quoteSummary, recordVersion: '8' } }))
|
||||
vi.mocked(overseasHttp.patch).mockResolvedValue(ok({ ...quoteDetail, summary: { ...quoteSummary, status: 'ACTIVE', recordVersion: '9' } }))
|
||||
vi.mocked(http.post).mockResolvedValue(ok(quoteDetail))
|
||||
vi.mocked(http.put).mockResolvedValue(ok({ ...quoteDetail, summary: { ...quoteSummary, recordVersion: '8' } }))
|
||||
vi.mocked(http.patch).mockResolvedValue(ok({ ...quoteDetail, summary: { ...quoteSummary, status: 'ACTIVE', recordVersion: '9' } }))
|
||||
|
||||
await createQuote(create)
|
||||
const updated = await updateQuote(longId, update)
|
||||
await changeQuoteStatus(longId, 'ACTIVE', 8)
|
||||
|
||||
expect(updated.summary.recordVersion).toBe(8)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/master-data/overseas-quotes', create)
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/overseas-quotes/${longId}`, update)
|
||||
expect(overseasHttp.patch).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/overseas-quotes/${longId}/status`, { status: 'ACTIVE', recordVersion: 8 })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/master-data/overseas-quotes', create)
|
||||
expect(http.put).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/overseas-quotes/${longId}`, update)
|
||||
expect(http.patch).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/overseas-quotes/${longId}/status`, { status: 'ACTIVE', recordVersion: 8 })
|
||||
expect(update).not.toHaveProperty('warehouseId')
|
||||
expect(update).not.toHaveProperty('versionCode')
|
||||
})
|
||||
|
||||
it('normalizes exchange-rate decimal/version and uses month as the stable key', async () => {
|
||||
vi.mocked(overseasHttp.get)
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce(ok({ records: [exchangeRate], page: '1', size: '20', total: '1', pages: '1' }))
|
||||
.mockResolvedValueOnce(ok(exchangeRate))
|
||||
.mockResolvedValueOnce(ok({ latestMonth: '2026-08', latestUsdToCnyAverage: '7.12345678', updatedBy: 'admin', updatedAt: '2026-08-24T10:00:00' }))
|
||||
@@ -88,17 +88,17 @@ describe('overseas master data API', () => {
|
||||
expect(detail).toMatchObject({ month: '2026-08', usdToCnyAverage: 7.12345678, recordVersion: 3 })
|
||||
expect(summary.latestUsdToCnyAverage).toBe(7.12345678)
|
||||
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue(ok(exchangeRate))
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue(ok({ ...exchangeRate, recordVersion: '4' }))
|
||||
vi.mocked(overseasHttp.patch).mockResolvedValue(ok({ ...exchangeRate, status: 'INACTIVE', recordVersion: '5' }))
|
||||
vi.mocked(http.post).mockResolvedValue(ok(exchangeRate))
|
||||
vi.mocked(http.put).mockResolvedValue(ok({ ...exchangeRate, recordVersion: '4' }))
|
||||
vi.mocked(http.patch).mockResolvedValue(ok({ ...exchangeRate, status: 'INACTIVE', recordVersion: '5' }))
|
||||
await createExchangeRate({ month: '2026-08', usdToCnyAverage: 7.12345678, remark: null })
|
||||
await updateExchangeRate('2026-08', { recordVersion: 3, usdToCnyAverage: 7.2, remark: null })
|
||||
await changeExchangeRateStatus('2026-08', 'INACTIVE', 4, '停用')
|
||||
expect(overseasHttp.patch).toHaveBeenLastCalledWith('/platform/v1/last-leg/master-data/exchange-rates/2026-08/status', { status: 'INACTIVE', recordVersion: 4, remark: '停用' })
|
||||
expect(http.patch).toHaveBeenLastCalledWith('/platform/v1/last-leg/master-data/exchange-rates/2026-08/status', { status: 'INACTIVE', recordVersion: 4, remark: '停用' })
|
||||
})
|
||||
|
||||
it('normalizes vehicle decimals/version while preserving long string IDs', async () => {
|
||||
vi.mocked(overseasHttp.get)
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce(ok({ records: [vehicle], page: '1', size: '20', total: '1', pages: '1' }))
|
||||
.mockResolvedValueOnce(ok(vehicle))
|
||||
const result = await listVehicles({ page: 1, size: 20, ownership: 'OWNED' })
|
||||
@@ -107,18 +107,18 @@ describe('overseas master data API', () => {
|
||||
expect(detail.id).toBe(longId)
|
||||
|
||||
const editable = { plateNumber: 'CA-01', model: 'Truck', fuelConsumptionPer100Km: 12.5, mileageKm: 101, driverOrDispatchCompany: null, phone: null, region: 'OVERSEAS' as const, ownership: 'OWNED' as const, remark: null }
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue(ok(vehicle))
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue(ok({ ...vehicle, recordVersion: '5' }))
|
||||
vi.mocked(overseasHttp.patch).mockResolvedValue(ok({ ...vehicle, status: 'INACTIVE', recordVersion: '6' }))
|
||||
vi.mocked(http.post).mockResolvedValue(ok(vehicle))
|
||||
vi.mocked(http.put).mockResolvedValue(ok({ ...vehicle, recordVersion: '5' }))
|
||||
vi.mocked(http.patch).mockResolvedValue(ok({ ...vehicle, status: 'INACTIVE', recordVersion: '6' }))
|
||||
await createVehicle({ ...editable, status: 'IN_SERVICE' })
|
||||
await updateVehicle(longId, { ...editable, recordVersion: 4 })
|
||||
await changeVehicleStatus(longId, 'INACTIVE', 5)
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/vehicles/${longId}`, { ...editable, recordVersion: 4 })
|
||||
expect(overseasHttp.patch).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/vehicles/${longId}/status`, { status: 'INACTIVE', recordVersion: 5 })
|
||||
expect(http.put).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/vehicles/${longId}`, { ...editable, recordVersion: 4 })
|
||||
expect(http.patch).toHaveBeenCalledWith(`/platform/v1/last-leg/master-data/vehicles/${longId}/status`, { status: 'INACTIVE', recordVersion: 5 })
|
||||
})
|
||||
|
||||
it('preserves A0409 metadata instead of translating it into success', async () => {
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: 'A0409', message: '记录版本已变化', data: null, requestId: 'request-conflict', traceId: 'trace-conflict' })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: 'A0409', message: '记录版本已变化', data: null, requestId: 'request-conflict', traceId: 'trace-conflict' })
|
||||
const error = await updateExchangeRate('2026-08', { recordVersion: 1, usdToCnyAverage: 7.2, remark: null }).catch((reason: unknown) => reason)
|
||||
expect(error).toBeInstanceOf(ApiResponseError)
|
||||
expect(error).toMatchObject({ code: 'A0409', message: '记录版本已变化', requestId: 'request-conflict', traceId: 'trace-conflict' })
|
||||
@@ -126,7 +126,7 @@ describe('overseas master data API', () => {
|
||||
|
||||
it('downloads real CSV Blobs and rejects JSON error Blobs with trace metadata', async () => {
|
||||
const csv = new Blob(['id,status\n1,ACTIVE\n'], { type: 'text/csv;charset=UTF-8' })
|
||||
vi.mocked(overseasHttp.get)
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce(csv)
|
||||
.mockResolvedValueOnce(csv)
|
||||
.mockResolvedValueOnce(csv)
|
||||
@@ -138,8 +138,8 @@ describe('overseas master data API', () => {
|
||||
const error = await exportVehicles({}).catch((reason: unknown) => reason)
|
||||
expect(error).toBeInstanceOf(ApiResponseError)
|
||||
expect(error).toMatchObject({ code: 'A0409', message: '导出条件已变化', requestId: 'request-export' })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/master-data/overseas-quotes/export', { params: { status: 'ACTIVE' }, responseType: 'arraybuffer' })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/master-data/exchange-rates/export', { params: {}, responseType: 'arraybuffer' })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(3, '/platform/v1/last-leg/master-data/vehicles/export', { params: { ownership: 'OWNED' }, responseType: 'arraybuffer' })
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/master-data/overseas-quotes/export', { params: { status: 'ACTIVE' }, responseType: 'arraybuffer' })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/master-data/exchange-rates/export', { params: {}, responseType: 'arraybuffer' })
|
||||
expect(http.get).toHaveBeenNthCalledWith(3, '/platform/v1/last-leg/master-data/vehicles/export', { params: { ownership: 'OWNED' }, responseType: 'arraybuffer' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import axios from 'axios'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { ApiResponseError, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, ApiResponseError, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import type {
|
||||
MasterDataStatus, MonthlyExchangeRate, OverseasTransitPrice, OverseasWarehouseFee, OverseasWarehouseQuote, OverseasWarehouseQuoteDetail, PartnerWarehouseOption,
|
||||
VehicleDetail, VehicleOwnership, VehicleRegion, VehicleStatus,
|
||||
@@ -23,7 +23,7 @@ function page<T, W>(value: PagePayload<W>, normalize: (record: W) => T): PageRes
|
||||
return { ...value, records: value.records.map(normalize), page: Number(value.page), size: Number(value.size), total: Number(value.total), pages: Number(value.pages) }
|
||||
}
|
||||
async function getPage<T, W>(path: string, params: object, normalize: (record: W) => T) {
|
||||
return page(unwrapApiResponse(await overseasHttp.get<ApiEnvelope<PagePayload<W>>, ApiEnvelope<PagePayload<W>>>(path, { params })), normalize)
|
||||
return page(unwrapApiResponse(await http.get<ApiEnvelope<PagePayload<W>>, ApiEnvelope<PagePayload<W>>>(path, { params })), normalize)
|
||||
}
|
||||
const numeric = (value: Numeric) => Number(value)
|
||||
const nullableNumeric = (value: Numeric | null) => value == null ? null : Number(value)
|
||||
@@ -71,7 +71,7 @@ function csvBlob(payload: DownloadPayload) {
|
||||
}
|
||||
async function download(path: string, params: object) {
|
||||
try {
|
||||
const payload = await overseasHttp.get<DownloadPayload, DownloadPayload>(path, { params, responseType: 'arraybuffer' })
|
||||
const payload = await http.get<DownloadPayload, DownloadPayload>(path, { params, responseType: 'arraybuffer' })
|
||||
const error = await csvError(payload, 200)
|
||||
if (error) throw error
|
||||
return csvBlob(payload)
|
||||
@@ -93,23 +93,23 @@ type QuoteEditableFields = Pick<OverseasWarehouseQuote, 'name' | 'providerName'
|
||||
export type QuoteCreate = QuoteEditableFields & Pick<OverseasWarehouseQuote, 'warehouseId' | 'versionCode'>
|
||||
export type QuoteUpdate = QuoteEditableFields & Pick<OverseasWarehouseQuote, 'recordVersion'>
|
||||
export const listQuotes = (query: QuoteQuery) => getPage<OverseasWarehouseQuote, QuoteWire>(`${base}/overseas-quotes`, query, normalizeQuote)
|
||||
export async function getQuote(id: string) { return normalizeQuoteDetail(unwrapApiResponse(await overseasHttp.get<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes/${encodeURIComponent(id)}`))) }
|
||||
export async function listQuoteWarehouseOptions() { return unwrapApiResponse(await overseasHttp.get<ApiEnvelope<PartnerWarehouseOption[]>, ApiEnvelope<PartnerWarehouseOption[]>>(`${base}/overseas-quotes/warehouse-options`)) }
|
||||
export async function createQuote(payload: QuoteCreate) { return normalizeQuoteDetail(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes`, payload))) }
|
||||
export async function updateQuote(id: string, payload: QuoteUpdate) { return normalizeQuoteDetail(unwrapApiResponse(await overseasHttp.put<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes/${encodeURIComponent(id)}`, payload))) }
|
||||
export async function changeQuoteStatus(id: string, status: MasterDataStatus, recordVersion: number) { return normalizeQuoteDetail(unwrapApiResponse(await overseasHttp.patch<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes/${encodeURIComponent(id)}/status`, { status, recordVersion }))) }
|
||||
export async function getQuote(id: string) { return normalizeQuoteDetail(unwrapApiResponse(await http.get<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes/${encodeURIComponent(id)}`))) }
|
||||
export async function listQuoteWarehouseOptions() { return unwrapApiResponse(await http.get<ApiEnvelope<PartnerWarehouseOption[]>, ApiEnvelope<PartnerWarehouseOption[]>>(`${base}/overseas-quotes/warehouse-options`)) }
|
||||
export async function createQuote(payload: QuoteCreate) { return normalizeQuoteDetail(unwrapApiResponse(await http.post<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes`, payload))) }
|
||||
export async function updateQuote(id: string, payload: QuoteUpdate) { return normalizeQuoteDetail(unwrapApiResponse(await http.put<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes/${encodeURIComponent(id)}`, payload))) }
|
||||
export async function changeQuoteStatus(id: string, status: MasterDataStatus, recordVersion: number) { return normalizeQuoteDetail(unwrapApiResponse(await http.patch<ApiEnvelope<QuoteDetailWire>, ApiEnvelope<QuoteDetailWire>>(`${base}/overseas-quotes/${encodeURIComponent(id)}/status`, { status, recordVersion }))) }
|
||||
export const exportQuotes = (query: Omit<QuoteQuery, 'page' | 'size'>) => download(`${base}/overseas-quotes/export`, query)
|
||||
|
||||
export interface ExchangeRateQuery { page: number; size: number; monthFrom?: string; monthTo?: string; status?: MasterDataStatus }
|
||||
export const listExchangeRates = (query: ExchangeRateQuery) => getPage<MonthlyExchangeRate, ExchangeRateWire>(`${base}/exchange-rates`, query, normalizeExchangeRate)
|
||||
export async function getExchangeRate(month: string) { return normalizeExchangeRate(unwrapApiResponse(await overseasHttp.get<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates/${encodeURIComponent(month)}`))) }
|
||||
export async function getExchangeRate(month: string) { return normalizeExchangeRate(unwrapApiResponse(await http.get<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates/${encodeURIComponent(month)}`))) }
|
||||
export async function getExchangeRateSummary(): Promise<ExchangeRateSummary> {
|
||||
const value = unwrapApiResponse(await overseasHttp.get<ApiEnvelope<ExchangeRateSummaryWire>, ApiEnvelope<ExchangeRateSummaryWire>>(`${base}/exchange-rates/summary`))
|
||||
const value = unwrapApiResponse(await http.get<ApiEnvelope<ExchangeRateSummaryWire>, ApiEnvelope<ExchangeRateSummaryWire>>(`${base}/exchange-rates/summary`))
|
||||
return { ...value, latestUsdToCnyAverage: nullableNumeric(value.latestUsdToCnyAverage) }
|
||||
}
|
||||
export async function createExchangeRate(payload: { month: string; usdToCnyAverage: number; remark: string | null }) { return normalizeExchangeRate(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates`, payload))) }
|
||||
export async function updateExchangeRate(month: string, payload: { recordVersion: number; usdToCnyAverage: number; remark: string | null }) { return normalizeExchangeRate(unwrapApiResponse(await overseasHttp.put<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates/${encodeURIComponent(month)}`, payload))) }
|
||||
export async function changeExchangeRateStatus(month: string, status: MasterDataStatus, recordVersion: number, remark: string | null) { return normalizeExchangeRate(unwrapApiResponse(await overseasHttp.patch<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates/${encodeURIComponent(month)}/status`, { status, recordVersion, remark }))) }
|
||||
export async function createExchangeRate(payload: { month: string; usdToCnyAverage: number; remark: string | null }) { return normalizeExchangeRate(unwrapApiResponse(await http.post<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates`, payload))) }
|
||||
export async function updateExchangeRate(month: string, payload: { recordVersion: number; usdToCnyAverage: number; remark: string | null }) { return normalizeExchangeRate(unwrapApiResponse(await http.put<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates/${encodeURIComponent(month)}`, payload))) }
|
||||
export async function changeExchangeRateStatus(month: string, status: MasterDataStatus, recordVersion: number, remark: string | null) { return normalizeExchangeRate(unwrapApiResponse(await http.patch<ApiEnvelope<ExchangeRateWire>, ApiEnvelope<ExchangeRateWire>>(`${base}/exchange-rates/${encodeURIComponent(month)}/status`, { status, recordVersion, remark }))) }
|
||||
export const exportExchangeRates = (query: Omit<ExchangeRateQuery, 'page' | 'size'>) => download(`${base}/exchange-rates/export`, query)
|
||||
|
||||
export interface VehicleQuery { page: number; size: number; keyword?: string; ownership?: VehicleOwnership; region?: VehicleRegion; status?: VehicleStatus }
|
||||
@@ -117,8 +117,8 @@ type VehicleEditableFields = Omit<VehicleDetail, 'id' | 'recordVersion' | 'updat
|
||||
export type VehicleCreate = VehicleEditableFields & Pick<VehicleDetail, 'status'>
|
||||
export type VehicleUpdate = VehicleEditableFields & Pick<VehicleDetail, 'recordVersion'>
|
||||
export const listVehicles = (query: VehicleQuery) => getPage<VehicleDetail, VehicleWire>(`${base}/vehicles`, query, normalizeVehicle)
|
||||
export async function getVehicle(id: string) { return normalizeVehicle(unwrapApiResponse(await overseasHttp.get<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles/${encodeURIComponent(id)}`))) }
|
||||
export async function createVehicle(payload: VehicleCreate) { return normalizeVehicle(unwrapApiResponse(await overseasHttp.post<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles`, payload))) }
|
||||
export async function updateVehicle(id: string, payload: VehicleUpdate) { return normalizeVehicle(unwrapApiResponse(await overseasHttp.put<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles/${encodeURIComponent(id)}`, payload))) }
|
||||
export async function changeVehicleStatus(id: string, status: VehicleStatus, recordVersion: number) { return normalizeVehicle(unwrapApiResponse(await overseasHttp.patch<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles/${encodeURIComponent(id)}/status`, { status, recordVersion }))) }
|
||||
export async function getVehicle(id: string) { return normalizeVehicle(unwrapApiResponse(await http.get<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles/${encodeURIComponent(id)}`))) }
|
||||
export async function createVehicle(payload: VehicleCreate) { return normalizeVehicle(unwrapApiResponse(await http.post<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles`, payload))) }
|
||||
export async function updateVehicle(id: string, payload: VehicleUpdate) { return normalizeVehicle(unwrapApiResponse(await http.put<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles/${encodeURIComponent(id)}`, payload))) }
|
||||
export async function changeVehicleStatus(id: string, status: VehicleStatus, recordVersion: number) { return normalizeVehicle(unwrapApiResponse(await http.patch<ApiEnvelope<VehicleWire>, ApiEnvelope<VehicleWire>>(`${base}/vehicles/${encodeURIComponent(id)}/status`, { status, recordVersion }))) }
|
||||
export const exportVehicles = (query: Omit<VehicleQuery, 'page' | 'size'>) => download(`${base}/vehicles/export`, query)
|
||||
|
||||
@@ -5,7 +5,7 @@ withDefaults(defineProps<{ domain: string; detail?: boolean }>(), { detail: fals
|
||||
<template>
|
||||
<el-alert class="contract-pending" type="warning" :closable="false" show-icon>
|
||||
<template #title>{{ domain }}海外区域接口待接入</template>
|
||||
<p>{{ detail ? '当前详情没有可查询的真实记录。' : '页面已按四期原型冻结字段与布局。' }}海外请求统一经 gateway-overseas;在统一 Base/Token 选择及本页面端点、DTO 与权限适配完成前,不展示演示数据,也不会模拟查询或写操作成功。</p>
|
||||
<p>当前功能尚未完成接口接入,暂不可操作。</p>
|
||||
</el-alert>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
- 本文件适用于 `src/modules/overseas-warehouse/`,路径默认相对此目录;其他模块以 `../` 开头。应用公共规则见 `../../../AGENTS.md`。
|
||||
- 先按下表定位页面,再沿 `routes.ts`、页面 import 与 `api/` 追踪;页面是否开放以正式路由、权限和测试为准。后台接口与状态进入 `../../../../../baiyue-firstleg/lastleg-service/AGENTS.md`,不扩大扫描其他业务模块。
|
||||
- 请求统一使用 `../../shared/api/overseasHttp.ts`;不以 `PROTOTYPE_MATRIX.md` 或 `CONTRACT_GAPS.md` 代替代码与服务端契约。
|
||||
- 请求统一使用 `../../shared/api/http.ts`;不以 `PROTOTYPE_MATRIX.md` 或 `CONTRACT_GAPS.md` 代替代码与服务端契约。
|
||||
|
||||
## 页面与业务快速索引
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
getCustomerVisit,
|
||||
listCustomerVisits,
|
||||
@@ -8,45 +8,45 @@ import {
|
||||
uploadCustomerVisitAttachment,
|
||||
} from './customerVisits'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
|
||||
describe('customer visit API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(overseasHttp.get).mockReset()
|
||||
vi.mocked(overseasHttp.post).mockReset()
|
||||
vi.mocked(overseasHttp.put).mockReset()
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
})
|
||||
|
||||
it('loads the customer visit page and detail in customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce({ code: '200', data: { records: [], current: 1, size: 10, total: 0, pages: 0, visitable: 3, pending: 2, completed: 1 } })
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', data: { records: [], current: 1, size: 10, total: 0, pages: 0, visitable: 3, pending: 2, completed: 1 } })
|
||||
await listCustomerVisits({ page: 1, size: 10, keyword: 'DEL' })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/customer-visits', { params: { page: 1, size: 10, keyword: 'DEL' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/customer-visits', { params: { page: 1, size: 10, keyword: 'DEL' } })
|
||||
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce({ code: '200', data: { visit: { id: '9' }, inboundOrders: [] } })
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', data: { visit: { id: '9' }, inboundOrders: [] } })
|
||||
await getCustomerVisit('9', '100')
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/customer-visits/9', { params: { customerId: '100' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/customer-visits/9', { params: { customerId: '100' } })
|
||||
})
|
||||
|
||||
it('updates a delivery to an operator-managed nonterminal status', async () => {
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', data: { deliveryStatus: 'DELIVERING' } })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', data: { deliveryStatus: 'DELIVERING' } })
|
||||
await updateDeliveryOrderStatus('DEL/1', '100', { status: 'DELIVERING', expectedVersion: 7, remark: '开始派送' })
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1/status', { status: 'DELIVERING', expectedVersion: 7, remark: '开始派送' }, { params: { customerId: '100' } })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1/status', { status: 'DELIVERING', expectedVersion: 7, remark: '开始派送' }, { params: { customerId: '100' } })
|
||||
})
|
||||
|
||||
it('uploads and saves repeatable visit material', async () => {
|
||||
const file = new File(['data'], 'visit.pdf', { type: 'application/pdf' })
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: { fileId: '8', fileName: 'visit.pdf', sizeBytes: 4 } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: { fileId: '8', fileName: 'visit.pdf', sizeBytes: 4 } })
|
||||
await uploadCustomerVisitAttachment('9', '100', file)
|
||||
const body = vi.mocked(overseasHttp.post).mock.calls[0]?.[1] as FormData
|
||||
const body = vi.mocked(http.post).mock.calls[0]?.[1] as FormData
|
||||
expect(body.get('file')).toBe(file)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith(
|
||||
expect(http.post).toHaveBeenCalledWith(
|
||||
'/platform/v1/last-leg/customer-visits/9/attachments',
|
||||
body,
|
||||
{ params: { customerId: '100' }, headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
)
|
||||
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', data: { visit: { id: '9' }, inboundOrders: [] } })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', data: { visit: { id: '9' }, inboundOrders: [] } })
|
||||
await saveCustomerVisit('9', '100', { selectedInboundOrderId: '7', visitResult: 'NORMAL', attachments: [] })
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/customer-visits/9', expect.objectContaining({ selectedInboundOrderId: '7' }), { params: { customerId: '100' } })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/customer-visits/9', expect.objectContaining({ selectedInboundOrderId: '7' }), { params: { customerId: '100' } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
|
||||
export interface CustomerVisitAttachment {
|
||||
fileId: string
|
||||
@@ -63,14 +63,14 @@ export async function listCustomerVisits(params: {
|
||||
completedFrom?: string
|
||||
completedTo?: string
|
||||
}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<CustomerVisitPage>, ApiEnvelope<CustomerVisitPage>>(
|
||||
const response = await http.get<ApiEnvelope<CustomerVisitPage>, ApiEnvelope<CustomerVisitPage>>(
|
||||
'/platform/v1/last-leg/customer-visits', { params },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function getCustomerVisit(visitId: string, customerId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<CustomerVisitDetail>, ApiEnvelope<CustomerVisitDetail>>(
|
||||
const response = await http.get<ApiEnvelope<CustomerVisitDetail>, ApiEnvelope<CustomerVisitDetail>>(
|
||||
`/platform/v1/last-leg/customer-visits/${encodeURIComponent(visitId)}`, { params: { customerId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
@@ -83,7 +83,7 @@ export async function saveCustomerVisit(visitId: string, customerId: string, pay
|
||||
remark?: string
|
||||
attachments: CustomerVisitAttachment[]
|
||||
}) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<CustomerVisitDetail>, ApiEnvelope<CustomerVisitDetail>>(
|
||||
const response = await http.put<ApiEnvelope<CustomerVisitDetail>, ApiEnvelope<CustomerVisitDetail>>(
|
||||
`/platform/v1/last-leg/customer-visits/${encodeURIComponent(visitId)}`, payload, { params: { customerId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
@@ -92,7 +92,7 @@ export async function saveCustomerVisit(visitId: string, customerId: string, pay
|
||||
export async function uploadCustomerVisitAttachment(visitId: string, customerId: string, file: File) {
|
||||
const body = new FormData()
|
||||
body.append('file', file)
|
||||
const response = await overseasHttp.post<ApiEnvelope<CustomerVisitAttachment>, ApiEnvelope<CustomerVisitAttachment>>(
|
||||
const response = await http.post<ApiEnvelope<CustomerVisitAttachment>, ApiEnvelope<CustomerVisitAttachment>>(
|
||||
`/platform/v1/last-leg/customer-visits/${encodeURIComponent(visitId)}/attachments`, body,
|
||||
{ params: { customerId }, headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
)
|
||||
@@ -100,7 +100,7 @@ export async function uploadCustomerVisitAttachment(visitId: string, customerId:
|
||||
}
|
||||
|
||||
export async function updateDeliveryOrderStatus(deliveryNo: string, customerId: string, payload: { status: string; expectedVersion: number; remark?: string }) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<{ visitId?: string | null; deliveryNo: string; deliveryStatus: string; visitStatus?: string | null; replayed: boolean }>, ApiEnvelope<{ visitId?: string | null; deliveryNo: string; deliveryStatus: string; visitStatus?: string | null; replayed: boolean }>>(
|
||||
const response = await http.put<ApiEnvelope<{ visitId?: string | null; deliveryNo: string; deliveryStatus: string; visitStatus?: string | null; replayed: boolean }>, ApiEnvelope<{ visitId?: string | null; deliveryNo: string; deliveryStatus: string; visitStatus?: string | null; replayed: boolean }>>(
|
||||
`/platform/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}/status`, payload,
|
||||
{ params: { customerId } },
|
||||
)
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { deliveryDocumentCategories, getDeliveryDocuments, saveDeliveryDocuments, uploadDeliveryDocument, downloadDeliveryDocument } from './deliveryDocuments'
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
describe('delivery document API', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
it('scopes reads and full three-category snapshots by customer and delivery number', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: {} })
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', data: {} })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: {} })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', data: {} })
|
||||
await getDeliveryDocuments('DL/1', '9007199254740993')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DL%2F1/documents', { params: { customerId: '9007199254740993' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DL%2F1/documents', { params: { customerId: '9007199254740993' } })
|
||||
const body = { expectedVersion: 8, idempotencyKey: 'save-1', bolNo: null, documents: deliveryDocumentCategories.map(item => ({ category: item.category, fileIds: [] })) }
|
||||
await saveDeliveryDocuments('DL/1', '9007199254740993', body)
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DL%2F1/documents', body, { params: { customerId: '9007199254740993' } })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DL%2F1/documents', body, { params: { customerId: '9007199254740993' } })
|
||||
})
|
||||
it('uploads only the file and downloads through the authenticated category endpoint', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: { fileId: '9007199254740995' } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: { fileId: '9007199254740995' } })
|
||||
const file = new File(['data'], 'proof.bin')
|
||||
await uploadDeliveryDocument('DL/1', '100', 'RECEIPT', file)
|
||||
const [url, body, config] = vi.mocked(overseasHttp.post).mock.calls[0]!
|
||||
const [url, body, config] = vi.mocked(http.post).mock.calls[0]!
|
||||
expect(url).toBe('/platform/v1/last-leg/delivery-orders/DL%2F1/documents/RECEIPT/files')
|
||||
expect(Array.from((body as FormData).keys())).toEqual(['file'])
|
||||
expect((body as FormData).get('file')).toBe(file)
|
||||
expect(config).toEqual({ params: { customerId: '100' } })
|
||||
await downloadDeliveryDocument('DL/1', '100', 'RECEIPT', '9007199254740995')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DL%2F1/documents/RECEIPT/files/9007199254740995/download', { params: { customerId: '100' }, responseType: 'blob' })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DL%2F1/documents/RECEIPT/files/9007199254740995/download', { params: { customerId: '100' }, responseType: 'blob' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
|
||||
export const deliveryDocumentCategories = [
|
||||
{ category: 'LOADING_PHOTO', label: '装车照片' },
|
||||
@@ -18,16 +18,16 @@ export interface DeliveryDocuments extends DeliveryDocumentSummary {
|
||||
export interface SaveDeliveryDocuments { expectedVersion: number; idempotencyKey: string; bolNo: string | null; documents: Array<{ category: DeliveryDocumentCategory; fileIds: string[] }> }
|
||||
const path = (deliveryNo: string) => `/platform/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}/documents`
|
||||
export async function getDeliveryDocuments(deliveryNo: string, customerId: string) {
|
||||
return unwrapApiResponse(await overseasHttp.get<ApiEnvelope<DeliveryDocuments>, ApiEnvelope<DeliveryDocuments>>(path(deliveryNo), { params: { customerId } }))
|
||||
return unwrapApiResponse(await http.get<ApiEnvelope<DeliveryDocuments>, ApiEnvelope<DeliveryDocuments>>(path(deliveryNo), { params: { customerId } }))
|
||||
}
|
||||
export async function saveDeliveryDocuments(deliveryNo: string, customerId: string, body: SaveDeliveryDocuments) {
|
||||
return unwrapApiResponse(await overseasHttp.put<ApiEnvelope<DeliveryDocuments>, ApiEnvelope<DeliveryDocuments>>(path(deliveryNo), body, { params: { customerId } }))
|
||||
return unwrapApiResponse(await http.put<ApiEnvelope<DeliveryDocuments>, ApiEnvelope<DeliveryDocuments>>(path(deliveryNo), body, { params: { customerId } }))
|
||||
}
|
||||
export async function uploadDeliveryDocument(deliveryNo: string, customerId: string, category: DeliveryDocumentCategory, file: File) {
|
||||
const body = new FormData()
|
||||
body.append('file', file)
|
||||
return unwrapApiResponse(await overseasHttp.post<ApiEnvelope<DeliveryDocumentFile>, ApiEnvelope<DeliveryDocumentFile>>(`${path(deliveryNo)}/${category}/files`, body, { params: { customerId } }))
|
||||
return unwrapApiResponse(await http.post<ApiEnvelope<DeliveryDocumentFile>, ApiEnvelope<DeliveryDocumentFile>>(`${path(deliveryNo)}/${category}/files`, body, { params: { customerId } }))
|
||||
}
|
||||
export async function downloadDeliveryDocument(deliveryNo: string, customerId: string, category: DeliveryDocumentCategory, fileId: string) {
|
||||
return overseasHttp.get<Blob, Blob>(`${path(deliveryNo)}/${category}/files/${encodeURIComponent(fileId)}/download`, { params: { customerId }, responseType: 'blob' })
|
||||
return http.get<Blob, Blob>(`${path(deliveryNo)}/${category}/files/${encodeURIComponent(fileId)}/download`, { params: { customerId }, responseType: 'blob' })
|
||||
}
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { getDeliveryOrder, listDeliveryOrders, listDeliveryReturnInboundOptions, markDeliveryReturn } from './deliveryOrders'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn() } }))
|
||||
|
||||
describe('delivery order API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(overseasHttp.get).mockReset()
|
||||
vi.mocked(overseasHttp.post).mockReset()
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
})
|
||||
|
||||
it('passes paging and expanded filters and normalizes page numbers', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { records: [], page: '2', size: '20', total: '41', pages: '3' } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { records: [], page: '2', size: '20', total: '41', pages: '3' } })
|
||||
const result = await listDeliveryOrders({ page: 2, size: 20, documentNo: 'DEL-1', vehiclePlate: 'CA-1' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders', { params: { page: 2, size: 20, documentNo: 'DEL-1', vehiclePlate: 'CA-1' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders', { params: { page: 2, size: 20, documentNo: 'DEL-1', vehiclePlate: 'CA-1' } })
|
||||
expect(result).toMatchObject({ page: 2, size: 20, total: 41, pages: 3 })
|
||||
})
|
||||
|
||||
it('loads an encoded detail in its explicit customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { order: { deliveryNo: 'DEL/1', version: '0' }, skus: [], fees: [], operations: [] } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { order: { deliveryNo: 'DEL/1', version: '0' }, skus: [], fees: [], operations: [] } })
|
||||
await getDeliveryOrder('DEL/1', '1001')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1', { params: { customerId: '1001', page: 1, size: 200 } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1', { params: { customerId: '1001', page: 1, size: 200 } })
|
||||
})
|
||||
|
||||
it.each(['0', '7', '9007199254740991'])('reads Java Long version %s for status editing', async version => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { order: { version, id: '2097515131537313794' } } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { order: { version, id: '2097515131537313794' } } })
|
||||
const detail = await getDeliveryOrder('DEL/1', '1001')
|
||||
expect(detail.order.version).toBe(Number(version))
|
||||
expect(detail.order.id).toBe('2097515131537313794')
|
||||
})
|
||||
|
||||
it.each([null, undefined, '', ' ', '-1', '1.5', '9007199254740992', -1])('rejects invalid version %s', async version => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { order: { version } } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { order: { version } } })
|
||||
await expect(getDeliveryOrder('DEL/1', '1001')).rejects.toThrow('派送单缺少有效版本')
|
||||
})
|
||||
|
||||
it('loads return options and marks a return in the explicit customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: [{ inboundOrderId: '9', inboundCode: 'IN-1' }] })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: [{ inboundOrderId: '9', inboundCode: 'IN-1' }] })
|
||||
await listDeliveryReturnInboundOptions('DEL/1', '1001')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1/return-inbound-options', { params: { customerId: '1001' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1/return-inbound-options', { params: { customerId: '1001' } })
|
||||
|
||||
const payload = { inboundOrderId: '9', reason: '客户拒收', returnDirection: 'OVERSEAS_WAREHOUSE' as const, items: [{ outboundPalletItemId: '9007199254740995', inventoryPositionId: '9007199254740996', packageCount: 2 }], idempotencyKey: 'return-1' }
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: { id: '19', exceptionNo: 'EXC-1', status: 'PENDING' } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: { id: '19', exceptionNo: 'EXC-1', status: 'PENDING' } })
|
||||
await markDeliveryReturn('DEL/1', '1001', payload)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1/mark-return', payload, { params: { customerId: '1001' } })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/delivery-orders/DEL%2F1/mark-return', payload, { params: { customerId: '1001' } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
import type { DeliveryDocumentSummary } from './deliveryDocuments'
|
||||
|
||||
@@ -94,14 +94,14 @@ export interface MarkDeliveryReturnPayload {
|
||||
|
||||
export async function listDeliveryOrders(query: DeliveryOrderQuery) {
|
||||
const { customerId, ...params } = query
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<DeliveryOrderRow>>, ApiEnvelope<OverseasPagePayload<DeliveryOrderRow>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<DeliveryOrderRow>>, ApiEnvelope<OverseasPagePayload<DeliveryOrderRow>>>(
|
||||
'/platform/v1/last-leg/delivery-orders', { params: { ...params, ...(customerId ? { customerId } : {}) } },
|
||||
)
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
export async function getDeliveryOrder(deliveryNo: string, customerId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<DeliveryOrderDetail>, ApiEnvelope<DeliveryOrderDetail>>(
|
||||
const response = await http.get<ApiEnvelope<DeliveryOrderDetail>, ApiEnvelope<DeliveryOrderDetail>>(
|
||||
`/platform/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}`, { params: { customerId, page: 1, size: 200 } },
|
||||
)
|
||||
const detail = unwrapApiResponse(response)
|
||||
@@ -116,14 +116,14 @@ export async function getDeliveryOrder(deliveryNo: string, customerId: string) {
|
||||
}
|
||||
|
||||
export async function listDeliveryReturnInboundOptions(deliveryNo: string, customerId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<DeliveryReturnRelation[]>, ApiEnvelope<DeliveryReturnRelation[]>>(
|
||||
const response = await http.get<ApiEnvelope<DeliveryReturnRelation[]>, ApiEnvelope<DeliveryReturnRelation[]>>(
|
||||
`/platform/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}/return-inbound-options`, { params: { customerId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function markDeliveryReturn(deliveryNo: string, customerId: string, payload: MarkDeliveryReturnPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<{ id: string; exceptionNo: string; status: string }>, ApiEnvelope<{ id: string; exceptionNo: string; status: string }>>(
|
||||
const response = await http.post<ApiEnvelope<{ id: string; exceptionNo: string; status: string }>, ApiEnvelope<{ id: string; exceptionNo: string; status: string }>>(
|
||||
`/platform/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}/mark-return`, payload, { params: { customerId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { cancelDispatch, createDispatchDraftContainer, deleteDispatchDraftContainer, getDispatch, getDispatchBolPdf, listDispatchCandidates, listDispatchDrafts, listDispatches, lockDispatchDraftPallet, preArrangeDispatch, releaseDispatchDraft, transferDispatchToDelivery, unlockDispatchDraftPallet, updateDispatch } from './dispatches'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() } }))
|
||||
|
||||
describe('dispatch overseas API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(overseasHttp.get).mockReset()
|
||||
vi.mocked(overseasHttp.post).mockReset()
|
||||
vi.mocked(overseasHttp.put).mockReset()
|
||||
vi.mocked(overseasHttp.delete).mockReset()
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(http.delete).mockReset()
|
||||
})
|
||||
|
||||
it('uses the platform dispatch page without customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({
|
||||
vi.mocked(http.get).mockResolvedValue({
|
||||
code: '200', message: 'success', data: { records: [], page: 2, size: 50, total: 0, pages: 0 },
|
||||
})
|
||||
|
||||
@@ -22,7 +22,7 @@ describe('dispatch overseas API', () => {
|
||||
vehiclePlate: 'CA-100', status: 'PENDING_DEPARTURE', fbaAppointmentNo: 'FBA-1',
|
||||
})
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches', {
|
||||
params: {
|
||||
page: 2, size: 50, dispatchNo: 'PC-1',
|
||||
vehiclePlate: 'CA-100', status: 'PENDING_DEPARTURE', fbaAppointmentNo: 'FBA-1',
|
||||
@@ -31,78 +31,78 @@ describe('dispatch overseas API', () => {
|
||||
})
|
||||
|
||||
it('loads a platform dispatch detail by encoded dispatch number', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', dispatchNo: 'PC/1' } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', dispatchNo: 'PC/1' } })
|
||||
|
||||
await getDispatch('PC/1')
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1')
|
||||
})
|
||||
|
||||
it('requests the generated BOL as a PDF blob', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue(new Blob(['%PDF-test']))
|
||||
vi.mocked(http.get).mockResolvedValue(new Blob(['%PDF-test']))
|
||||
await getDispatchBolPdf('PC/1')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1/prints/bol', { responseType: 'blob' })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1/prints/bol', { responseType: 'blob' })
|
||||
})
|
||||
|
||||
it('loads candidates and creates a pre-arrange dispatch in an explicit customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', dispatchNo: 'PC-1' } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', dispatchNo: 'PC-1' } })
|
||||
await listDispatchCandidates({ planIds: '101,102', fbaWarehouseCode: 'ONT8', sourceStage: 'PLAN' })
|
||||
await preArrangeDispatch({ planPalletIds: ['190000000000000099'] })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/candidates', { params: { planIds: '101,102', fbaWarehouseCode: 'ONT8', sourceStage: 'PLAN' } })
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/pre-arrange', { planPalletIds: ['190000000000000099'] })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/candidates', { params: { planIds: '101,102', fbaWarehouseCode: 'ONT8', sourceStage: 'PLAN' } })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/pre-arrange', { planPalletIds: ['190000000000000099'] })
|
||||
})
|
||||
|
||||
it('loads platform candidates without selected inbound plans', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
|
||||
await listDispatchCandidates({ sourceStage: 'RECEIVED' })
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/candidates', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/candidates', {
|
||||
params: { sourceStage: 'RECEIVED' },
|
||||
})
|
||||
})
|
||||
|
||||
it('locks, unlocks, and releases intelligent dispatch drafts through dedicated endpoints', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
|
||||
await lockDispatchDraftPallet('99', 'draft-1')
|
||||
await unlockDispatchDraftPallet('99', 'draft-1')
|
||||
await releaseDispatchDraft('draft-1')
|
||||
|
||||
expect(overseasHttp.post).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/dispatches/draft-locks/lock', { planPalletId: '99', draftToken: 'draft-1' })
|
||||
expect(overseasHttp.post).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/dispatches/draft-locks/unlock', { planPalletId: '99', draftToken: 'draft-1' })
|
||||
expect(overseasHttp.post).toHaveBeenNthCalledWith(3, '/platform/v1/last-leg/dispatches/draft-locks/release', { draftToken: 'draft-1' })
|
||||
expect(http.post).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/dispatches/draft-locks/lock', { planPalletId: '99', draftToken: 'draft-1' })
|
||||
expect(http.post).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/dispatches/draft-locks/unlock', { planPalletId: '99', draftToken: 'draft-1' })
|
||||
expect(http.post).toHaveBeenNthCalledWith(3, '/platform/v1/last-leg/dispatches/draft-locks/release', { draftToken: 'draft-1' })
|
||||
})
|
||||
|
||||
it('edits and cancels only by dispatchNo without customer scope or status mutation', async () => {
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', dispatchNo: 'PC/1' } })
|
||||
vi.mocked(overseasHttp.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', dispatchNo: 'PC/1' } })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
await updateDispatch('PC/1', { vehiclePlate: 'CA-100' })
|
||||
await cancelDispatch('PC/1')
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1', { vehiclePlate: 'CA-100' })
|
||||
expect(overseasHttp.put).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ status: expect.anything() }))
|
||||
expect(overseasHttp.delete).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1')
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1', { vehiclePlate: 'CA-100' })
|
||||
expect(http.put).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ status: expect.anything() }))
|
||||
expect(http.delete).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1')
|
||||
})
|
||||
|
||||
it('transfers to delivery only by dispatchNo without customerId', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: { dispatchNo: 'PC/1', outboundNo: 'OUT-1', outboundStatus: 'PICKED', palletCount: 2, packageCount: 20, deliveries: [{ deliveryNo: 'DEL-1', deliveryStatus: 'WAIT_DELIVERY', destinationWarehouseCode: 'ACY2', palletCount: 2, packageCount: 20 }], replayed: false } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { dispatchNo: 'PC/1', outboundNo: 'OUT-1', outboundStatus: 'PICKED', palletCount: 2, packageCount: 20, deliveries: [{ deliveryNo: 'DEL-1', deliveryStatus: 'WAIT_DELIVERY', destinationWarehouseCode: 'ACY2', palletCount: 2, packageCount: 20 }], replayed: false } })
|
||||
const payload = { idempotencyKey: 'transfer-1', plannedDeliveryAt: '2026-09-01T10:00:00', deliveryMethod: 'TRUCK_PALLET', pickupMethod: 'WAREHOUSE_PICKUP', loadingType: 'PALLET', fees: [{ feeType: 'DELIVERY_FEE', feeName: '派送费用', direction: 'RECEIVABLE' as const, currency: 'USD' as const, amount: 10 }] }
|
||||
await transferDispatchToDelivery('PC/1', payload)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1/transfer-delivery', payload)
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/PC%2F1/transfer-delivery', payload)
|
||||
})
|
||||
|
||||
it('loads drafts and preserves long container ids in create and delete paths', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '190000000000000099', capacity: 30, palletIds: [] } })
|
||||
vi.mocked(overseasHttp.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '190000000000000099', capacity: 30, palletIds: [] } })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
|
||||
await listDispatchDrafts()
|
||||
await createDispatchDraftContainer('draft/1', 30)
|
||||
await deleteDispatchDraftContainer('draft/1', '190000000000000099')
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/drafts')
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/drafts/containers', { draftToken: 'draft/1', capacity: 30 })
|
||||
expect(overseasHttp.delete).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/drafts/draft%2F1/containers/190000000000000099')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/drafts')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/drafts/containers', { draftToken: 'draft/1', capacity: 30 })
|
||||
expect(http.delete).toHaveBeenCalledWith('/platform/v1/last-leg/dispatches/drafts/draft%2F1/containers/190000000000000099')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface DispatchQuery {
|
||||
@@ -140,7 +140,7 @@ export interface DispatchItemDto {
|
||||
}
|
||||
|
||||
export async function listDispatches(query: DispatchQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<DispatchSummaryDto>>, ApiEnvelope<OverseasPagePayload<DispatchSummaryDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<DispatchSummaryDto>>, ApiEnvelope<OverseasPagePayload<DispatchSummaryDto>>>(
|
||||
'/platform/v1/last-leg/dispatches',
|
||||
{ params: query },
|
||||
)
|
||||
@@ -148,42 +148,42 @@ export async function listDispatches(query: DispatchQuery) {
|
||||
}
|
||||
|
||||
export async function getDispatch(dispatchNo: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
const response = await http.get<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
`/platform/v1/last-leg/dispatches/${encodeURIComponent(dispatchNo)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function getDispatchBolPdf(dispatchNo: string) {
|
||||
return overseasHttp.get<Blob, Blob>(
|
||||
return http.get<Blob, Blob>(
|
||||
`/platform/v1/last-leg/dispatches/${encodeURIComponent(dispatchNo)}/prints/bol`,
|
||||
{ responseType: 'blob' },
|
||||
)
|
||||
}
|
||||
|
||||
export async function updateDispatch(dispatchNo: string, payload: UpdateDispatchPayload) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
const response = await http.put<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
`/platform/v1/last-leg/dispatches/${encodeURIComponent(dispatchNo)}`, payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function cancelDispatch(dispatchNo: string) {
|
||||
const response = await overseasHttp.delete<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
const response = await http.delete<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
`/platform/v1/last-leg/dispatches/${encodeURIComponent(dispatchNo)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function removeDispatchItem(dispatchNo: string, itemId: string) {
|
||||
const response = await overseasHttp.delete<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
const response = await http.delete<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
`/platform/v1/last-leg/dispatches/${encodeURIComponent(dispatchNo)}/items/${encodeURIComponent(itemId)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function listDispatchCandidates(query: DispatchCandidateQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<DispatchPalletCandidateDto[]>, ApiEnvelope<DispatchPalletCandidateDto[]>>(
|
||||
const response = await http.get<ApiEnvelope<DispatchPalletCandidateDto[]>, ApiEnvelope<DispatchPalletCandidateDto[]>>(
|
||||
'/platform/v1/last-leg/dispatches/candidates',
|
||||
{ params: query },
|
||||
)
|
||||
@@ -191,7 +191,7 @@ export async function listDispatchCandidates(query: DispatchCandidateQuery) {
|
||||
}
|
||||
|
||||
export async function preArrangeDispatch(payload: PreArrangeDispatchPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
const response = await http.post<ApiEnvelope<DispatchSummaryDto>, ApiEnvelope<DispatchSummaryDto>>(
|
||||
'/platform/v1/last-leg/dispatches/pre-arrange',
|
||||
payload,
|
||||
)
|
||||
@@ -199,34 +199,34 @@ export async function preArrangeDispatch(payload: PreArrangeDispatchPayload) {
|
||||
}
|
||||
|
||||
export async function lockDispatchDraftPallet(planPalletId: string, draftToken: string, draftContainerId?: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
const response = await http.post<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
'/platform/v1/last-leg/dispatches/draft-locks/lock', { planPalletId, draftToken, ...(draftContainerId ? { draftContainerId } : {}) },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function listDispatchDrafts() {
|
||||
const response = await overseasHttp.get<ApiEnvelope<DispatchDraftDto[]>, ApiEnvelope<DispatchDraftDto[]>>('/platform/v1/last-leg/dispatches/drafts')
|
||||
const response = await http.get<ApiEnvelope<DispatchDraftDto[]>, ApiEnvelope<DispatchDraftDto[]>>('/platform/v1/last-leg/dispatches/drafts')
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function createDispatchDraftContainer(draftToken: string, capacity: number) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<DispatchDraftContainerDto>, ApiEnvelope<DispatchDraftContainerDto>>('/platform/v1/last-leg/dispatches/drafts/containers', { draftToken, capacity })
|
||||
const response = await http.post<ApiEnvelope<DispatchDraftContainerDto>, ApiEnvelope<DispatchDraftContainerDto>>('/platform/v1/last-leg/dispatches/drafts/containers', { draftToken, capacity })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function deleteDispatchDraftContainer(draftToken: string, containerId: string) {
|
||||
const response = await overseasHttp.delete<ApiEnvelope<null>, ApiEnvelope<null>>(`/platform/v1/last-leg/dispatches/drafts/${encodeURIComponent(draftToken)}/containers/${encodeURIComponent(containerId)}`)
|
||||
const response = await http.delete<ApiEnvelope<null>, ApiEnvelope<null>>(`/platform/v1/last-leg/dispatches/drafts/${encodeURIComponent(draftToken)}/containers/${encodeURIComponent(containerId)}`)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function unlockDispatchDraftPallet(planPalletId: string, draftToken: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
const response = await http.post<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
'/platform/v1/last-leg/dispatches/draft-locks/unlock', { planPalletId, draftToken },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function releaseDispatchDraft(draftToken: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
const response = await http.post<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
'/platform/v1/last-leg/dispatches/draft-locks/release', { draftToken },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
@@ -257,7 +257,7 @@ export interface TransferDeliveryPayload {
|
||||
periodStart?: string; periodEnd?: string; remark?: string }>
|
||||
}
|
||||
export async function transferDispatchToDelivery(dispatchNo: string, payload: TransferDeliveryPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<TransferDeliveryResult>, ApiEnvelope<TransferDeliveryResult>>(
|
||||
const response = await http.post<ApiEnvelope<TransferDeliveryResult>, ApiEnvelope<TransferDeliveryResult>>(
|
||||
`/platform/v1/last-leg/dispatches/${encodeURIComponent(dispatchNo)}/transfer-delivery`, payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { createExceptionOrder, listExceptionOrders, resolveExceptionRelation } from './exceptionOrders'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn() } }))
|
||||
|
||||
describe('exception order API', () => {
|
||||
beforeEach(() => { vi.mocked(overseasHttp.get).mockReset(); vi.mocked(overseasHttp.post).mockReset() })
|
||||
beforeEach(() => { vi.mocked(http.get).mockReset(); vi.mocked(http.post).mockReset() })
|
||||
|
||||
it('queries the real paginated exception endpoint', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { records: [], page: '1', size: '20', total: '2', pages: '1' } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { records: [], page: '1', size: '20', total: '2', pages: '1' } })
|
||||
const result = await listExceptionOrders({ page: 1, size: 20, keyword: 'EXC' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/exception-orders', { params: { page: 1, size: 20, keyword: 'EXC' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/exception-orders', { params: { page: 1, size: 20, keyword: 'EXC' } })
|
||||
expect(result.total).toBe(2)
|
||||
})
|
||||
|
||||
it('resolves relation before creating an exception document', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { inboundOrderId: '11', inboundCode: 'IN-1', lastMileOrderId: '12', lastMileOrderNo: 'LM-1', customerId: '1' } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { inboundOrderId: '11', inboundCode: 'IN-1', lastMileOrderId: '12', lastMileOrderNo: 'LM-1', customerId: '1' } })
|
||||
await resolveExceptionRelation({ inboundCode: 'IN-1', lastMileOrderNo: 'LM-1' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/exception-orders/resolve', { params: { inboundCode: 'IN-1', lastMileOrderNo: 'LM-1' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/exception-orders/resolve', { params: { inboundCode: 'IN-1', lastMileOrderNo: 'LM-1' } })
|
||||
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: { id: '99', exceptionNo: 'EXC-1', status: 'PENDING' } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: { id: '99', exceptionNo: 'EXC-1', status: 'PENDING' } })
|
||||
await createExceptionOrder({ inboundCode: 'IN-1', lastMileOrderNo: 'LM-1', exceptionType: 'RETURN', reason: '拒收' })
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/exception-orders', expect.objectContaining({ inboundCode: 'IN-1', lastMileOrderNo: 'LM-1' }))
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/exception-orders', expect.objectContaining({ inboundCode: 'IN-1', lastMileOrderNo: 'LM-1' }))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface ExceptionOrderQuery { page: number; size: number; keyword?: string; exceptionType?: string; status?: string; customerId?: string; warehouseId?: string; createdFrom?: string; createdTo?: string }
|
||||
@@ -19,14 +19,14 @@ export interface ExceptionRelation {
|
||||
export interface CreateExceptionOrderPayload { customerId?: string; inboundCode?: string; lastMileOrderNo?: string; exceptionType: string; reason: string; packageCount?: number; skuCode?: string }
|
||||
|
||||
export async function listExceptionOrders(query: ExceptionOrderQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<ExceptionOrderRow>>, ApiEnvelope<OverseasPagePayload<ExceptionOrderRow>>>('/platform/v1/last-leg/exception-orders', { params: query })
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<ExceptionOrderRow>>, ApiEnvelope<OverseasPagePayload<ExceptionOrderRow>>>('/platform/v1/last-leg/exception-orders', { params: query })
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
export async function resolveExceptionRelation(params: { customerId?: string; inboundCode?: string; lastMileOrderNo?: string }) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<ExceptionRelation>, ApiEnvelope<ExceptionRelation>>('/platform/v1/last-leg/exception-orders/resolve', { params })
|
||||
const response = await http.get<ApiEnvelope<ExceptionRelation>, ApiEnvelope<ExceptionRelation>>('/platform/v1/last-leg/exception-orders/resolve', { params })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function createExceptionOrder(payload: CreateExceptionOrderPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<{ id: string; exceptionNo: string; status: string }>, ApiEnvelope<{ id: string; exceptionNo: string; status: string }>>('/platform/v1/last-leg/exception-orders', payload)
|
||||
const response = await http.post<ApiEnvelope<{ id: string; exceptionNo: string; status: string }>, ApiEnvelope<{ id: string; exceptionNo: string; status: string }>>('/platform/v1/last-leg/exception-orders', payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { createFbaAppointment, getFbaAppointment, listInboundOrders, updateFbaAppointment } from './inboundOrders'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
|
||||
describe('inbound order overseas API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(overseasHttp.get).mockReset()
|
||||
vi.mocked(overseasHttp.post).mockReset()
|
||||
vi.mocked(overseasHttp.put).mockReset()
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
})
|
||||
|
||||
it('loads appointment details and updates the existing appointment without replacing its lines', async () => {
|
||||
const detail = { id: '1', customerId: '190000000000000001', appointmentNo: 'APT/1', appointmentAt: '2026-08-20T10:30:00', expectedLoadingAt: '2026-08-20T09:00:00', appointmentStatus: 'SUCCESS', selectedCount: 2, fbaWarehouseCode: 'ONT8', items: [] }
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: detail })
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', message: 'success', data: detail })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: detail })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: detail })
|
||||
|
||||
await getFbaAppointment('190000000000000001', 'APT/1')
|
||||
await updateFbaAppointment('APT/1', { customerId: '190000000000000001', appointmentAt: detail.appointmentAt, expectedLoadingAt: detail.expectedLoadingAt, appointmentStatus: 'SUCCESS' })
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/fba-appointments/APT%2F1', { params: { customerId: '190000000000000001' } })
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/fba-appointments/APT%2F1', expect.objectContaining({ customerId: '190000000000000001' }))
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/fba-appointments/APT%2F1', { params: { customerId: '190000000000000001' } })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/fba-appointments/APT%2F1', expect.objectContaining({ customerId: '190000000000000001' }))
|
||||
})
|
||||
|
||||
it('loads the paginated list across all customers without a customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
await listInboundOrders({ page: 1, size: 20, appointmentStatus: 'UNAPPOINTED' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans', {
|
||||
params: { page: 1, size: 20, appointmentStatus: 'UNAPPOINTED' },
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves selected line ids as strings when creating an appointment', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', appointmentNo: 'APT-1', appointmentStatus: 'SUCCESS', selectedCount: 1, fbaWarehouseCode: 'ONT8' } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '1', appointmentNo: 'APT-1', appointmentStatus: 'SUCCESS', selectedCount: 1, fbaWarehouseCode: 'ONT8' } })
|
||||
const payload = {
|
||||
customerId: '190000000000000001',
|
||||
lineIds: ['190000000000000099'],
|
||||
@@ -42,6 +42,6 @@ describe('inbound order overseas API', () => {
|
||||
appointmentStatus: 'SUCCESS' as const,
|
||||
}
|
||||
await createFbaAppointment(payload)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/fba-appointments/batch', payload)
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/fba-appointments/batch', payload)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface InboundOrderQuery {
|
||||
@@ -79,21 +79,21 @@ export interface FbaAppointmentDto {
|
||||
export type UpdateFbaAppointmentPayload = Omit<BatchFbaAppointmentPayload, 'lineIds' | 'appointmentNo'>
|
||||
|
||||
export async function listInboundOrders(query: InboundOrderQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<InboundOrderSummaryDto>>, ApiEnvelope<OverseasPagePayload<InboundOrderSummaryDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<InboundOrderSummaryDto>>, ApiEnvelope<OverseasPagePayload<InboundOrderSummaryDto>>>(
|
||||
'/platform/v1/last-leg/inbound-plans', { params: query },
|
||||
)
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
export async function createFbaAppointment(payload: BatchFbaAppointmentPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<FbaAppointmentDto>, ApiEnvelope<FbaAppointmentDto>>(
|
||||
const response = await http.post<ApiEnvelope<FbaAppointmentDto>, ApiEnvelope<FbaAppointmentDto>>(
|
||||
'/platform/v1/last-leg/inbound-plans/fba-appointments/batch', payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function getFbaAppointment(customerId: string, appointmentNo: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<FbaAppointmentDto>, ApiEnvelope<FbaAppointmentDto>>(
|
||||
const response = await http.get<ApiEnvelope<FbaAppointmentDto>, ApiEnvelope<FbaAppointmentDto>>(
|
||||
`/platform/v1/last-leg/inbound-plans/fba-appointments/${encodeURIComponent(appointmentNo)}`,
|
||||
{ params: { customerId } },
|
||||
)
|
||||
@@ -101,7 +101,7 @@ export async function getFbaAppointment(customerId: string, appointmentNo: strin
|
||||
}
|
||||
|
||||
export async function updateFbaAppointment(appointmentNo: string, payload: UpdateFbaAppointmentPayload) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<FbaAppointmentDto>, ApiEnvelope<FbaAppointmentDto>>(
|
||||
const response = await http.put<ApiEnvelope<FbaAppointmentDto>, ApiEnvelope<FbaAppointmentDto>>(
|
||||
`/platform/v1/last-leg/inbound-plans/fba-appointments/${encodeURIComponent(appointmentNo)}`,
|
||||
payload,
|
||||
)
|
||||
@@ -109,7 +109,7 @@ export async function updateFbaAppointment(appointmentNo: string, payload: Updat
|
||||
}
|
||||
|
||||
export async function updateInboundPlan(planNo: string, payload: { customerId: string; overseasWarehouseId: string; warehouseCode?: string; warehouseName?: string; version: number }) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<InboundOrderSummaryDto>, ApiEnvelope<InboundOrderSummaryDto>>(
|
||||
const response = await http.put<ApiEnvelope<InboundOrderSummaryDto>, ApiEnvelope<InboundOrderSummaryDto>>(
|
||||
`/platform/v1/last-leg/inbound-plans/${encodeURIComponent(planNo)}`, payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { getInboundPlan, listInboundPlans } from './inboundPlans'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn() } }))
|
||||
describe('inbound plan overseas API', () => {
|
||||
beforeEach(() => vi.mocked(overseasHttp.get).mockReset())
|
||||
beforeEach(() => vi.mocked(http.get).mockReset())
|
||||
it('pages plans with explicit customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'ok', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'ok', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
await listInboundPlans({ customerId: '190000000000000001', page: 1, size: 20, inboundCode: 'IN-1' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans', { params: { customerId: '190000000000000001', page: 1, size: 20, inboundCode: 'IN-1' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans', { params: { customerId: '190000000000000001', page: 1, size: 20, inboundCode: 'IN-1' } })
|
||||
})
|
||||
it('gets detail by encoded plan number', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'ok', data: { id: '1', planNo: 'IP/1', customerId: '2', sourceOrderId: '190000000000000099', lineCount: 0, palletCount: 0, totalGrossWeightKg: 0, totalNetWeightKg: 0, totalVolumeCbm: 0, lines: [], pallets: [], allocations: [] } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'ok', data: { id: '1', planNo: 'IP/1', customerId: '2', sourceOrderId: '190000000000000099', lineCount: 0, palletCount: 0, totalGrossWeightKg: 0, totalNetWeightKg: 0, totalVolumeCbm: 0, lines: [], pallets: [], allocations: [] } })
|
||||
await getInboundPlan('IP/1', '2')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/IP%2F1', { params: { customerId: '2' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/IP%2F1', { params: { customerId: '2' } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface InboundPlanQuery {
|
||||
@@ -74,11 +74,11 @@ export interface InboundPlanDetailDto {
|
||||
|
||||
export async function listInboundPlans(query: InboundPlanQuery) {
|
||||
const { customerId, ...params } = query
|
||||
return normalizeOverseasPage(unwrapApiResponse(await overseasHttp.get<ApiEnvelope<OverseasPagePayload<InboundPlanSummaryDto>>, ApiEnvelope<OverseasPagePayload<InboundPlanSummaryDto>>>('/platform/v1/last-leg/inbound-plans', { params: { customerId, ...params } })))
|
||||
return normalizeOverseasPage(unwrapApiResponse(await http.get<ApiEnvelope<OverseasPagePayload<InboundPlanSummaryDto>>, ApiEnvelope<OverseasPagePayload<InboundPlanSummaryDto>>>('/platform/v1/last-leg/inbound-plans', { params: { customerId, ...params } })))
|
||||
}
|
||||
|
||||
export async function getInboundPlan(planNo: string, customerId: string) {
|
||||
return unwrapApiResponse(await overseasHttp.get<ApiEnvelope<InboundPlanDetailDto>, ApiEnvelope<InboundPlanDetailDto>>(`/platform/v1/last-leg/inbound-plans/${encodeURIComponent(planNo)}`, { params: { customerId } }))
|
||||
return unwrapApiResponse(await http.get<ApiEnvelope<InboundPlanDetailDto>, ApiEnvelope<InboundPlanDetailDto>>(`/platform/v1/last-leg/inbound-plans/${encodeURIComponent(planNo)}`, { params: { customerId } }))
|
||||
}
|
||||
|
||||
export interface PlatformInventoryMoveRequest {
|
||||
@@ -101,6 +101,6 @@ export interface PlatformInventoryMoveResult {
|
||||
}
|
||||
|
||||
export async function moveInboundPallet(payload: PlatformInventoryMoveRequest) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<PlatformInventoryMoveResult>, ApiEnvelope<PlatformInventoryMoveResult>>('/platform/v1/last-leg/inventory-moves', payload, { headers: { 'Idempotency-Key': payload.idempotencyKey } })
|
||||
const response = await http.post<ApiEnvelope<PlatformInventoryMoveResult>, ApiEnvelope<PlatformInventoryMoveResult>>('/platform/v1/last-leg/inventory-moves', payload, { headers: { 'Idempotency-Key': payload.idempotencyKey } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { downloadInventoryBalances, downloadInventoryLedger, getInventorySummary, listInventoryBalances, listInventoryLedger, listInventoryPositions } from './inventory'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn() } }))
|
||||
|
||||
describe('overseas inventory API', () => {
|
||||
beforeEach(() => { vi.clearAllMocks() })
|
||||
@@ -10,44 +10,44 @@ describe('overseas inventory API', () => {
|
||||
it('returns the binary response directly for inventory exports', async () => {
|
||||
const balances = new Blob(['customerId\\r\\n10001\\r\\n'], { type: 'text/csv' })
|
||||
const ledger = new Blob(['occurredAt\\r\\n'], { type: 'text/csv' })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce(balances).mockResolvedValueOnce(ledger)
|
||||
vi.mocked(http.get).mockResolvedValueOnce(balances).mockResolvedValueOnce(ledger)
|
||||
|
||||
await expect(downloadInventoryBalances({ skuCode: 'SKU-1' })).resolves.toBe(balances)
|
||||
await expect(downloadInventoryLedger({ inboundCode: 'IN-1' })).resolves.toBe(ledger)
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/inventory/balances/export', {
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/inventory/balances/export', {
|
||||
params: { skuCode: 'SKU-1' }, responseType: 'blob',
|
||||
})
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/inventory/ledger/export', {
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/inventory/ledger/export', {
|
||||
params: { inboundCode: 'IN-1' }, responseType: 'blob',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps skuCode and nullable location filters on real balance queries', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce({ code: '200', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } }).mockResolvedValueOnce({ code: '200', data: { totalPackages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } }).mockResolvedValueOnce({ code: '200', data: { totalPackages: 0 } })
|
||||
const query = { page: 1, size: 20, skuCode: 'SKU-1', warehouseLocationCode: 'A-01' }
|
||||
|
||||
await listInventoryBalances(query)
|
||||
await getInventorySummary(query)
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/inventory/balances', { params: query })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/inventory/summary', { params: { page: 1, size: 200, skuCode: 'SKU-1', warehouseLocationCode: 'A-01' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/inventory/balances', { params: query })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/inventory/summary', { params: { page: 1, size: 200, skuCode: 'SKU-1', warehouseLocationCode: 'A-01' } })
|
||||
})
|
||||
|
||||
it('uses the read-only position and ledger endpoints without customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: [] })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: [] })
|
||||
|
||||
await listInventoryPositions('190000000000000099')
|
||||
await listInventoryLedger({ page: 1, size: 20, skuCode: 'SKU-1' })
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/inventory/balances/190000000000000099/positions', { params: {} })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/inventory/ledger', { params: { page: 1, size: 20, skuCode: 'SKU-1' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/last-leg/inventory/balances/190000000000000099/positions', { params: {} })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/last-leg/inventory/ledger', { params: { page: 1, size: 20, skuCode: 'SKU-1' } })
|
||||
})
|
||||
|
||||
it('passes the inbound code as a business filter and preserves the returned customer name', async () => {
|
||||
const record = { id: '2093539779795795969', customerId: '2093539779795795970', customerName: '华远贸易', inboundCode: 'NYEXX2608300001', beforePackages: 0, deltaPackages: 2, afterPackages: 2 }
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { records: [record], page: 1, size: 20, total: 1, pages: 1 } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { records: [record], page: 1, size: 20, total: 1, pages: 1 } })
|
||||
await expect(listInventoryLedger({ page: 1, size: 20, inboundCode: 'NYEXX2608300001', customerName: '华远贸易' })).resolves.toMatchObject({ records: [record] })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/inventory/ledger', { params: { page: 1, size: 20, inboundCode: 'NYEXX2608300001', customerName: '华远贸易' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/inventory/ledger', { params: { page: 1, size: 20, inboundCode: 'NYEXX2608300001', customerName: '华远贸易' } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface InventoryBalanceDto {
|
||||
@@ -111,18 +111,18 @@ export interface InventoryBalanceQuery {
|
||||
function params(query: InventoryBalanceQuery) { return { ...query } }
|
||||
|
||||
export async function listInventoryBalances(query: InventoryBalanceQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<InventoryBalanceDto>>, ApiEnvelope<OverseasPagePayload<InventoryBalanceDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<InventoryBalanceDto>>, ApiEnvelope<OverseasPagePayload<InventoryBalanceDto>>>(
|
||||
'/platform/v1/last-leg/inventory/balances', { params: params(query) },
|
||||
)
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
export async function downloadInventoryBalances(query: Partial<InventoryBalanceQuery>) {
|
||||
return overseasHttp.get<Blob, Blob>('/platform/v1/last-leg/inventory/balances/export', { params: query, responseType: 'blob' })
|
||||
return http.get<Blob, Blob>('/platform/v1/last-leg/inventory/balances/export', { params: query, responseType: 'blob' })
|
||||
}
|
||||
|
||||
export async function getInventorySummary(query: InventoryBalanceQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<InventoryDashboardDto>, ApiEnvelope<InventoryDashboardDto>>(
|
||||
const response = await http.get<ApiEnvelope<InventoryDashboardDto>, ApiEnvelope<InventoryDashboardDto>>(
|
||||
'/platform/v1/last-leg/inventory/summary', { params: params({ ...query, page: 1, size: 200 }) },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
@@ -132,7 +132,7 @@ export async function listInventoryPositions(
|
||||
balanceId: string,
|
||||
query: { palletNo?: string; batchNo?: string; inventoryStatus?: string } = {},
|
||||
) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<InventoryPositionDto[]>, ApiEnvelope<InventoryPositionDto[]>>(
|
||||
const response = await http.get<ApiEnvelope<InventoryPositionDto[]>, ApiEnvelope<InventoryPositionDto[]>>(
|
||||
`/platform/v1/last-leg/inventory/balances/${encodeURIComponent(balanceId)}/positions`,
|
||||
{ params: query },
|
||||
)
|
||||
@@ -159,7 +159,7 @@ export interface InventoryLedgerQuery {
|
||||
}
|
||||
|
||||
export async function listInventoryLedger(query: InventoryLedgerQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<InventoryLedgerDto>>, ApiEnvelope<OverseasPagePayload<InventoryLedgerDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<InventoryLedgerDto>>, ApiEnvelope<OverseasPagePayload<InventoryLedgerDto>>>(
|
||||
'/platform/v1/last-leg/inventory/ledger',
|
||||
{ params: { ...query } },
|
||||
)
|
||||
@@ -167,5 +167,5 @@ export async function listInventoryLedger(query: InventoryLedgerQuery) {
|
||||
}
|
||||
|
||||
export async function downloadInventoryLedger(query: Partial<InventoryLedgerQuery>) {
|
||||
return overseasHttp.get<Blob, Blob>('/platform/v1/last-leg/inventory/ledger/export', { params: query, responseType: 'blob' })
|
||||
return http.get<Blob, Blob>('/platform/v1/last-leg/inventory/ledger/export', { params: query, responseType: 'blob' })
|
||||
}
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { changeContainerReceivingWarehouse, convertLastMileContainerToInboundPlans, createManualInboundPlan, downloadLastMileOrders, getContainerPlanProgress, getLastMileOrder, getLastMileOrderManualNodes, listContainerPlanProgress, listLastMileOrders, transferLastMileOrders, updateLastMileOrderHold, updateLastMileOrderManualNodes } from './lastMileOrders'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), put: vi.fn(), post: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), put: vi.fn(), post: vi.fn() } }))
|
||||
|
||||
describe('last-mile order overseas API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(overseasHttp.get).mockReset()
|
||||
vi.mocked(overseasHttp.put).mockReset()
|
||||
vi.mocked(overseasHttp.post).mockReset()
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
})
|
||||
|
||||
it('loads all platform orders without a customer scope', async () => {
|
||||
const record = { id: '190000000000000099', customerId: '190000000000000001', sourceContainerBookingId: '190000000000000088', customerName: '华远贸易', orderNo: 'LMO-260827-0001' }
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [record], page: '2', size: '20', total: '1', pages: '1' } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [record], page: '2', size: '20', total: '1', pages: '1' } })
|
||||
await expect(listLastMileOrders({ page: 2, size: 20, orderType: 'FIRST_LEG', currentStatus: 'PENDING_ASSIGNMENT', warehouse: 'LAX' })).resolves.toEqual({ records: [record], page: 2, size: 20, total: 1, pages: 1 })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders', {
|
||||
params: { page: 2, size: 20, orderType: 'FIRST_LEG', currentStatus: 'PENDING_ASSIGNMENT', warehouse: 'LAX' },
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves a long order id as a string in the detail path', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { order: { id: '190000000000000099' }, cargo: [], statusHistory: [] } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { order: { id: '190000000000000099' }, cargo: [], statusHistory: [] } })
|
||||
await getLastMileOrder('190000000000000099')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/190000000000000099')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/190000000000000099')
|
||||
})
|
||||
|
||||
it('does not call outbound or delivery endpoints', () => {
|
||||
@@ -32,43 +32,43 @@ describe('last-mile order overseas API', () => {
|
||||
})
|
||||
|
||||
it('passes all supported list filters and pagination without customerId', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: 2, size: 50, total: 0, pages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: 2, size: 50, total: 0, pages: 0 } })
|
||||
await listLastMileOrders({
|
||||
page: 2, size: 50, orderNo: 'LM-1', inboundCode: 'IN-1', sourceOrderNo: 'SRC-1',
|
||||
containerNo: 'CONT-1', status: 'PENDING_DELIVERY', transferWarehouseCode: 'ONT8',
|
||||
abnormal: true, detained: false, createdFrom: '2026-08-01T00:00:00', createdTo: '2026-08-31T23:59:59',
|
||||
})
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders', {
|
||||
params: expect.objectContaining({ page: 2, size: 50, sourceOrderNo: 'SRC-1', transferWarehouseCode: 'ONT8', abnormal: true, detained: false }),
|
||||
})
|
||||
expect(JSON.stringify(vi.mocked(overseasHttp.get).mock.calls[0]?.[1])).not.toContain('customerId')
|
||||
expect(JSON.stringify(vi.mocked(http.get).mock.calls[0]?.[1])).not.toContain('customerId')
|
||||
})
|
||||
|
||||
it('uses the real destination transfer endpoint and edit contract', async () => {
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', message: 'success', data: 1 })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: 1 })
|
||||
await transferLastMileOrders({
|
||||
orderIds: ['190000000000000099'], warehouseId: 'WH-1', warehouseCode: 'ONT8', warehouseName: 'Ontario',
|
||||
})
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/orders/destination', expect.objectContaining({ orderIds: ['190000000000000099'] }))
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/orders/destination', expect.objectContaining({ orderIds: ['190000000000000099'] }))
|
||||
})
|
||||
|
||||
it('returns the exported CSV blob without reading data twice', async () => {
|
||||
const blob = new Blob(['orders'], { type: 'text/csv' })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue(blob)
|
||||
vi.mocked(http.get).mockResolvedValue(blob)
|
||||
|
||||
await expect(downloadLastMileOrders({ orderNo: 'LM-1' })).resolves.toBe(blob)
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/export', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/export', {
|
||||
params: { orderNo: 'LM-1' }, responseType: 'blob',
|
||||
})
|
||||
})
|
||||
|
||||
it('exports all authorized orders without pagination or empty filters', async () => {
|
||||
const blob = new Blob(['orders'], { type: 'text/csv' })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue(blob)
|
||||
vi.mocked(http.get).mockResolvedValue(blob)
|
||||
|
||||
await downloadLastMileOrders({ page: 1, size: 10, orderNo: '', createdFrom: undefined })
|
||||
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/export', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/export', {
|
||||
params: {}, responseType: 'blob',
|
||||
})
|
||||
})
|
||||
@@ -77,7 +77,7 @@ describe('last-mile order overseas API', () => {
|
||||
const blob = new Blob([JSON.stringify({
|
||||
code: 'S0500', message: '系统内部错误', data: null, requestId: 'req-1', traceId: 'trace-1',
|
||||
})], { type: 'application/json' })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue(blob)
|
||||
vi.mocked(http.get).mockResolvedValue(blob)
|
||||
|
||||
await expect(downloadLastMileOrders({})).rejects.toMatchObject({
|
||||
code: 'S0500', message: '系统内部错误', requestId: 'req-1', traceId: 'trace-1',
|
||||
@@ -85,12 +85,12 @@ describe('last-mile order overseas API', () => {
|
||||
})
|
||||
|
||||
it('uses the manual inbound-plan endpoint with the complete form and idempotency evidence', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: {} })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: {} })
|
||||
const payload = { orderId: '190000000000000099', customerId: '190000000000000001', expectedOrderVersion: 4,
|
||||
palletCount: 8, palletType: 'STANDARD' as const,
|
||||
assigned: false, mergeRequired: false, urgent: true, remark: '加急' }
|
||||
await createManualInboundPlan(payload, 'plan-key-1')
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/manual', payload,
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/manual', payload,
|
||||
{ headers: { 'Idempotency-Key': 'plan-key-1' } })
|
||||
expect(payload).not.toHaveProperty('inboundCode')
|
||||
expect(payload).not.toHaveProperty('plannedArrivalDate')
|
||||
@@ -100,28 +100,28 @@ describe('last-mile order overseas API', () => {
|
||||
})
|
||||
|
||||
it('uses versioned idempotent order hold and complete manual-node snapshot endpoints', async () => {
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', message: 'success', data: {} })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { nodes: [] } })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: {} })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { nodes: [] } })
|
||||
await updateLastMileOrderHold('190000000000000099', { held: true, chargeable: true, reason: '海关查验', expectedVersion: 4 }, 'hold-key-1')
|
||||
expect(overseasHttp.put).toHaveBeenLastCalledWith('/platform/v1/last-leg/orders/190000000000000099/hold',
|
||||
expect(http.put).toHaveBeenLastCalledWith('/platform/v1/last-leg/orders/190000000000000099/hold',
|
||||
{ held: true, chargeable: true, reason: '海关查验', expectedVersion: 4 }, { headers: { 'Idempotency-Key': 'hold-key-1' } })
|
||||
await getLastMileOrderManualNodes('190000000000000099')
|
||||
expect(overseasHttp.get).toHaveBeenLastCalledWith('/platform/v1/last-leg/orders/190000000000000099/manual-nodes')
|
||||
expect(http.get).toHaveBeenLastCalledWith('/platform/v1/last-leg/orders/190000000000000099/manual-nodes')
|
||||
const nodes = [{ nodeCode: 'ESTIMATED_ARRIVAL' as const, nodeAt: '2026-09-10T10:00:00' }]
|
||||
await updateLastMileOrderManualNodes('190000000000000099', 5, nodes, 'node-key-1')
|
||||
expect(overseasHttp.put).toHaveBeenLastCalledWith('/platform/v1/last-leg/orders/190000000000000099/manual-nodes',
|
||||
expect(http.put).toHaveBeenLastCalledWith('/platform/v1/last-leg/orders/190000000000000099/manual-nodes',
|
||||
{ expectedVersion: 5, nodes }, { headers: { 'Idempotency-Key': 'node-key-1' } })
|
||||
})
|
||||
|
||||
it('uses one atomic container request without looping individual conversions', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: [] })
|
||||
await expect(convertLastMileContainerToInboundPlans({
|
||||
sourceContainerBookingId: '2092873463568597001',
|
||||
snapshotVersion: 9,
|
||||
snapshotHash: 'a'.repeat(64),
|
||||
}, 'container-plan-idempotency-key')).resolves.toEqual([])
|
||||
expect(overseasHttp.post).toHaveBeenCalledTimes(1)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/convert-container', {
|
||||
expect(http.post).toHaveBeenCalledTimes(1)
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/inbound-plans/convert-container', {
|
||||
sourceContainerBookingId: '2092873463568597001',
|
||||
snapshotVersion: 9,
|
||||
snapshotHash: 'a'.repeat(64),
|
||||
@@ -134,14 +134,14 @@ describe('last-mile order overseas API', () => {
|
||||
inboundCodeCount: 13, missingInboundCodeCount: 2, planCount: 10, plannedInboundCodeCount: 10,
|
||||
pendingPlanCount: 5, resourcePendingPlanCount: 0, plannedArrivalAt: '2026-09-01T08:00:00', allPlansReady: false, blockingReason: '存在2票缺少入仓码',
|
||||
}
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({
|
||||
vi.mocked(http.get).mockResolvedValue({
|
||||
code: '200', message: 'success', data: { records: [record], page: '2', size: '10', total: '21', pages: '3' },
|
||||
})
|
||||
await expect(listContainerPlanProgress({
|
||||
page: 2, size: 10, containerNo: 'CONT-15',
|
||||
createdFrom: '2026-08-01T00:00:00', createdTo: '2026-08-31T23:59:59',
|
||||
})).resolves.toEqual({ records: [record], page: 2, size: 10, total: 21, pages: 3 })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-summaries', {
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-summaries', {
|
||||
params: {
|
||||
page: 2, size: 10, containerNo: 'CONT-15',
|
||||
createdFrom: '2026-08-01T00:00:00', createdTo: '2026-08-31T23:59:59',
|
||||
@@ -151,18 +151,18 @@ describe('last-mile order overseas API', () => {
|
||||
|
||||
it('loads one container detail with the encoded stable long id', async () => {
|
||||
const detail = { summary: { sourceContainerBookingId: '2092873463568597001' }, orders: [] }
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: detail })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: detail })
|
||||
await expect(getContainerPlanProgress('2092873463568597001/unsafe')).resolves.toEqual(detail)
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-summaries/2092873463568597001%2Funsafe')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/orders/container-summaries/2092873463568597001%2Funsafe')
|
||||
})
|
||||
|
||||
it('changes one whole container receiving warehouse with version and idempotency evidence', async () => {
|
||||
const updated = { sourceContainerBookingId: '2092873463568597001', overseasWarehouseId: '9007199254740993' }
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', message: 'success', data: updated })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: updated })
|
||||
await expect(changeContainerReceivingWarehouse('2092873463568597001/unsafe', {
|
||||
overseasWarehouseId: '9007199254740993', expectedVersion: 7, remark: '改派洛杉矶接柜',
|
||||
}, 'receiving-key-1')).resolves.toEqual(updated)
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith(
|
||||
expect(http.put).toHaveBeenCalledWith(
|
||||
'/platform/v1/last-leg/orders/container-summaries/2092873463568597001%2Funsafe/receiving-warehouse',
|
||||
{ overseasWarehouseId: '9007199254740993', expectedVersion: 7, remark: '改派洛杉矶接柜' },
|
||||
{ headers: { 'Idempotency-Key': 'receiving-key-1' } },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { ApiResponseError, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, ApiResponseError, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import type { InboundPlanDetailDto } from './inboundPlans'
|
||||
|
||||
export interface OverseasPageResult<T> {
|
||||
@@ -351,7 +351,7 @@ export interface LastMileOrderDetailDto {
|
||||
}
|
||||
|
||||
export async function listLastMileOrders(query: LastMileOrderQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<LastMileOrderSummaryDto>>, ApiEnvelope<OverseasPagePayload<LastMileOrderSummaryDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<LastMileOrderSummaryDto>>, ApiEnvelope<OverseasPagePayload<LastMileOrderSummaryDto>>>(
|
||||
'/platform/v1/last-leg/orders',
|
||||
{ params: query },
|
||||
)
|
||||
@@ -359,14 +359,14 @@ export async function listLastMileOrders(query: LastMileOrderQuery) {
|
||||
}
|
||||
|
||||
export async function getLastMileOrder(orderId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<LastMileOrderDetailDto>, ApiEnvelope<LastMileOrderDetailDto>>(
|
||||
const response = await http.get<ApiEnvelope<LastMileOrderDetailDto>, ApiEnvelope<LastMileOrderDetailDto>>(
|
||||
`/platform/v1/last-leg/orders/${encodeURIComponent(orderId)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function reviewReturnOrder(returnNo: string, customerId: string, decision: 'APPROVE' | 'REJECT', remark?: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
const response = await http.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
`/platform/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}/review`,
|
||||
{ decision, remark: remark?.trim() || undefined },
|
||||
{ headers: { 'X-Customer-Id': customerId } },
|
||||
@@ -375,7 +375,7 @@ export async function reviewReturnOrder(returnNo: string, customerId: string, de
|
||||
}
|
||||
|
||||
export async function reviewDirectRelabelOrder(orderId: string, customerId: string, decision: 'APPROVE' | 'REJECT', remark?: string) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
const response = await http.put<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
`/platform/v1/last-leg/orders/${encodeURIComponent(orderId)}/relabel-review`,
|
||||
{ status: decision === 'APPROVE' ? 'PENDING_PROCESSING' : 'REJECTED', remark: remark?.trim() || undefined },
|
||||
{ params: { customerId } },
|
||||
@@ -383,21 +383,12 @@ export async function reviewDirectRelabelOrder(orderId: string, customerId: stri
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function reviewCargoDiscardOrder(discardNo: string, customerId: string, decision: 'APPROVE' | 'REJECT', remark?: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
`/platform/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/review`,
|
||||
{ decision, remark: remark?.trim() || undefined },
|
||||
{ params: { customerId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function downloadLastMileOrders(query: Partial<LastMileOrderQuery>) {
|
||||
const { page: _page, size: _size, ...filters } = query
|
||||
const params = Object.fromEntries(
|
||||
Object.entries(filters).filter(([, value]) => value !== undefined && value !== null && value !== ''),
|
||||
)
|
||||
const blob = await overseasHttp.get<Blob, Blob>('/platform/v1/last-leg/orders/export', { params, responseType: 'blob' })
|
||||
const blob = await http.get<Blob, Blob>('/platform/v1/last-leg/orders/export', { params, responseType: 'blob' })
|
||||
if (!blob.type.toLowerCase().includes('json')) return blob
|
||||
let error: Partial<ApiEnvelope<unknown>>
|
||||
try {
|
||||
@@ -416,7 +407,7 @@ export async function downloadLastMileOrders(query: Partial<LastMileOrderQuery>)
|
||||
}
|
||||
|
||||
export async function createLastMileOrderFee(orderId: string, payload: CreateLastMileFeePayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<LastMileFeeDto>, ApiEnvelope<LastMileFeeDto>>(
|
||||
const response = await http.post<ApiEnvelope<LastMileFeeDto>, ApiEnvelope<LastMileFeeDto>>(
|
||||
`/platform/v1/last-leg/orders/${encodeURIComponent(orderId)}/fees`, payload,
|
||||
{ headers: { 'Idempotency-Key': `last-mile-fee-${orderId}-${Date.now()}-${Math.random().toString(36).slice(2)}` } },
|
||||
)
|
||||
@@ -424,14 +415,14 @@ export async function createLastMileOrderFee(orderId: string, payload: CreateLas
|
||||
}
|
||||
|
||||
export async function transferLastMileOrders(payload: TransferDestinationPayload) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<number>, ApiEnvelope<number>>(
|
||||
const response = await http.put<ApiEnvelope<number>, ApiEnvelope<number>>(
|
||||
'/platform/v1/last-leg/orders/destination', payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function listContainerPlanProgress(query: ContainerPlanProgressQuery): Promise<OverseasPageResult<ContainerPlanProgressSummaryDto>> {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<ContainerPlanProgressSummaryDto>>, ApiEnvelope<OverseasPagePayload<ContainerPlanProgressSummaryDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<ContainerPlanProgressSummaryDto>>, ApiEnvelope<OverseasPagePayload<ContainerPlanProgressSummaryDto>>>(
|
||||
'/platform/v1/last-leg/orders/container-summaries',
|
||||
{ params: query },
|
||||
)
|
||||
@@ -439,14 +430,14 @@ export async function listContainerPlanProgress(query: ContainerPlanProgressQuer
|
||||
}
|
||||
|
||||
export async function getContainerPlanProgress(sourceContainerBookingId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<ContainerPlanProgressDetailDto>, ApiEnvelope<ContainerPlanProgressDetailDto>>(
|
||||
const response = await http.get<ApiEnvelope<ContainerPlanProgressDetailDto>, ApiEnvelope<ContainerPlanProgressDetailDto>>(
|
||||
`/platform/v1/last-leg/orders/container-summaries/${encodeURIComponent(sourceContainerBookingId)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function createManualInboundPlan(payload: ManualInboundPlanPayload, idempotencyKey: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<InboundPlanDetailDto>, ApiEnvelope<InboundPlanDetailDto>>(
|
||||
const response = await http.post<ApiEnvelope<InboundPlanDetailDto>, ApiEnvelope<InboundPlanDetailDto>>(
|
||||
'/platform/v1/last-leg/inbound-plans/manual', payload,
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey } },
|
||||
)
|
||||
@@ -454,7 +445,7 @@ export async function createManualInboundPlan(payload: ManualInboundPlanPayload,
|
||||
}
|
||||
|
||||
export async function updateLastMileOrderHold(orderId: string, payload: HoldLastMileOrderPayload, idempotencyKey: string) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<HoldLastMileOrderResponse>, ApiEnvelope<HoldLastMileOrderResponse>>(
|
||||
const response = await http.put<ApiEnvelope<HoldLastMileOrderResponse>, ApiEnvelope<HoldLastMileOrderResponse>>(
|
||||
`/platform/v1/last-leg/orders/${encodeURIComponent(orderId)}/hold`, payload,
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey } },
|
||||
)
|
||||
@@ -462,7 +453,7 @@ export async function updateLastMileOrderHold(orderId: string, payload: HoldLast
|
||||
}
|
||||
|
||||
export async function getLastMileOrderManualNodes(orderId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<ManualNodesResponse>, ApiEnvelope<ManualNodesResponse>>(
|
||||
const response = await http.get<ApiEnvelope<ManualNodesResponse>, ApiEnvelope<ManualNodesResponse>>(
|
||||
`/platform/v1/last-leg/orders/${encodeURIComponent(orderId)}/manual-nodes`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
@@ -474,7 +465,7 @@ export async function updateLastMileOrderManualNodes(
|
||||
nodes: ManualNodeValue[],
|
||||
idempotencyKey: string,
|
||||
) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<ManualNodesResponse>, ApiEnvelope<ManualNodesResponse>>(
|
||||
const response = await http.put<ApiEnvelope<ManualNodesResponse>, ApiEnvelope<ManualNodesResponse>>(
|
||||
`/platform/v1/last-leg/orders/${encodeURIComponent(orderId)}/manual-nodes`,
|
||||
{ expectedVersion, nodes },
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey } },
|
||||
@@ -487,7 +478,7 @@ export async function changeContainerReceivingWarehouse(
|
||||
payload: ChangeContainerReceivingWarehousePayload,
|
||||
idempotencyKey: string,
|
||||
) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<ContainerPlanProgressSummaryDto>, ApiEnvelope<ContainerPlanProgressSummaryDto>>(
|
||||
const response = await http.put<ApiEnvelope<ContainerPlanProgressSummaryDto>, ApiEnvelope<ContainerPlanProgressSummaryDto>>(
|
||||
`/platform/v1/last-leg/orders/container-summaries/${encodeURIComponent(sourceContainerBookingId)}/receiving-warehouse`,
|
||||
payload,
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey } },
|
||||
@@ -496,7 +487,7 @@ export async function changeContainerReceivingWarehouse(
|
||||
}
|
||||
|
||||
export async function getContainerInboundPlanPreview(sourceContainerBookingId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<ContainerInboundPlanPreviewDto>, ApiEnvelope<ContainerInboundPlanPreviewDto>>(
|
||||
const response = await http.get<ApiEnvelope<ContainerInboundPlanPreviewDto>, ApiEnvelope<ContainerInboundPlanPreviewDto>>(
|
||||
'/platform/v1/last-leg/inbound-plans/container-preview',
|
||||
{ params: { sourceContainerBookingId } },
|
||||
)
|
||||
@@ -504,7 +495,7 @@ export async function getContainerInboundPlanPreview(sourceContainerBookingId: s
|
||||
}
|
||||
|
||||
export async function convertLastMileContainerToInboundPlans(payload: ConvertContainerInboundPlanPayload, idempotencyKey: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<InboundPlanDetailDto[]>, ApiEnvelope<InboundPlanDetailDto[]>>(
|
||||
const response = await http.post<ApiEnvelope<InboundPlanDetailDto[]>, ApiEnvelope<InboundPlanDetailDto[]>>(
|
||||
'/platform/v1/last-leg/inbound-plans/convert-container', payload,
|
||||
{ headers: { 'Idempotency-Key': idempotencyKey } },
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export type OverseasLocationType = 'VIRTUAL' | 'NORMAL' | 'SHARED_OVERFLOW'
|
||||
@@ -33,10 +33,10 @@ export interface SaveOverseasLocationPayload {
|
||||
|
||||
export interface OverseasLocationQuery { page?: number; size?: number; keyword?: string; locationType?: OverseasLocationType | ''; status?: OverseasLocationStatus | '' }
|
||||
|
||||
function base(warehouseId: string) { return `/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/locations` }
|
||||
function base(warehouseId: string) { return `/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/locations` }
|
||||
|
||||
export async function listOverseasLocations(warehouseId: string, query: OverseasLocationQuery = {}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<OverseasLocationDto>>, ApiEnvelope<OverseasPagePayload<OverseasLocationDto>>>(base(warehouseId), { params: { page: query.page ?? 1, size: query.size ?? 20, ...query } })
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<OverseasLocationDto>>, ApiEnvelope<OverseasPagePayload<OverseasLocationDto>>>(base(warehouseId), { params: { page: query.page ?? 1, size: query.size ?? 20, ...query } })
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
@@ -47,21 +47,21 @@ export async function listAllOverseasLocations(warehouseIds: string[], query: Ov
|
||||
}
|
||||
|
||||
export async function createOverseasLocation(warehouseId: string, payload: SaveOverseasLocationPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<string>, ApiEnvelope<string>>(base(warehouseId), payload)
|
||||
const response = await http.post<ApiEnvelope<string>, ApiEnvelope<string>>(base(warehouseId), payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function updateOverseasLocation(warehouseId: string, locationId: string, payload: SaveOverseasLocationPayload & { version: number }) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${base(warehouseId)}/${encodeURIComponent(locationId)}`, payload)
|
||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${base(warehouseId)}/${encodeURIComponent(locationId)}`, payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function changeOverseasLocationStatus(warehouseId: string, locationId: string, payload: SaveOverseasLocationPayload & { version: number }) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${base(warehouseId)}/${encodeURIComponent(locationId)}`, payload)
|
||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${base(warehouseId)}/${encodeURIComponent(locationId)}`, payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function deleteOverseasLocation(warehouseId: string, locationId: string, version: number) {
|
||||
const response = await overseasHttp.delete<ApiEnvelope<null>, ApiEnvelope<null>>(`${base(warehouseId)}/${encodeURIComponent(locationId)}`, { params: { version } })
|
||||
const response = await http.delete<ApiEnvelope<null>, ApiEnvelope<null>>(`${base(warehouseId)}/${encodeURIComponent(locationId)}`, { params: { version } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { cancelOutbound, createOneClickDropshipOutbound, getOutbound, listOneClickOutboundCandidates, listOutbounds } from './outbounds'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn() } }))
|
||||
|
||||
describe('outbound overseas API', () => {
|
||||
beforeEach(() => { vi.mocked(overseasHttp.get).mockReset(); vi.mocked(overseasHttp.post).mockReset() })
|
||||
beforeEach(() => { vi.mocked(http.get).mockReset(); vi.mocked(http.post).mockReset() })
|
||||
|
||||
it('lists outbound orders with supported filters', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
await listOutbounds({ page: 1, size: 20, documentNo: 'OUT-1', warehouseId: 'WH-1', status: 'PICKED' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders', { params: { page: 1, size: 20, documentNo: 'OUT-1', warehouseId: 'WH-1', status: 'PICKED' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders', { params: { page: 1, size: 20, documentNo: 'OUT-1', warehouseId: 'WH-1', status: 'PICKED' } })
|
||||
})
|
||||
|
||||
it('loads detail and cancels only by outboundNo without customerId', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { outbound: { id: '1', outboundNo: 'OUT/1', status: 'PICKED' }, deliveries: [] } })
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: null })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { outbound: { id: '1', outboundNo: 'OUT/1', status: 'PICKED' }, deliveries: [] } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: null })
|
||||
await getOutbound('OUT/1')
|
||||
await cancelOutbound('OUT/1', '运营取消')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders/OUT%2F1')
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders/OUT%2F1/cancel', { reason: '运营取消' })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders/OUT%2F1')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders/OUT%2F1/cancel', { reason: '运营取消' })
|
||||
})
|
||||
|
||||
it('keeps customerId explicit only for one-click dropship creation', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: { id: '1', outboundNo: 'OUT-1' } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: { id: '1', outboundNo: 'OUT-1' } })
|
||||
const payload = { recipient: 'John / 555 / LA', items: [{ inventoryPositionId: '99', packages: 2, sku: 'SKU-1' }], idempotencyKey: 'dropship-1' }
|
||||
await createOneClickDropshipOutbound('customer-1', payload)
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders/one-click-dropship', payload, { params: { customerId: 'customer-1' } })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/outbound-orders/one-click-dropship', payload, { params: { customerId: 'customer-1' } })
|
||||
})
|
||||
|
||||
it('normalizes one-click candidate measurements returned as decimal strings', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: [{
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: [{
|
||||
inventoryPositionId: '99', availablePackages: 4,
|
||||
grossWeightKg: '40.000', volumeWeightKg: '80.000', volumeCbm: '4.0000',
|
||||
}] })
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
import type { DeliveryOrderRow } from './deliveryOrders'
|
||||
|
||||
@@ -26,19 +26,19 @@ export interface OneClickOutboundCandidate { inventoryPositionId: string; orderN
|
||||
export interface WarehouseTransferOutboundCandidate { customerId: string; customerName?: string | null; transferNo: string; overseasWarehouseId: string; transferStatus: string; needRelabel: boolean; relabelNo?: string | null; destinationType?: 'FBA' | 'PRIVATE' | null; destinationWarehouseCode?: string | null; privateDestinationAddress?: string | null; privateDestinationPostalCode?: string | null; packageCount: number; grossWeightKg?: number | null; volumeCbm?: number | null }
|
||||
export interface WarehouseTransferDestinationPayload { transfers: Array<{ customerId: string; transferNo: string }>; destinationType: 'FBA' | 'PRIVATE'; destinationWarehouseId?: string; destinationWarehouseCode?: string; destinationWarehouseName?: string; privateDestinationAddress?: string; privateDestinationPostalCode?: string; privateDestinationContactName?: string; privateDestinationContactPhone?: string; idempotencyKey: string }
|
||||
export async function listOutbounds(query: OutboundQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<OutboundRow>>, ApiEnvelope<OverseasPagePayload<OutboundRow>>>('/platform/v1/last-leg/outbound-orders', { params: query })
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<OutboundRow>>, ApiEnvelope<OverseasPagePayload<OutboundRow>>>('/platform/v1/last-leg/outbound-orders', { params: query })
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
export async function getOutbound(outboundNo: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OutboundDetail>, ApiEnvelope<OutboundDetail>>(`/platform/v1/last-leg/outbound-orders/${encodeURIComponent(outboundNo)}`)
|
||||
const response = await http.get<ApiEnvelope<OutboundDetail>, ApiEnvelope<OutboundDetail>>(`/platform/v1/last-leg/outbound-orders/${encodeURIComponent(outboundNo)}`)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function createOneClickDropshipOutbound(customerId: string, payload: { recipient: string; items: Array<{ inventoryPositionId: string; packages: number; sku?: string; cartonMarks?: string[] }>; remark?: string; idempotencyKey: string }) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<OutboundRow>, ApiEnvelope<OutboundRow>>('/platform/v1/last-leg/outbound-orders/one-click-dropship', payload, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<OutboundRow>, ApiEnvelope<OutboundRow>>('/platform/v1/last-leg/outbound-orders/one-click-dropship', payload, { params: { customerId } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function listOneClickOutboundCandidates(customerId?: string, query: { warehouseId?: string } = {}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OneClickOutboundCandidate[]>, ApiEnvelope<OneClickOutboundCandidate[]>>('/platform/v1/last-leg/outbound-orders/one-click-dropship/candidates', { params: { customerId, ...query } })
|
||||
const response = await http.get<ApiEnvelope<OneClickOutboundCandidate[]>, ApiEnvelope<OneClickOutboundCandidate[]>>('/platform/v1/last-leg/outbound-orders/one-click-dropship/candidates', { params: { customerId, ...query } })
|
||||
return unwrapApiResponse(response).map((item) => ({
|
||||
...item,
|
||||
inventoryPositionId: String(item.inventoryPositionId),
|
||||
@@ -49,22 +49,22 @@ export async function listOneClickOutboundCandidates(customerId?: string, query:
|
||||
}))
|
||||
}
|
||||
export async function listReturnOutboundCandidates(customerId: string, warehouseId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<ReturnOutboundCandidate[]>, ApiEnvelope<ReturnOutboundCandidate[]>>('/platform/v1/last-leg/outbound-orders/return/candidates', { params: { customerId, warehouseId } })
|
||||
const response = await http.get<ApiEnvelope<ReturnOutboundCandidate[]>, ApiEnvelope<ReturnOutboundCandidate[]>>('/platform/v1/last-leg/outbound-orders/return/candidates', { params: { customerId, warehouseId } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function createReturnOutbound(customerId: string, payload: { recipient: string; overseasWarehouseId: string; returnNo: string; cartonMarks: string[]; skuCode?: string; unitType?: 'BOX' | 'PALLET'; remark?: string; idempotencyKey: string }) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<OutboundRow>, ApiEnvelope<OutboundRow>>('/platform/v1/last-leg/outbound-orders/return', payload, { params: { customerId } })
|
||||
const response = await http.post<ApiEnvelope<OutboundRow>, ApiEnvelope<OutboundRow>>('/platform/v1/last-leg/outbound-orders/return', payload, { params: { customerId } })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function listWarehouseTransferOutboundCandidates(query: { customerId?: string; warehouseId?: string } = {}) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<WarehouseTransferOutboundCandidate[]>, ApiEnvelope<WarehouseTransferOutboundCandidate[]>>('/platform/v1/last-leg/outbound-orders/warehouse-transfer/candidates', { params: query })
|
||||
const response = await http.get<ApiEnvelope<WarehouseTransferOutboundCandidate[]>, ApiEnvelope<WarehouseTransferOutboundCandidate[]>>('/platform/v1/last-leg/outbound-orders/warehouse-transfer/candidates', { params: query })
|
||||
return unwrapApiResponse(response).map(item => ({ ...item, packageCount: Number(item.packageCount || 0) }))
|
||||
}
|
||||
export async function bindWarehouseTransferDestination(payload: WarehouseTransferDestinationPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<unknown[]>, ApiEnvelope<unknown[]>>('/platform/v1/last-leg/warehouse-transfers/bind-destination', payload)
|
||||
const response = await http.post<ApiEnvelope<unknown[]>, ApiEnvelope<unknown[]>>('/platform/v1/last-leg/warehouse-transfers/bind-destination', payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
export async function cancelOutbound(outboundNo: string, reason: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<null>, ApiEnvelope<null>>(`/platform/v1/last-leg/outbound-orders/${encodeURIComponent(outboundNo)}/cancel`, { reason })
|
||||
const response = await http.post<ApiEnvelope<null>, ApiEnvelope<null>>(`/platform/v1/last-leg/outbound-orders/${encodeURIComponent(outboundNo)}/cancel`, { reason })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ describe('Admin pallet warehouse routing contract', () => {
|
||||
})
|
||||
|
||||
it('never calls the nonexistent overseas warehouse-admin root and always scopes pallet calls by warehouseId', () => {
|
||||
expect(palletsApi).not.toMatch(/overseasHttp\.get[^\n]*\(\s*['"]\/platform\/v1\/warehouse-admin['"]/)
|
||||
expect(palletsApi).not.toMatch(/http\.get[^\n]*\(\s*['"]\/platform\/v1\/warehouse-admin['"]/)
|
||||
expect(palletsApi).not.toContain('listCustomerWarehouses')
|
||||
expect(palletsApi).toContain('`/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets`')
|
||||
expect(palletsApi).toContain('`/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}`')
|
||||
expect(palletsApi).toContain('`/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets`')
|
||||
expect(palletsApi).toContain('`/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}`')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { listSharedReceivingOverseasWarehouseOptions } from '@/modules/iam'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { createPallet, getPallet, getPalletLabelPdf, listPallets, listReceivingOverseasWarehouses, updatePallet } from './pallets'
|
||||
|
||||
vi.mock('@/modules/iam', () => ({ listSharedReceivingOverseasWarehouseOptions: vi.fn() }))
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
|
||||
describe('overseas pallet API', () => {
|
||||
beforeEach(() => { vi.clearAllMocks() })
|
||||
|
||||
it('downloads only the selected pallet through the overseas gateway', async () => {
|
||||
const pdf = new Blob(['%PDF-label'], { type: 'application/pdf' })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce(pdf)
|
||||
vi.mocked(http.get).mockResolvedValueOnce(pdf)
|
||||
await expect(getPalletLabelPdf('200', '9007199254740993')).resolves.toBe(pdf)
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/warehouse-admin/200/pallets/9007199254740993/label', { responseType: 'blob', timeout: 60_000 })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/overseas-warehouse-resources/200/pallets/9007199254740993/label', { responseType: 'blob', timeout: 60_000 })
|
||||
})
|
||||
|
||||
it('surfaces a JSON business failure instead of saving it as a PDF', async () => {
|
||||
const error = new Blob([JSON.stringify({ code: 'A0422', message: '托盘编码不支持打印', requestId: 'r1' })], { type: 'application/json' })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce(error)
|
||||
vi.mocked(http.get).mockResolvedValueOnce(error)
|
||||
await expect(getPalletLabelPdf('200', '9')).rejects.toMatchObject({ message: '托盘编码不支持打印', code: 'A0422', requestId: 'r1' })
|
||||
})
|
||||
|
||||
it('uses the public warehouse scoped pallet CRUD contract', async () => {
|
||||
const page = { records: [], page: 1, size: 20, total: 0, pages: 0 }
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: page })
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: '9' })
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', data: null })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: page })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: '9' })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', data: null })
|
||||
vi.mocked(listSharedReceivingOverseasWarehouseOptions).mockResolvedValue([{ id: '200', warehouseCode: 'LAX', warehouseName: '洛杉矶仓', countryCode: 'US' }])
|
||||
const payload = { palletCode: 'PLT-NEW', palletType: 'WOOD', fbaWarehouseCode: 'ABE3', capacityCbm: 2, unitPrice: 10, status: 'IDLE' }
|
||||
|
||||
@@ -37,11 +37,11 @@ describe('overseas pallet API', () => {
|
||||
await updatePallet('200', '9', { ...payload, version: 7 })
|
||||
|
||||
expect(listSharedReceivingOverseasWarehouseOptions).toHaveBeenCalledOnce()
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(1, '/platform/v1/warehouse-admin/200/pallets', { params: { page: 1, size: 20, keyword: 'PLT' } })
|
||||
expect(overseasHttp.get).toHaveBeenNthCalledWith(2, '/platform/v1/warehouse-admin/200/pallets/9', {})
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/warehouse-admin/200/pallets', payload)
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/warehouse-admin/200/pallets/9', { ...payload, version: 7 })
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/warehouse-admin/200/pallets/9', expect.objectContaining({ palletCode: 'PLT-NEW', fbaWarehouseCode: 'ABE3', status: 'IDLE', version: 7 }))
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/warehouse-admin/200/pallets', expect.not.objectContaining({ version: expect.anything() }))
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/overseas-warehouse-resources/200/pallets', { params: { page: 1, size: 20, keyword: 'PLT' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/overseas-warehouse-resources/200/pallets/9', {})
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/overseas-warehouse-resources/200/pallets', payload)
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/overseas-warehouse-resources/200/pallets/9', { ...payload, version: 7 })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/overseas-warehouse-resources/200/pallets/9', expect.objectContaining({ palletCode: 'PLT-NEW', fbaWarehouseCode: 'ABE3', status: 'IDLE', version: 7 }))
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/overseas-warehouse-resources/200/pallets', expect.not.objectContaining({ version: expect.anything() }))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { listSharedReceivingOverseasWarehouseOptions } from '@/modules/iam'
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
@@ -58,29 +58,29 @@ export async function listReceivingOverseasWarehouses() {
|
||||
}
|
||||
|
||||
export async function listPallets(warehouseId: string | undefined, query: { page: number; size: number; keyword?: string; palletType?: string; status?: string }) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<PalletDto>>, ApiEnvelope<OverseasPagePayload<PalletDto>>>(
|
||||
warehouseId ? `/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets` : '/platform/v1/warehouse-admin/pallets',
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<PalletDto>>, ApiEnvelope<OverseasPagePayload<PalletDto>>>(
|
||||
warehouseId ? `/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets` : '/platform/v1/overseas-warehouse-resources/pallets',
|
||||
{ params: { ...query } },
|
||||
)
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
export async function getPalletSummary(warehouseId: string, query: { keyword?: string; palletType?: string }) {
|
||||
const path = warehouseId ? `/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets/summary` : '/platform/v1/warehouse-admin/pallets/summary'
|
||||
const response = await overseasHttp.get<ApiEnvelope<PalletSummaryDto>, ApiEnvelope<PalletSummaryDto>>(path, { params: { page: 1, size: 1, ...query } })
|
||||
const path = warehouseId ? `/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets/summary` : '/platform/v1/overseas-warehouse-resources/pallets/summary'
|
||||
const response = await http.get<ApiEnvelope<PalletSummaryDto>, ApiEnvelope<PalletSummaryDto>>(path, { params: { page: 1, size: 1, ...query } })
|
||||
const value = unwrapApiResponse(response); return { totalCount: Number(value.totalCount), idleCount: Number(value.idleCount), occupiedCount: Number(value.occupiedCount), scrappedCount: Number(value.scrappedCount) }
|
||||
}
|
||||
|
||||
export async function getPallet(warehouseId: string, palletId: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<PalletDto>, ApiEnvelope<PalletDto>>(
|
||||
`/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}`,
|
||||
const response = await http.get<ApiEnvelope<PalletDto>, ApiEnvelope<PalletDto>>(
|
||||
`/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}`,
|
||||
{},
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function getPalletLabelPdf(warehouseId: string, palletId: string) {
|
||||
const blob = await overseasHttp.get<Blob, Blob>(
|
||||
`/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}/label`,
|
||||
const blob = await http.get<Blob, Blob>(
|
||||
`/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}/label`,
|
||||
{ responseType: 'blob', timeout: 60_000 },
|
||||
)
|
||||
if (blob.type.includes('application/json')) unwrapApiResponse(JSON.parse(await blob.text()) as ApiEnvelope<unknown>)
|
||||
@@ -89,15 +89,15 @@ export async function getPalletLabelPdf(warehouseId: string, palletId: string) {
|
||||
}
|
||||
|
||||
export async function createPallet(warehouseId: string, payload: SavePalletPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<string>, ApiEnvelope<string>>(
|
||||
`/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets`, payload,
|
||||
const response = await http.post<ApiEnvelope<string>, ApiEnvelope<string>>(
|
||||
`/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets`, payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function updatePallet(warehouseId: string, palletId: string, payload: UpdatePalletPayload) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
`/platform/v1/warehouse-admin/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}`,
|
||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(
|
||||
`/platform/v1/overseas-warehouse-resources/${encodeURIComponent(warehouseId)}/pallets/${encodeURIComponent(palletId)}`,
|
||||
payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
|
||||
@@ -1,45 +1,45 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { listSharedReceivingOverseasWarehouseOptions } from '@/modules/iam'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { changeRelabelOrderStatus, createRelabelOrder, getRelabelOrder, listRelabelOrders, listRelabelWarehouseOptions } from './relabelOrders'
|
||||
|
||||
vi.mock('@/modules/iam', () => ({ listSharedReceivingOverseasWarehouseOptions: vi.fn() }))
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))
|
||||
|
||||
describe('relabel overseas API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(overseasHttp.get).mockReset()
|
||||
vi.mocked(overseasHttp.post).mockReset()
|
||||
vi.mocked(overseasHttp.put).mockReset()
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(listSharedReceivingOverseasWarehouseOptions).mockReset()
|
||||
})
|
||||
|
||||
it('uses the platform page endpoint without customer scope', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: 1, size: 20, total: 0, pages: 0 } })
|
||||
await listRelabelOrders({ page: 1, size: 20, skuCode: 'SKU-1' })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications', { params: { page: 1, size: 20, skuCode: 'SKU-1' } })
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications', { params: { page: 1, size: 20, skuCode: 'SKU-1' } })
|
||||
})
|
||||
|
||||
it('encodes the relabel number and does not call a mutation endpoint', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', message: 'success', data: { application: { id: '1', relabelNo: 'RL/1' }, items: [], history: [] } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { application: { id: '1', relabelNo: 'RL/1' }, items: [], history: [] } })
|
||||
await getRelabelOrder('RL/1')
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications/RL%2F1')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications/RL%2F1')
|
||||
})
|
||||
|
||||
it('uses the real create and status endpoints', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: {} })
|
||||
vi.mocked(overseasHttp.put).mockResolvedValue({ code: '200', data: {} })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: {} })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', data: {} })
|
||||
const payload = { customerOrderNo: 'CO-1', overseasWarehouseId: '9', labelDeadline: '2026-08-20T10:00:00', contactName: 'A', contactPhone: '1', chargeAmount: 20, idempotencyKey: 'k', items: [{ skuCode: 'SKU', productNameZh: 'P', totalPackageCount: 1, notifiedPackageCount: 1, shipmentNo: 'S', newSkuCode: 'SKU-2' }] }
|
||||
await createRelabelOrder('10001', payload)
|
||||
await changeRelabelOrderStatus('RL/1', 'PROCESSING', 'ok')
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications', payload, { params: { customerId: '10001' } })
|
||||
expect(overseasHttp.put).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications/RL%2F1/status', { status: 'PROCESSING', remark: 'ok' })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications', payload, { params: { customerId: '10001' } })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/last-leg/relabel-applications/RL%2F1/status', { status: 'PROCESSING', remark: 'ok' })
|
||||
})
|
||||
|
||||
it('loads shared ACTIVE OVERSEAS RECEIVING warehouses from the domestic candidate contract', async () => {
|
||||
vi.mocked(listSharedReceivingOverseasWarehouseOptions).mockResolvedValue([{ id: '200', warehouseCode: 'LAX', warehouseName: '洛杉矶仓', countryCode: 'US' }])
|
||||
await expect(listRelabelWarehouseOptions()).resolves.toMatchObject({ records: [{ id: '200', customerId: '0', warehouseType: 'OVERSEAS', status: 'ACTIVE' }] })
|
||||
expect(listSharedReceivingOverseasWarehouseOptions).toHaveBeenCalledOnce()
|
||||
expect(overseasHttp.get).not.toHaveBeenCalledWith('/platform/v1/warehouse-admin', expect.anything())
|
||||
expect(http.get).not.toHaveBeenCalledWith('/platform/v1/warehouse-admin', expect.anything())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { listSharedReceivingOverseasWarehouseOptions } from '@/modules/iam'
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
@@ -9,12 +9,6 @@ export interface RelabelOrderQuery {
|
||||
relabelNo?: string
|
||||
skuCode?: string
|
||||
status?: string
|
||||
reviewedFrom?: string
|
||||
reviewedTo?: string
|
||||
measuredFrom?: string
|
||||
measuredTo?: string
|
||||
outboundFrom?: string
|
||||
outboundTo?: string
|
||||
}
|
||||
|
||||
export interface CreateRelabelItemPayload {
|
||||
@@ -88,9 +82,6 @@ export interface RelabelSummaryDto {
|
||||
customerConfirmedAt?: string | null
|
||||
reviewChannel?: 'TAIL_ORDER' | 'RELABEL_ORDER' | null
|
||||
reviewRemark?: string | null
|
||||
reviewedAt?: string | null
|
||||
measuredAt?: string | null
|
||||
outboundAt?: string | null
|
||||
createdAt?: string | null
|
||||
}
|
||||
|
||||
@@ -159,21 +150,21 @@ export interface ReturnPackingPlanDto extends ReturnPackingPlanPayload {
|
||||
}
|
||||
|
||||
export async function createReturnPackingPlan(payload: ReturnPackingPlanPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<ReturnPackingPlanDto>, ApiEnvelope<ReturnPackingPlanDto>>(
|
||||
const response = await http.post<ApiEnvelope<ReturnPackingPlanDto>, ApiEnvelope<ReturnPackingPlanDto>>(
|
||||
'/platform/v1/last-leg/return-packing-plans', payload,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
return unwrapApiResponse(response) as ReturnPackingPlanDto
|
||||
}
|
||||
|
||||
export async function listRelabelOrders(query: RelabelOrderQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<RelabelSummaryDto>>, ApiEnvelope<OverseasPagePayload<RelabelSummaryDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<RelabelSummaryDto>>, ApiEnvelope<OverseasPagePayload<RelabelSummaryDto>>>(
|
||||
'/platform/v1/last-leg/relabel-applications', { params: query },
|
||||
)
|
||||
return normalizeOverseasPage(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
export async function getRelabelOrder(relabelNo: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
const response = await http.get<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
@@ -192,14 +183,14 @@ export async function listRelabelWarehouseOptions() {
|
||||
}
|
||||
|
||||
export async function createRelabelOrder(customerId: string, payload: CreateRelabelPayload) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
const response = await http.post<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
'/platform/v1/last-leg/relabel-applications', payload, { params: { customerId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function changeRelabelOrderStatus(relabelNo: string, status: string, remark?: string) {
|
||||
const response = await overseasHttp.put<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
const response = await http.put<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/status`,
|
||||
{ status, remark },
|
||||
)
|
||||
@@ -207,17 +198,17 @@ export async function changeRelabelOrderStatus(relabelNo: string, status: string
|
||||
}
|
||||
|
||||
export async function getRelabelReviewTask(relabelNo: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<{ version: number; taskStatus: string }>, ApiEnvelope<{ version: number; taskStatus: string }>>(`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/review-task`)
|
||||
const response = await http.get<ApiEnvelope<{ version: number; taskStatus: string }>, ApiEnvelope<{ version: number; taskStatus: string }>>(`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/review-task`)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function returnRelabelForRework(relabelNo: string, expectedVersion: number, remark: string, idempotencyKey: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/rework`, { decision: 'REWORK', expectedVersion, remark, idempotencyKey })
|
||||
const response = await http.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/rework`, { decision: 'REWORK', expectedVersion, remark, idempotencyKey })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function confirmRelabelCompletion(relabelNo: string, remark?: string) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
const response = await http.post<ApiEnvelope<unknown>, ApiEnvelope<unknown>>(
|
||||
`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/confirm-completion`,
|
||||
{ idempotencyKey: crypto.randomUUID(), remark },
|
||||
)
|
||||
@@ -227,7 +218,7 @@ export async function confirmRelabelCompletion(relabelNo: string, remark?: strin
|
||||
export async function uploadRelabelPdf(relabelNo: string, file: File, scope: 'TOTAL' | 'ITEM', itemId?: string) {
|
||||
const body = new FormData()
|
||||
body.append('file', file)
|
||||
const response = await overseasHttp.post<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
const response = await http.post<ApiEnvelope<RelabelDetailDto>, ApiEnvelope<RelabelDetailDto>>(
|
||||
`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/files`, body,
|
||||
{ params: { scope, itemId }, headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
)
|
||||
@@ -235,14 +226,14 @@ export async function uploadRelabelPdf(relabelNo: string, file: File, scope: 'TO
|
||||
}
|
||||
|
||||
export async function downloadRelabelPdf(relabelNo: string, fileId: string, scope: 'TOTAL' | 'ITEM', itemId?: string) {
|
||||
return overseasHttp.get<Blob, Blob>(
|
||||
return http.get<Blob, Blob>(
|
||||
`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/files/${encodeURIComponent(fileId)}/download`,
|
||||
{ params: { scope, itemId }, responseType: 'blob' },
|
||||
)
|
||||
}
|
||||
|
||||
export async function downloadRelabelCompletionPhoto(relabelNo: string, fileId: string) {
|
||||
return overseasHttp.get<Blob, Blob>(
|
||||
return http.get<Blob, Blob>(
|
||||
`/platform/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/completion-photos/${encodeURIComponent(fileId)}/download`,
|
||||
{ responseType: 'blob' },
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface ReturnStockRow { customerId: string; overseasWarehouseId: string; skuCode: string; productNameZh?: string; totalQuantity: number; availableQuantity: number; cartonQuantity: number; updatedAt: string }
|
||||
@@ -9,8 +9,8 @@ export interface ReturnCartonLabel extends ReturnCartonDetail { printableHtml: s
|
||||
export interface ReturnInventoryMovement { customerId: string; overseasWarehouseId: string; skuCode: string; productNameZh?: string; movementType: 'RECEIPT' | 'MERGE' | 'OUTBOUND'; referenceNo: string; totalDelta: number; availableDelta: number; occurredAt: string }
|
||||
export interface ReturnInventoryQuery { page: number; size: number; customerId?: string; overseasWarehouseId?: string; skuCode?: string; cartonMark?: string; returnNo?: string; status?: string }
|
||||
|
||||
export async function listReturnStock(params: ReturnInventoryQuery) { const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<ReturnStockRow>>, ApiEnvelope<OverseasPagePayload<ReturnStockRow>>>('/platform/v1/last-leg/return-inventory', { params }); return normalizeOverseasPage(unwrapApiResponse(response)) }
|
||||
export async function listReturnCartons(params: ReturnInventoryQuery) { const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<ReturnCartonRow>>, ApiEnvelope<OverseasPagePayload<ReturnCartonRow>>>('/platform/v1/last-leg/return-inventory/cartons', { params }); return normalizeOverseasPage(unwrapApiResponse(response)) }
|
||||
export async function listReturnInventoryMovements(params: ReturnInventoryQuery) { const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<ReturnInventoryMovement>>, ApiEnvelope<OverseasPagePayload<ReturnInventoryMovement>>>('/platform/v1/last-leg/return-inventory/movements', { params }); return normalizeOverseasPage(unwrapApiResponse(response)) }
|
||||
export async function getReturnCarton(cartonMark: string) { const response = await overseasHttp.get<ApiEnvelope<ReturnCartonDetail>, ApiEnvelope<ReturnCartonDetail>>(`/platform/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}`); return unwrapApiResponse(response) }
|
||||
export async function getReturnCartonLabel(cartonMark: string) { const response = await overseasHttp.get<ApiEnvelope<ReturnCartonLabel>, ApiEnvelope<ReturnCartonLabel>>(`/platform/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}/label`); return unwrapApiResponse(response) }
|
||||
export async function listReturnStock(params: ReturnInventoryQuery) { const response = await http.get<ApiEnvelope<OverseasPagePayload<ReturnStockRow>>, ApiEnvelope<OverseasPagePayload<ReturnStockRow>>>('/platform/v1/last-leg/return-inventory', { params }); return normalizeOverseasPage(unwrapApiResponse(response)) }
|
||||
export async function listReturnCartons(params: ReturnInventoryQuery) { const response = await http.get<ApiEnvelope<OverseasPagePayload<ReturnCartonRow>>, ApiEnvelope<OverseasPagePayload<ReturnCartonRow>>>('/platform/v1/last-leg/return-inventory/cartons', { params }); return normalizeOverseasPage(unwrapApiResponse(response)) }
|
||||
export async function listReturnInventoryMovements(params: ReturnInventoryQuery) { const response = await http.get<ApiEnvelope<OverseasPagePayload<ReturnInventoryMovement>>, ApiEnvelope<OverseasPagePayload<ReturnInventoryMovement>>>('/platform/v1/last-leg/return-inventory/movements', { params }); return normalizeOverseasPage(unwrapApiResponse(response)) }
|
||||
export async function getReturnCarton(cartonMark: string) { const response = await http.get<ApiEnvelope<ReturnCartonDetail>, ApiEnvelope<ReturnCartonDetail>>(`/platform/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}`); return unwrapApiResponse(response) }
|
||||
export async function getReturnCartonLabel(cartonMark: string) { const response = await http.get<ApiEnvelope<ReturnCartonLabel>, ApiEnvelope<ReturnCartonLabel>>(`/platform/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}/label`); return unwrapApiResponse(response) }
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { getWarehouseTransfer, listWarehouseTransfers, reviewWarehouseTransfer } from './warehouseTransfers'
|
||||
|
||||
vi.mock('@/shared/api/overseasHttp', () => ({ overseasHttp: { get: vi.fn(), post: vi.fn() } }))
|
||||
vi.mock('@/shared/api/http', async (importOriginal) => ({ ...(await importOriginal<typeof import('@/shared/api/http')>()), http: { get: vi.fn(), post: vi.fn() } }))
|
||||
|
||||
describe('warehouseTransfers API', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('always scopes platform list and detail requests to the selected customer', async () => {
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce({ code: '200', data: { records: [], page: 1, size: 10, total: 0, pages: 0 } })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValueOnce({ code: '200', data: { transferNo: 'WT-1', items: [], cartons: [], relabelBindings: [] } })
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', data: { records: [], page: 1, size: 10, total: 0, pages: 0 } })
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', data: { transferNo: 'WT-1', items: [], cartons: [], relabelBindings: [] } })
|
||||
await listWarehouseTransfers('20001', { page: 1, size: 10, status: 'PENDING_REVIEW' })
|
||||
await getWarehouseTransfer('20001', 'WT-1')
|
||||
expect(vi.mocked(overseasHttp.get).mock.calls[0]).toEqual(['/platform/v1/last-leg/warehouse-transfers', { params: { page: 1, size: 10, status: 'PENDING_REVIEW', customerId: '20001' } }])
|
||||
expect(vi.mocked(overseasHttp.get).mock.calls[1]).toEqual(['/platform/v1/last-leg/warehouse-transfers/WT-1', { params: { customerId: '20001' } }])
|
||||
expect(vi.mocked(http.get).mock.calls[0]).toEqual(['/platform/v1/last-leg/warehouse-transfers', { params: { page: 1, size: 10, status: 'PENDING_REVIEW', customerId: '20001' } }])
|
||||
expect(vi.mocked(http.get).mock.calls[1]).toEqual(['/platform/v1/last-leg/warehouse-transfers/WT-1', { params: { customerId: '20001' } }])
|
||||
})
|
||||
|
||||
it('posts the real review decision with customer scope', async () => {
|
||||
vi.mocked(overseasHttp.post).mockResolvedValue({ code: '200', data: { transferNo: 'WT-1', items: [], cartons: [], relabelBindings: [] } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', data: { transferNo: 'WT-1', items: [], cartons: [], relabelBindings: [] } })
|
||||
await reviewWarehouseTransfer('20001', 'WT-1', 'APPROVE', '资料无误')
|
||||
expect(overseasHttp.post).toHaveBeenCalledWith(
|
||||
expect(http.post).toHaveBeenCalledWith(
|
||||
'/platform/v1/last-leg/warehouse-transfers/WT-1/review',
|
||||
{ decision: 'APPROVE', remark: '资料无误' },
|
||||
{ params: { customerId: '20001' } },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { overseasHttp } from '@/shared/api/overseasHttp'
|
||||
import { unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
import { normalizeOverseasPage, type OverseasPagePayload } from './lastMileOrders'
|
||||
|
||||
export interface WarehouseTransferQuery {
|
||||
@@ -10,12 +10,6 @@ export interface WarehouseTransferQuery {
|
||||
fbaWarehouseCode?: string
|
||||
status?: string
|
||||
needRelabel?: boolean
|
||||
reviewedFrom?: string
|
||||
reviewedTo?: string
|
||||
measuredFrom?: string
|
||||
measuredTo?: string
|
||||
outboundFrom?: string
|
||||
outboundTo?: string
|
||||
}
|
||||
|
||||
export interface WarehouseTransferSummaryDto {
|
||||
@@ -32,12 +26,6 @@ export interface WarehouseTransferSummaryDto {
|
||||
relabelNo?: string | null
|
||||
status: string
|
||||
estimatedArrivalAt?: string | null
|
||||
estimatedShipAt?: string | null
|
||||
actualShipAt?: string | null
|
||||
reviewedAt?: string | null
|
||||
measuredAt?: string | null
|
||||
outboundAt?: string | null
|
||||
relabelCompletedAt?: string | null
|
||||
createdAt?: string | null
|
||||
}
|
||||
|
||||
@@ -96,14 +84,10 @@ export interface WarehouseTransferDetailDto extends WarehouseTransferSummaryDto
|
||||
relabelBindings: WarehouseTransferRelabelBindingDto[]
|
||||
customerConfirmedAt?: string | null
|
||||
actualShipAt?: string | null
|
||||
reviewedAt?: string | null
|
||||
measuredAt?: string | null
|
||||
outboundAt?: string | null
|
||||
relabelCompletedAt?: string | null
|
||||
}
|
||||
|
||||
export async function listWarehouseTransfers(customerId: string, query: WarehouseTransferQuery) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasPagePayload<WarehouseTransferSummaryDto>>, ApiEnvelope<OverseasPagePayload<WarehouseTransferSummaryDto>>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasPagePayload<WarehouseTransferSummaryDto>>, ApiEnvelope<OverseasPagePayload<WarehouseTransferSummaryDto>>>(
|
||||
'/platform/v1/last-leg/warehouse-transfers',
|
||||
{ params: { ...query, customerId } },
|
||||
)
|
||||
@@ -111,7 +95,7 @@ export async function listWarehouseTransfers(customerId: string, query: Warehous
|
||||
}
|
||||
|
||||
export async function getWarehouseTransfer(customerId: string, transferNo: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<WarehouseTransferDetailDto>, ApiEnvelope<WarehouseTransferDetailDto>>(
|
||||
const response = await http.get<ApiEnvelope<WarehouseTransferDetailDto>, ApiEnvelope<WarehouseTransferDetailDto>>(
|
||||
`/platform/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}`,
|
||||
{ params: { customerId } },
|
||||
)
|
||||
@@ -124,7 +108,7 @@ export async function reviewWarehouseTransfer(
|
||||
decision: 'APPROVE' | 'REJECT',
|
||||
remark?: string,
|
||||
) {
|
||||
const response = await overseasHttp.post<ApiEnvelope<WarehouseTransferDetailDto>, ApiEnvelope<WarehouseTransferDetailDto>>(
|
||||
const response = await http.post<ApiEnvelope<WarehouseTransferDetailDto>, ApiEnvelope<WarehouseTransferDetailDto>>(
|
||||
`/platform/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/review`,
|
||||
{ decision, remark },
|
||||
{ params: { customerId } },
|
||||
|
||||
@@ -5,7 +5,7 @@ defineProps<{ domain: string }>()
|
||||
<template>
|
||||
<el-alert class="contract-pending" type="warning" :closable="false" show-icon>
|
||||
<template #title>{{ domain }}海外区域接口待接入</template>
|
||||
<p>后端边界已固定为 gateway-overseas → lastleg-service / warehouse-overseas-service;统一海外 Base/Token 选择及本页面端点、DTO 与权限适配完成前,不展示演示数据,也不会模拟查询或写操作成功。</p>
|
||||
<p>当前功能尚未完成接口接入,暂不可操作。</p>
|
||||
</el-alert>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -257,21 +257,6 @@ describe('LastMileOrdersView pending order and container conversion', () => {
|
||||
expect((button(wrapper, '生成入库计划')!.element as HTMLButtonElement).disabled).toBe(true)
|
||||
})
|
||||
|
||||
it.each(['WAREHOUSE_TRANSFER', 'RELABEL_APPLICATION', 'RETURN_RELABEL'])(
|
||||
'does not offer an inbound plan for %s orders',
|
||||
async (orderType) => {
|
||||
canAccess.mockReturnValue(true)
|
||||
vi.mocked(listLastMileOrders).mockResolvedValue({ records: [{
|
||||
id: `order-${orderType}`, customerId, orderNo: `LM-${orderType}`, currentStatus: 'PENDING_REVIEW', orderType,
|
||||
}], page: 1, size: 10, total: 1, pages: 1 })
|
||||
|
||||
const wrapper = await mountView()
|
||||
const row = (wrapper.findComponent(DataTable).props('data') as object[])[0]
|
||||
expect(wrapper.get('.el-table__body-wrapper .row-actions').text()).not.toContain('生成入库计划')
|
||||
expect((wrapper.vm as unknown as { canGenerateInboundPlan: (source: object) => boolean }).canGenerateInboundPlan(row)).toBe(false)
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps the original pending order table and does not render a view switch or container table', async () => {
|
||||
const wrapper = await openPending()
|
||||
expect(wrapper.text()).toContain('尾程单号')
|
||||
|
||||
@@ -15,7 +15,7 @@ import LoadErrorState from '@/shared/components/LoadErrorState.vue'
|
||||
import OperationErrorToast from '@/shared/components/OperationErrorToast.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import RowActions, { type RowActionItem } from '@/shared/components/RowActions.vue'
|
||||
import { changeContainerReceivingWarehouse, convertLastMileContainerToInboundPlans, createManualInboundPlan, downloadLastMileOrders, getContainerInboundPlanPreview, getContainerPlanProgress, getLastMileOrderManualNodes, listContainerPlanProgress, listLastMileOrders, reviewCargoDiscardOrder, reviewDirectRelabelOrder, reviewReturnOrder, transferLastMileOrders, updateLastMileOrderHold, updateLastMileOrderManualNodes, type ContainerInboundPlanPreviewDto, type ContainerInboundPlanPreviewGroupDto, type ContainerInboundPlanPreviewOrderDto, type ContainerPlanProgressDetailDto, type ContainerPlanProgressSummaryDto, type ManualNodeCode } from '../api/lastMileOrders'
|
||||
import { changeContainerReceivingWarehouse, convertLastMileContainerToInboundPlans, createManualInboundPlan, downloadLastMileOrders, getContainerInboundPlanPreview, getContainerPlanProgress, getLastMileOrderManualNodes, listContainerPlanProgress, listLastMileOrders, reviewDirectRelabelOrder, reviewReturnOrder, transferLastMileOrders, updateLastMileOrderHold, updateLastMileOrderManualNodes, type ContainerInboundPlanPreviewDto, type ContainerInboundPlanPreviewGroupDto, type ContainerInboundPlanPreviewOrderDto, type ContainerPlanProgressDetailDto, type ContainerPlanProgressSummaryDto, type ManualNodeCode } from '../api/lastMileOrders'
|
||||
import OrderReferenceText from '../components/OrderReferenceText.vue'
|
||||
import WarehouseTransferReviewDialog from '../components/WarehouseTransferReviewDialog.vue'
|
||||
import { confirmRelabelCompletion, createReturnPackingPlan, getRelabelReviewTask, returnRelabelForRework, type ReturnPackingPlanBox } from '../api/relabelOrders'
|
||||
@@ -474,8 +474,6 @@ function hasSelectedRejectedReturn() { return selectedRows.value.some(isRejected
|
||||
function hasSelectedInboundPlan() { return selectedRows.value.some(hasInboundPlan) }
|
||||
const inboundPlanExcludedOrderTypes = new Set(['WAREHOUSE_TRANSFER', 'RELABEL_APPLICATION', 'RETURN_RELABEL'])
|
||||
function canGenerateInboundPlan(row: LastMileOrderListItem) {
|
||||
// Older list responses expose the same value as orderType; keep the action
|
||||
// gate correct while the API rollout is mixed across environments.
|
||||
return !inboundPlanExcludedOrderTypes.has(String(row.orderTypeCode || row.orderType || ''))
|
||||
}
|
||||
async function loadTransferWarehouseOptions() {
|
||||
@@ -532,7 +530,6 @@ function idempotencyKey(prefix: string) {
|
||||
function openInboundPlan(source?: object) {
|
||||
const target = source ? source as LastMileOrderListItem : (selectedRows.value.length === 1 ? selectedRows.value[0] : null)
|
||||
if (!target) { ElMessage.warning('生成入库计划时请选择 1 条尾程订单'); return }
|
||||
if (!canGenerateInboundPlan(target)) { ElMessage.warning('当前业务单不需要生成入库计划'); return }
|
||||
if (isRejectedReturn(target)) { ElMessage.warning('已驳回的退货预报只能查看详情'); return }
|
||||
if (hasInboundPlan(target)) { ElMessage.warning('当前订单已提交入库计划,不能重复生成'); return }
|
||||
if (target.detained) { ElMessage.warning('订单处于暂扣状态,解除暂扣后才能生成入库计划'); return }
|
||||
@@ -858,26 +855,6 @@ async function reviewDirectRelabel(source: object) {
|
||||
} else if (error !== 'close') ElMessage.error(getApiErrorDetails(error, '贴标单审核失败').message)
|
||||
}
|
||||
}
|
||||
async function reviewCargoDiscard(source: object) {
|
||||
const row = source as LastMileOrderListItem
|
||||
const discardNo = row.orderNo
|
||||
if (!discardNo || discardNo === '—' || !row.customerId) return
|
||||
try {
|
||||
await ElMessageBox.confirm('审核通过后,货物废弃单将推送到 PDA,仓库按托盘填写实际废弃数量。', '货物废弃审核', { confirmButtonText: '审核通过', cancelButtonText: '驳回', distinguishCancelAndClose: true })
|
||||
await reviewCargoDiscardOrder(discardNo, row.customerId, 'APPROVE')
|
||||
ElMessage.success('货物废弃单已审核通过,已推送 PDA 废弃出库作业')
|
||||
await load()
|
||||
} catch (error) {
|
||||
if (error === 'cancel') {
|
||||
try {
|
||||
const { value } = await ElMessageBox.prompt('请填写驳回原因', '驳回货物废弃单', { inputType: 'textarea', inputValidator: (input) => Boolean(input?.trim()) || '请填写驳回原因', confirmButtonText: '确认驳回', cancelButtonText: '取消' })
|
||||
await reviewCargoDiscardOrder(discardNo, row.customerId, 'REJECT', value)
|
||||
ElMessage.success('货物废弃单已驳回')
|
||||
await load()
|
||||
} catch (rejectError) { if (rejectError !== 'cancel' && rejectError !== 'close') ElMessage.error(getApiErrorDetails(rejectError, '货物废弃审核失败').message) }
|
||||
} else if (error !== 'close') ElMessage.error(getApiErrorDetails(error, '货物废弃审核失败').message)
|
||||
}
|
||||
}
|
||||
function canConfirmRelabel(row: { relabelStatusCode?: string }) { return row.relabelStatusCode === 'CUSTOMER_CONFIRM_PENDING' }
|
||||
function canReworkRelabel(row: { relabelStatusCode?: string }) { return ['CUSTOMER_CONFIRM_PENDING', 'PROCESSING'].includes(row.relabelStatusCode ?? '') }
|
||||
function hasRelabelActions(row: LastMileOrderListItem) {
|
||||
@@ -904,9 +881,8 @@ function lastMileRowActions(row: LastMileOrderListItem): RowActionItem[] {
|
||||
{ key: 'detail', label: '查看', priority: 500 },
|
||||
{ key: 'review-direct-relabel', label: '审核', priority: 470, tone: 'warning', visible: access.can(permission.lastMileOrderTransfer) && row.orderTypeCode === 'RELABEL_APPLICATION' && row.currentStatusCode === 'PENDING_REVIEW' },
|
||||
{ key: 'review-return', label: '审核', priority: 460, tone: 'warning', visible: access.can(permission.returnOrderReview) && row.orderTypeCode === 'RETURN_RELABEL' && row.currentStatusCode === 'PENDING_REVIEW' },
|
||||
{ key: 'review-cargo-discard', label: '审核', priority: 455, tone: 'warning', visible: (access.can(permission.cargoDiscardApprove) || access.can(permission.warehouseTransferApprove)) && row.orderTypeCode === 'CARGO_DISCARD' && row.currentStatusCode === 'PENDING_REVIEW' },
|
||||
{ key: 'review', label: '审核', priority: 450, tone: 'warning', visible: access.can(permission.warehouseTransferApprove) && row.orderTypeCode === 'WAREHOUSE_TRANSFER' && row.currentStatusCode === 'PENDING_REVIEW' },
|
||||
{ key: 'inbound-plan', label: '生成入库计划', priority: 400, visible: access.can(permission.inboundOrderCreate) && canGenerateInboundPlan(row) && !inboundPlanCreated },
|
||||
{ key: 'inbound-plan', label: '生成入库计划', priority: 400, visible: access.can(permission.inboundOrderCreate) && !inboundPlanCreated },
|
||||
{ key: 'hold', label: row.detained ? '解除暂扣' : '暂扣订单', priority: 300, tone: 'warning', visible: access.can(permission.lastMileOrderTransfer) && (row.detained || row.currentStatusCode === 'INBOUND_COMPLETED') },
|
||||
{ key: 'manual-nodes', label: '人工修改节点', priority: 200, visible: access.can(permission.lastMileOrderTransfer) },
|
||||
{ key: 'confirm-relabel', label: '换标完成确认', priority: 150, visible: access.can(permission.relabelOrderStatus) && Boolean(row.relabelOrderNo) && canConfirmRelabel(row) },
|
||||
@@ -917,7 +893,6 @@ function handleLastMileRowAction(command: string, row: LastMileOrderListItem) {
|
||||
if (command === 'detail') openDetail(row)
|
||||
else if (command === 'review-direct-relabel') void reviewDirectRelabel(row)
|
||||
else if (command === 'review-return') void reviewReturn(row)
|
||||
else if (command === 'review-cargo-discard') void reviewCargoDiscard(row)
|
||||
else if (command === 'review') openTransferReview(row)
|
||||
else if (command === 'inbound-plan') openInboundPlan(row)
|
||||
else if (command === 'hold') openHold(row)
|
||||
|
||||
@@ -31,14 +31,11 @@ const warehousesLoading = ref(false)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const total = ref(0)
|
||||
const filters = ref<QueryModel>({ relabelNo: '', sku: '', status: '', reviewedDates: [], measuredDates: [], outboundDates: [] })
|
||||
const filters = ref<QueryModel>({ relabelNo: '', sku: '', status: '' })
|
||||
const fields = computed<QueryField[]>(() => [
|
||||
{ key: 'relabelNo', type: 'input', label: '换标单号', placeholder: '请输入换标单号', width: 220 },
|
||||
{ key: 'sku', type: 'input', label: '商品SKU', placeholder: '请输入商品SKU', width: 180 },
|
||||
{ key: 'status', type: 'select', label: '状态', placeholder: '全部状态', width: 160, options: [{ label: '待审核', value: 'PENDING_REVIEW' }, { label: '待处理', value: 'PENDING_PROCESSING' }, { label: '处理中', value: 'PROCESSING' }, { label: '换标完成', value: 'COMPLETED' }] },
|
||||
{ key: 'reviewedDates', type: 'daterange', label: '审核时间', width: 240 },
|
||||
{ key: 'measuredDates', type: 'daterange', label: '测量时间', width: 240 },
|
||||
{ key: 'outboundDates', type: 'daterange', label: '出库时间', width: 240 },
|
||||
])
|
||||
const columns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 180, fixed: 'left', slotName: 'actions' },
|
||||
@@ -53,9 +50,6 @@ const columns: DataTableColumn[] = [
|
||||
{ key: 'labelRequirement', label: '贴标要求', minWidth: 150 },
|
||||
{ key: 'fileName', label: '上传文件', minWidth: 160 },
|
||||
{ key: 'status', label: '状态', width: 110 },
|
||||
{ key: 'reviewedAt', label: '审核时间', minWidth: 170 },
|
||||
{ key: 'measuredAt', label: '测量时间', minWidth: 170 },
|
||||
{ key: 'outboundAt', label: '出库时间', minWidth: 170 },
|
||||
{ key: 'createdAt', label: '创建时间', minWidth: 170 },
|
||||
]
|
||||
const dialogOpen = ref(false)
|
||||
@@ -217,13 +211,10 @@ async function load(model: QueryModel = filters.value) {
|
||||
Object.assign(filters.value, model)
|
||||
loading.value = true; loadError.value = null
|
||||
try {
|
||||
const reviewedDates = Array.isArray(filters.value.reviewedDates) ? filters.value.reviewedDates : []
|
||||
const measuredDates = Array.isArray(filters.value.measuredDates) ? filters.value.measuredDates : []
|
||||
const outboundDates = Array.isArray(filters.value.outboundDates) ? filters.value.outboundDates : []
|
||||
const result = await listRelabelOrders({ page: page.value, size: pageSize.value, relabelNo: String(filters.value.relabelNo || '').trim() || undefined, skuCode: String(filters.value.sku || '').trim() || undefined, status: String(filters.value.status || '').trim() || undefined, reviewedFrom: String(reviewedDates[0] || '') || undefined, reviewedTo: String(reviewedDates[1] || '') || undefined, measuredFrom: String(measuredDates[0] || '') || undefined, measuredTo: String(measuredDates[1] || '') || undefined, outboundFrom: String(outboundDates[0] || '') || undefined, outboundTo: String(outboundDates[1] || '') || undefined })
|
||||
const result = await listRelabelOrders({ page: page.value, size: pageSize.value, relabelNo: String(filters.value.relabelNo || '').trim() || undefined, skuCode: String(filters.value.sku || '').trim() || undefined, status: String(filters.value.status || '').trim() || undefined })
|
||||
rows.value = result.records.map((item) => ({
|
||||
customerId: '', orderNo: String(item.relabelNo), relatedOrderNo: String(item.lastlegOrderNo || item.customerOrderNo || '—'), sku: String(item.skuCodes || '—'),
|
||||
productName: '—', cartons: Number(item.totalPackageCount || 0), budgetTotal: null, relabelCost: Number(item.chargeAmount || 0), walletStatus: walletStatus(item.walletStatus), walletErrorMessage: item.walletErrorMessage || '', labelRequirement: '—', fileName: '—', status: relabelStatus(item.status), rawStatus: String(item.status || ''), remark: '', reviewedAt: item.reviewedAt, measuredAt: item.measuredAt, outboundAt: item.outboundAt,
|
||||
productName: '—', cartons: Number(item.totalPackageCount || 0), budgetTotal: null, relabelCost: Number(item.chargeAmount || 0), walletStatus: walletStatus(item.walletStatus), walletErrorMessage: item.walletErrorMessage || '', labelRequirement: '—', fileName: '—', status: relabelStatus(item.status), rawStatus: String(item.status || ''), remark: '',
|
||||
reviewChannel: item.reviewChannel || undefined,
|
||||
createdAt: formatOverseasDateTime(item.createdAt),
|
||||
}))
|
||||
|
||||
@@ -409,7 +409,7 @@ describe('overseas warehouse first-batch prototype contract', () => {
|
||||
'inTransit', 'updatedAt',
|
||||
])
|
||||
expect(columnKeys('RelabelOrdersView.vue')).toEqual([
|
||||
'actions', 'orderNo', 'sku', 'productName', 'cartons', 'budgetTotal', 'relabelCost', 'walletStatus', 'labelRequirement', 'fileName', 'status', 'reviewedAt', 'measuredAt', 'outboundAt', 'createdAt',
|
||||
'actions', 'orderNo', 'sku', 'productName', 'cartons', 'budgetTotal', 'relabelCost', 'walletStatus', 'labelRequirement', 'fileName', 'status', 'createdAt',
|
||||
])
|
||||
expect(columnKeys('PalletsView.vue')).toEqual([
|
||||
'actions', 'code', 'type', 'warehouse', 'volume', 'purchasePrice', 'fbaWarehouse', 'status', 'remark',
|
||||
|
||||
@@ -3,7 +3,6 @@ export const overseasWarehousePermissions = {
|
||||
lastMileOrderExport: 'platform:overseas-warehouse:last-mile-order:export',
|
||||
lastMileOrderTransfer: 'platform:overseas-warehouse:last-mile-order:edit',
|
||||
warehouseTransferApprove: 'platform:overseas-warehouse:warehouse-transfer:approve',
|
||||
cargoDiscardApprove: 'platform:overseas-warehouse:discard:approve',
|
||||
inboundOrderList: 'platform:overseas-warehouse:inbound-order:list',
|
||||
inboundOrderCreate: 'platform:overseas-warehouse:inbound-order:create',
|
||||
inboundOrderEdit: 'platform:overseas-warehouse:inbound-order:edit',
|
||||
|
||||
@@ -153,9 +153,6 @@ export interface RelabelOrderListItem {
|
||||
status: string
|
||||
rawStatus?: string
|
||||
reviewChannel?: 'TAIL_ORDER' | 'RELABEL_ORDER'
|
||||
reviewedAt?: string | null
|
||||
measuredAt?: string | null
|
||||
outboundAt?: string | null
|
||||
remark: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
@@ -145,8 +145,8 @@ const exceptionPath = '/platform/v1/sailing-assignments/exceptions'
|
||||
function channel(raw: SailingChannelResource): SailingChannelResource { return { ...raw, id: String(raw.id), defaultCutoffDays: number(raw.defaultCutoffDays), version: number(raw.version) } }
|
||||
function template(raw: SailingTemplateResource): SailingTemplateResource { return { ...raw, id: String(raw.id), channelId: String(raw.channelId), warehouseId: String(raw.warehouseId), weekdays: (raw.weekdays || []).map((value) => number(value)), cutoffDays: number(raw.cutoffDays), version: number(raw.version) } }
|
||||
|
||||
export async function listSailingChannels() {
|
||||
const response = await http.get<ApiEnvelope<SailingChannelResource[]>, ApiEnvelope<SailingChannelResource[]>>(channelPath)
|
||||
export async function listSailingChannels(warehouseId?: string) {
|
||||
const response = await http.get<ApiEnvelope<SailingChannelResource[]>, ApiEnvelope<SailingChannelResource[]>>(channelPath, { params: warehouseId ? { warehouseId } : undefined })
|
||||
const result = unwrapApiResponse(response) as SailingChannelResource[] | { records?: SailingChannelResource[] } | null
|
||||
return (Array.isArray(result) ? result : result?.records || []).map(channel)
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,25 +1,8 @@
|
||||
# Admin Shared API Instructions
|
||||
|
||||
## 适用范围与入口
|
||||
|
||||
- 本文件适用于 `src/shared/api/` 及其测试。业务模块只通过领域 `api/` 适配层调用这里的客户端,不在页面和组件直接创建 Axios 实例。
|
||||
- 国内 API 客户端为 `http.ts`;海外 API 客户端为 `overseasHttp.ts`。认证会话编排在 `../../core/auth/auth.ts`,不得在本目录复制登录状态。
|
||||
|
||||
## 国内与海外请求
|
||||
|
||||
- `http` 使用 `VITE_API_BASE_URL`,默认走国内代理;国内登录、刷新和退出仍由统一 Auth 处理。
|
||||
- `overseasHttp` 使用 `VITE_OVERSEAS_API_BASE_URL`,默认 `/overseas-api`;Vite 将该前缀改写为海外 Gateway 的 `/api`。代理上游由开发环境配置,不在源码或指引中记录真实地址。
|
||||
- 登录和刷新响应一次性返回国内 Token、`overseasAccessToken`、`overseasExpiresIn`;`core/auth/auth.ts` 必须原子替换两套访问凭据。不得恢复 Token 兑换端点或让业务模块单独刷新海外 Token。
|
||||
- 海外 Token 只由 `replaceOverseasAccessToken`、`clearOverseasAccessToken` 管理;业务模块不得读写缓存、LocalStorage 或手工拼装 `Authorization`。
|
||||
- 国内、海外 401 共用统一会话刷新编排。海外请求最多统一刷新一次并重放一次;刷新失败按会话失效处理,不循环重试或回退假数据。
|
||||
|
||||
## 领域调用边界
|
||||
|
||||
- 国内业务领域 API 使用 `http`;海外尾程、海外仓资源和海外本土业务使用 `overseasHttp`,不得经国内 Gateway 中转。
|
||||
- 页面只调用所属模块的 API 封装;模块 API 负责路径、DTO 和错误适配,不把 Axios 响应或区域选择泄漏到页面。
|
||||
- 跨区域 Token、Audience、JWKS 和服务通信公共契约读取 `../../../../../docs/跨区域认证与服务通信契约.md`。
|
||||
|
||||
## 修改与验证
|
||||
|
||||
- 修改客户端、拦截器、刷新、Token 生命周期或 Base URL 时,联查 `http.test.ts`、`overseasHttp.test.ts`、`core/auth/auth.test.ts`、Vite 代理、`.env.example` 和全部实际消费者。
|
||||
- 至少运行相关 API/Auth 测试和 `pnpm typecheck`;交付前按项目指引运行完整测试与构建。
|
||||
- 本目录及测试承载统一请求基础设施。全部领域 API 使用 `http.ts`,业务模块不得创建区域客户端或自行持久化 Token。
|
||||
- 会话编排唯一入口为 `../../core/auth/auth.ts`;统一 Access/Refresh Token 由 Auth 签发,并发 401 共用一次刷新,每个原请求最多重放一次。
|
||||
- `VITE_API_BASE_URL` 默认 `/api`,Vite 只通过 `API_PROXY_TARGET` 代理到统一 Gateway,不直连业务服务。
|
||||
- 页面只调用领域 API 封装;模块适配路径、DTO 与错误,不暴露客户端选择或手工 Authorization。
|
||||
- 正式契约见 `../../../../../docs/统一认证与服务通信契约.md`;业务服务仍负责权限和客户隔离。
|
||||
- 修改拦截器、刷新或 Base URL 后联查 `http.test.ts`、`../../core/auth/auth.test.ts`、Vite、`.env.example` 及直接消费者,运行定向测试、`pnpm typecheck`、完整测试与构建。
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from './http'
|
||||
import { overseasHttp } from './overseasHttp'
|
||||
import { getLoadingAssociationSummary, getOverseasInboundCodeRelationship, getPlatformInboundCodeAssociation } from './inboundCodeRelations'
|
||||
|
||||
vi.mock('./http', async (original) => ({ ...(await original<typeof import('./http')>()), http: { get: vi.fn() } }))
|
||||
vi.mock('./overseasHttp', () => ({ overseasHttp: { get: vi.fn() } }))
|
||||
|
||||
describe('inbound-code relationship APIs', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('uses the frozen domestic and overseas read models and encodes the business code', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { inboundCode: 'IN/01', orderNo: 'ORD-1' } })
|
||||
vi.mocked(overseasHttp.get).mockResolvedValue({ code: '200', data: { inboundCode: 'IN/01', found: false, taillegOrders: [], inboundPlans: [], palletCodes: [], inventory: [] } })
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', data: { inboundCode: 'IN/01', found: false, taillegOrders: [], inboundPlans: [], palletCodes: [], inventory: [] } })
|
||||
await getPlatformInboundCodeAssociation('IN/01')
|
||||
await getLoadingAssociationSummary('IN/01')
|
||||
await getOverseasInboundCodeRelationship('IN/01')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/orders/first-leg/inbound-code-associations/IN%2F01')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/first-leg/loading-associations/summary', { params: { inboundCode: 'IN/01' } })
|
||||
expect(overseasHttp.get).toHaveBeenCalledWith('/platform/v1/last-leg/inventory/inbound-code-relationships/IN%2F01')
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/last-leg/inventory/inbound-code-relationships/IN%2F01')
|
||||
})
|
||||
|
||||
it('does not accept customer or internal ids as lookup parameters', () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from './http'
|
||||
import { overseasHttp } from './overseasHttp'
|
||||
|
||||
export interface PlatformInboundCodeAssociation {
|
||||
inboundCode: string
|
||||
@@ -68,7 +67,7 @@ export async function getLoadingAssociationSummaryByInboundId(inboundId: string)
|
||||
}
|
||||
|
||||
export async function getOverseasInboundCodeRelationship(inboundCode: string) {
|
||||
const response = await overseasHttp.get<ApiEnvelope<OverseasInboundCodeRelationship>, ApiEnvelope<OverseasInboundCodeRelationship>>(
|
||||
const response = await http.get<ApiEnvelope<OverseasInboundCodeRelationship>, ApiEnvelope<OverseasInboundCodeRelationship>>(
|
||||
`/platform/v1/last-leg/inventory/inbound-code-relationships/${encodeURIComponent(inboundCode)}`,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import axios, { type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { registerAuthRefreshHandler } from './http'
|
||||
import { clearOverseasAccessToken, overseasHttp, replaceOverseasAccessToken } from './overseasHttp'
|
||||
|
||||
const originalOverseasAdapter = overseasHttp.defaults.adapter
|
||||
|
||||
function success(config: InternalAxiosRequestConfig, data: unknown) {
|
||||
return Promise.resolve({ status: 200, statusText: 'OK', headers: {}, config, data })
|
||||
}
|
||||
|
||||
describe('overseas HTTP client', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.setItem('cc-admin-token', 'domestic-token')
|
||||
clearOverseasAccessToken()
|
||||
registerAuthRefreshHandler(async () => 'domestic-token')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
overseasHttp.defaults.adapter = originalOverseasAdapter
|
||||
localStorage.clear()
|
||||
clearOverseasAccessToken()
|
||||
})
|
||||
|
||||
it('uses the overseas token supplied by the login session for concurrent requests', async () => {
|
||||
replaceOverseasAccessToken('overseas-token', 900)
|
||||
const authorizations: unknown[] = []
|
||||
overseasHttp.defaults.adapter = async (config) => {
|
||||
authorizations.push(config.headers.Authorization)
|
||||
return success(config, { code: '200', message: 'success', data: [] })
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
overseasHttp.get('/platform/v1/last-leg/orders'),
|
||||
overseasHttp.get('/platform/v1/warehouse-admin'),
|
||||
])
|
||||
|
||||
expect(authorizations).toEqual(['Bearer overseas-token', 'Bearer overseas-token'])
|
||||
})
|
||||
|
||||
it('refreshes the unified session once and replays once after an overseas 401', async () => {
|
||||
replaceOverseasAccessToken('overseas-1', 900)
|
||||
const refresh = vi.fn(async () => {
|
||||
replaceOverseasAccessToken('overseas-2', 900)
|
||||
return 'domestic-2'
|
||||
})
|
||||
registerAuthRefreshHandler(refresh)
|
||||
let requests = 0
|
||||
const authorizations: unknown[] = []
|
||||
overseasHttp.defaults.adapter = async (config) => {
|
||||
authorizations.push(config.headers.Authorization)
|
||||
if (requests++ === 0) {
|
||||
throw new axios.AxiosError('Unauthorized', 'ERR_BAD_REQUEST', config, undefined, {
|
||||
status: 401,
|
||||
statusText: 'Unauthorized',
|
||||
headers: {},
|
||||
config,
|
||||
data: { code: 'A0401', message: '海外令牌失效' },
|
||||
})
|
||||
}
|
||||
return success(config, { code: '200', message: 'success', data: [] })
|
||||
}
|
||||
|
||||
await overseasHttp.get('/platform/v1/last-leg/orders')
|
||||
|
||||
expect(refresh).toHaveBeenCalledTimes(1)
|
||||
expect(requests).toBe(2)
|
||||
expect(authorizations).toEqual(['Bearer overseas-1', 'Bearer overseas-2'])
|
||||
})
|
||||
|
||||
it('refreshes the unified session when no usable overseas token is present', async () => {
|
||||
const refresh = vi.fn(async () => {
|
||||
replaceOverseasAccessToken('overseas-refreshed', 900)
|
||||
return 'domestic-refreshed'
|
||||
})
|
||||
registerAuthRefreshHandler(refresh)
|
||||
let authorization: unknown
|
||||
overseasHttp.defaults.adapter = async (config) => {
|
||||
authorization = config.headers.Authorization
|
||||
return success(config, { code: '200', message: 'success', data: [] })
|
||||
}
|
||||
|
||||
await overseasHttp.get('/platform/v1/last-leg/orders')
|
||||
|
||||
expect(refresh).toHaveBeenCalledTimes(1)
|
||||
expect(authorization).toBe('Bearer overseas-refreshed')
|
||||
})
|
||||
|
||||
it('fails before sending a business request when refresh is domestic-only', async () => {
|
||||
const refresh = vi.fn(async () => 'domestic-only')
|
||||
registerAuthRefreshHandler(refresh)
|
||||
const adapter = vi.fn(async (config: InternalAxiosRequestConfig) => success(config, { code: '200', message: 'success', data: [] }))
|
||||
overseasHttp.defaults.adapter = adapter
|
||||
|
||||
await expect(overseasHttp.get('/platform/v1/last-leg/orders')).rejects.toThrow('当前环境未签发海外访问令牌')
|
||||
expect(refresh).toHaveBeenCalledTimes(1)
|
||||
expect(adapter).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,77 +0,0 @@
|
||||
import axios, { type InternalAxiosRequestConfig } from 'axios'
|
||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||
import { refreshAuthenticatedSession } from './http'
|
||||
|
||||
interface CachedOverseasToken {
|
||||
accessToken: string
|
||||
refreshAfter: number
|
||||
}
|
||||
|
||||
type RetryableOverseasRequestConfig = InternalAxiosRequestConfig & { _overseasAuthRetry?: boolean }
|
||||
|
||||
const TOKEN_REFRESH_SAFETY_WINDOW_MS = 30_000
|
||||
|
||||
let cachedToken: CachedOverseasToken | null = null
|
||||
|
||||
export const overseasHttp = axios.create({
|
||||
baseURL: import.meta.env.VITE_OVERSEAS_API_BASE_URL || '/overseas-api',
|
||||
timeout: 15_000,
|
||||
transformResponse: [(data: unknown) => parseApiJsonResponse(data)],
|
||||
})
|
||||
|
||||
function currentOverseasAccessToken() {
|
||||
return cachedToken && cachedToken.refreshAfter > Date.now() ? cachedToken.accessToken : ''
|
||||
}
|
||||
|
||||
async function requireOverseasAccessToken() {
|
||||
const current = currentOverseasAccessToken()
|
||||
if (current) return current
|
||||
await refreshAuthenticatedSession()
|
||||
const refreshed = currentOverseasAccessToken()
|
||||
if (!refreshed) throw new Error('当前环境未签发海外访问令牌')
|
||||
return refreshed
|
||||
}
|
||||
|
||||
export function replaceOverseasAccessToken(accessToken: string | null, expiresIn: number) {
|
||||
if (!accessToken && expiresIn === 0) {
|
||||
cachedToken = null
|
||||
return
|
||||
}
|
||||
if (!accessToken || !Number.isFinite(expiresIn) || expiresIn <= 0) {
|
||||
throw new Error('海外访问令牌响应无效')
|
||||
}
|
||||
cachedToken = {
|
||||
accessToken,
|
||||
refreshAfter: Date.now() + Math.max(0, expiresIn * 1000 - TOKEN_REFRESH_SAFETY_WINDOW_MS),
|
||||
}
|
||||
}
|
||||
|
||||
export function clearOverseasAccessToken() {
|
||||
cachedToken = null
|
||||
}
|
||||
|
||||
overseasHttp.interceptors.request.use(async (config) => {
|
||||
const accessToken = await requireOverseasAccessToken()
|
||||
config.headers.Authorization = `Bearer ${accessToken}`
|
||||
return config
|
||||
})
|
||||
|
||||
overseasHttp.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
async (error) => {
|
||||
const config = error.config as RetryableOverseasRequestConfig | undefined
|
||||
if (error.response?.status !== 401 || !config || config._overseasAuthRetry) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
config._overseasAuthRetry = true
|
||||
clearOverseasAccessToken()
|
||||
try {
|
||||
await refreshAuthenticatedSession()
|
||||
const accessToken = await requireOverseasAccessToken()
|
||||
config.headers.Authorization = `Bearer ${accessToken}`
|
||||
return overseasHttp.request(config)
|
||||
} catch {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
import axios from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http, registerAuthRefreshHandler } from './http'
|
||||
|
||||
const originalAdapter = http.defaults.adapter
|
||||
const paths = ['/platform/v1/orders', '/platform/v1/last-leg/orders', '/platform/v1/overseas-warehouse-resources/pallets']
|
||||
|
||||
describe('unified business session', () => {
|
||||
beforeEach(() => localStorage.setItem('cc-admin-token', 'session-1'))
|
||||
afterEach(() => {
|
||||
http.defaults.adapter = originalAdapter
|
||||
localStorage.clear()
|
||||
registerAuthRefreshHandler(async () => { throw new Error('no active test session') })
|
||||
})
|
||||
|
||||
it('uses one base URL and the same token across order, lastleg and warehouse resources', async () => {
|
||||
const requests: unknown[] = []
|
||||
const refresh = vi.fn()
|
||||
registerAuthRefreshHandler(refresh)
|
||||
http.defaults.adapter = async (config) => {
|
||||
requests.push([config.baseURL, config.headers.Authorization])
|
||||
return { status: 200, statusText: 'OK', headers: {}, config, data: { code: '200', data: [] } }
|
||||
}
|
||||
await Promise.all(paths.map(path => http.get(path)))
|
||||
expect(requests).toEqual(paths.map(() => [http.defaults.baseURL, 'Bearer session-1']))
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shares a single refresh across simultaneous 401s from both business domains', async () => {
|
||||
const refresh = vi.fn(async () => {
|
||||
await Promise.resolve()
|
||||
localStorage.setItem('cc-admin-token', 'session-2')
|
||||
return 'session-2'
|
||||
})
|
||||
registerAuthRefreshHandler(refresh)
|
||||
const successes: string[] = []
|
||||
http.defaults.adapter = async (config) => {
|
||||
if (config.headers.Authorization === 'Bearer session-1') {
|
||||
throw new axios.AxiosError('Unauthorized', 'ERR_BAD_REQUEST', config, undefined,
|
||||
{ status: 401, statusText: 'Unauthorized', headers: {}, config, data: {} })
|
||||
}
|
||||
successes.push(String(config.headers.Authorization))
|
||||
return { status: 200, statusText: 'OK', headers: {}, config, data: { code: '200', data: [] } }
|
||||
}
|
||||
await Promise.all(paths.map(path => http.get(path)))
|
||||
expect(refresh).toHaveBeenCalledTimes(1)
|
||||
expect(successes).toEqual(paths.map(() => 'Bearer session-2'))
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user