Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test
This commit is contained in:
+83
-7
@@ -1,6 +1,6 @@
|
||||
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||
import { accessTokenIdentity, clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
||||
import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
|
||||
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
|
||||
@@ -13,6 +13,8 @@ const transport = axios.create({
|
||||
|
||||
interface RetryableRequest extends InternalAxiosRequestConfig {
|
||||
_retriedAfterRefresh?: boolean
|
||||
_sessionIdentity?: string | null
|
||||
_logoutGeneration?: number
|
||||
}
|
||||
|
||||
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
||||
@@ -51,9 +53,12 @@ function mapError(error: unknown) {
|
||||
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
|
||||
let refreshExchange: { identity: string; refreshToken: string; promise: Promise<TokenPair> } | null = null
|
||||
let logoutGeneration = 0
|
||||
let refreshPromise: Promise<string> | null = null
|
||||
let refreshIdentity: string | null = null
|
||||
let redirectingToLogin = false
|
||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/impersonations/exchange']
|
||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout', '/auth/impersonations/exchange']
|
||||
|
||||
function isPublicAuthRequest(url?: string) {
|
||||
return publicAuthPaths.some((path) => url?.endsWith(path))
|
||||
@@ -70,29 +75,46 @@ function redirectToLoginAfterSessionExpiry() {
|
||||
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
||||
}
|
||||
|
||||
function requireCurrentIdentity(identity: string | null | undefined, accessToken = getAccessToken()) {
|
||||
if (!identity || accessTokenIdentity(accessToken) !== identity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
}
|
||||
|
||||
export async function refreshAuthenticatedSession() {
|
||||
const observedIdentity = accessTokenIdentity(getAccessToken())
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const observedRefreshToken = getRefreshToken()
|
||||
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||
if (!refreshPromise) {
|
||||
refreshIdentity = observedIdentity
|
||||
refreshPromise = coordinateCrossTabRefresh({
|
||||
lockName: 'cc-client-auth-refresh',
|
||||
observedRefreshToken,
|
||||
currentRefreshToken: getRefreshToken,
|
||||
reuseCurrentSession: async () => {
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const currentAccessToken = getAccessToken()
|
||||
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||
return currentAccessToken
|
||||
},
|
||||
refresh: async (currentRefreshToken) => {
|
||||
const response = await transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken })
|
||||
const tokens = unwrap(response.data)
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const exchange = { identity: observedIdentity!, refreshToken: currentRefreshToken, promise: transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }).then(response => unwrap(response.data)) }
|
||||
refreshExchange = exchange
|
||||
let tokens: TokenPair
|
||||
try { tokens = await exchange.promise } finally { if (refreshExchange === exchange) refreshExchange = null }
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
requireCurrentIdentity(observedIdentity, tokens.accessToken)
|
||||
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
||||
if (getRefreshToken() !== currentRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||
persistTokenPair(tokens)
|
||||
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('cc-client-session-updated'))
|
||||
return tokens.accessToken
|
||||
},
|
||||
})
|
||||
.catch((error) => {
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
if (error instanceof CrossTabRefreshTimeoutError) {
|
||||
if (getRefreshToken() && getRefreshToken() !== observedRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||
const expiredError = new ApiError(error.message, 'A0401', 401)
|
||||
clearSessionTokens()
|
||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||
@@ -103,33 +125,60 @@ export async function refreshAuthenticatedSession() {
|
||||
})
|
||||
.finally(() => {
|
||||
refreshPromise = null
|
||||
refreshIdentity = null
|
||||
})
|
||||
}
|
||||
return refreshPromise
|
||||
if (refreshIdentity !== observedIdentity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
const refreshed = await refreshPromise
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
return refreshed
|
||||
}
|
||||
|
||||
transport.interceptors.request.use((config) => {
|
||||
const token = getAccessToken()
|
||||
if (token && !isPublicAuthRequest(config.url)) config.headers.Authorization = `Bearer ${token}`
|
||||
const request = config as RetryableRequest
|
||||
if (request._retriedAfterRefresh && !isPublicAuthRequest(config.url)) requireCurrentIdentity(request._sessionIdentity, token)
|
||||
if (token && !isPublicAuthRequest(config.url)) {
|
||||
if (!request._retriedAfterRefresh) {
|
||||
request._sessionIdentity = accessTokenIdentity(token)
|
||||
request._logoutGeneration = logoutGeneration
|
||||
}
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
transport.interceptors.response.use(
|
||||
(response) => response,
|
||||
(response) => {
|
||||
const request = response.config as RetryableRequest
|
||||
if (request._sessionIdentity) {
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
}
|
||||
return response
|
||||
},
|
||||
async (error: AxiosError) => {
|
||||
const request = error.config as RetryableRequest | undefined
|
||||
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
|
||||
throw mapError(error)
|
||||
}
|
||||
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
request._retriedAfterRefresh = true
|
||||
const refreshTokenBeforeRetry = getRefreshToken()
|
||||
try {
|
||||
const accessToken = await refreshAuthenticatedSession()
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
request.headers.Authorization = `Bearer ${accessToken}`
|
||||
return await transport.request(request)
|
||||
} catch (refreshError) {
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
const mappedError = mapError(refreshError)
|
||||
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
||||
if (getRefreshToken() && getRefreshToken() !== refreshTokenBeforeRetry) throw mappedError
|
||||
clearSessionTokens()
|
||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||
redirectToLoginAfterSessionExpiry()
|
||||
@@ -139,6 +188,33 @@ transport.interceptors.response.use(
|
||||
},
|
||||
)
|
||||
|
||||
// Captured revocation never persists credentials or restores local login state.
|
||||
export async function revokeCapturedSession(accessToken: string, refreshToken: string) {
|
||||
logoutGeneration++
|
||||
const identity = accessTokenIdentity(accessToken)
|
||||
if (!identity || !refreshToken) throw new ApiError('服务器会话注销未确认', 'SESSION_CHANGED')
|
||||
const pending = refreshExchange?.identity === identity && refreshExchange.refreshToken === refreshToken ? refreshExchange.promise : null
|
||||
const revoke = (pair: Pick<TokenPair, 'accessToken' | 'refreshToken'>) => apiRequest<void>({
|
||||
method: 'POST', url: '/auth/logout', data: { refreshToken: pair.refreshToken },
|
||||
headers: { Authorization: `Bearer ${pair.accessToken}` },
|
||||
})
|
||||
const validate = (pair: TokenPair) => {
|
||||
if (accessTokenIdentity(pair.accessToken) !== identity || !pair.refreshToken) throw new ApiError('刷新身份不一致,服务器会话注销未确认', 'SESSION_CHANGED')
|
||||
return pair
|
||||
}
|
||||
// An already sent refresh can rotate the pair. Consume its actual result
|
||||
// without issuing a competing refresh or restoring it to local storage.
|
||||
if (pending) {
|
||||
await revoke(validate(await pending))
|
||||
return
|
||||
}
|
||||
try { await revoke({ accessToken, refreshToken }) } catch (error) {
|
||||
if (!(error instanceof ApiError) || error.status !== 401) throw error
|
||||
const pair = await apiRequest<TokenPair>({ method: 'POST', url: '/auth/refresh', data: { refreshToken } })
|
||||
await revoke(validate(pair))
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<ApiEnvelope<T>>(config)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
accessTokenIdentity,
|
||||
ACCESS_TOKEN_KEY,
|
||||
REFRESH_TOKEN_KEY,
|
||||
REMEMBERED_LOGIN_ID_KEY,
|
||||
@@ -56,3 +57,34 @@ test('remembers only the login id and keeps it when session tokens are cleared',
|
||||
persistRememberedLoginId('merchant-user', false)
|
||||
assert.equal(getRememberedLoginId(), '')
|
||||
})
|
||||
|
||||
test('normal token rotation never removes either shared token between writes', () => {
|
||||
installStorage()
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, 'old-access')
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, 'old-refresh')
|
||||
const removed = []
|
||||
const remove = localStorage.removeItem
|
||||
localStorage.removeItem = key => { removed.push(key); remove(key) }
|
||||
persistTokenPair({ accessToken: 'new-access', refreshToken: 'new-refresh' })
|
||||
assert.ok(!removed.includes(ACCESS_TOKEN_KEY))
|
||||
assert.ok(!removed.includes(REFRESH_TOKEN_KEY))
|
||||
})
|
||||
|
||||
function rawIdentity(overrides = '') {
|
||||
return `test.${Buffer.from(`{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"${overrides}}`).toString('base64url')}.test`
|
||||
}
|
||||
test('identity preserves low digits of numeric 19 digit user customer and membership',()=>{
|
||||
const original=rawIdentity();const json=Buffer.from(original.split('.')[1],'base64url').toString();
|
||||
for(const field of ['user_id','tenant_id','membership_id']){
|
||||
const changed=json.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`)
|
||||
assert.notEqual(accessTokenIdentity(original),accessTokenIdentity(`test.${Buffer.from(changed).toString('base64url')}.test`))
|
||||
}
|
||||
})
|
||||
test('identity string and numeric integers are equivalent without changing other strings',()=>{
|
||||
const a=rawIdentity();const raw=Buffer.from(a.split('.')[1],'base64url').toString();
|
||||
const b=`test.${Buffer.from(raw.replaceAll(':2107003446494334978',':"2107003446494334978"')).toString('base64url')}.test`
|
||||
assert.equal(accessTokenIdentity(a),accessTokenIdentity(b))
|
||||
const decorated=rawIdentity(',"username":'+JSON.stringify('number 2107003446494334979 and "tenant_id":2107003446494334979')+',"note":"1234567890123456789"')
|
||||
assert.equal(accessTokenIdentity(a),accessTokenIdentity(decorated))
|
||||
assert.ok(accessTokenIdentity(a).includes('2107003446494334978'))
|
||||
})
|
||||
|
||||
+30
-1
@@ -19,9 +19,38 @@ export function getRefreshToken() {
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
// Only binds a retry to its original identity; never grants permissions. Expired
|
||||
// access tokens remain readable here because they are the normal refresh trigger.
|
||||
export function accessTokenIdentity(token: string): string | null {
|
||||
try {
|
||||
const encoded = token.split('.')[1]
|
||||
if (!encoded) return null
|
||||
const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const bytes = Uint8Array.from(atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')), character => character.charCodeAt(0))
|
||||
const json = new TextDecoder().decode(bytes)
|
||||
// Match whole JSON strings first so digits inside arbitrary string values
|
||||
// are never rewritten. Preserve integer identity claims before JSON.parse
|
||||
// can round them; number/string representations then share one identity.
|
||||
const exactIdentityJson = json.replace(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (part, offset: number) => {
|
||||
if (!/^-?\d+$/.test(part)) return part
|
||||
const key = json.slice(0, offset).match(/"(user_id|tenant_id|membership_id|operator_tenant_id)"\s*:\s*$/)
|
||||
return key ? JSON.stringify(part) : part
|
||||
})
|
||||
const value = JSON.parse(exactIdentityJson)
|
||||
if (!value?.user_id || !value.tenant_id || !value.membership_id || value.app_code !== 'MERCHANT') return null
|
||||
return JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type].map(item => item == null ? null : String(item)))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function persistTokenPair(tokens: TokenPair) {
|
||||
clearSessionTokens()
|
||||
// Replace the pair without publishing a transient logout to other tabs.
|
||||
sessionStorage.removeItem(ACCESS_TOKEN_KEY)
|
||||
sessionStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
sessionStorage.removeItem('cc-client-token')
|
||||
localStorage.removeItem('cc-client-token')
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
|
||||
}
|
||||
|
||||
@@ -18,13 +18,21 @@ function compile(name, dependencies = {}) {
|
||||
return exports
|
||||
}
|
||||
|
||||
function access(user, tenant = 1, membership = 1, nonce = 'original') {
|
||||
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, app_code: 'MERCHANT', nonce })).toString('base64url')}.test`
|
||||
}
|
||||
const oldAccess = access(1)
|
||||
const newAccess = access(1, 1, 1, 'rotated')
|
||||
const otherAccess = access(2, 2, 2)
|
||||
|
||||
function harness(adapter) {
|
||||
let token = 'old-access'
|
||||
let token = oldAccess
|
||||
let refreshToken = 'old-refresh'
|
||||
const http = compile('./http.ts', {
|
||||
axios: { ...axios, create: (config) => axios.create({ ...config, adapter }) },
|
||||
'@chongchong/shared': { parseApiJsonResponse: (data) => data },
|
||||
'@/api/session': {
|
||||
accessTokenIdentity: compile('./session.ts').accessTokenIdentity,
|
||||
getAccessToken: () => token, getRefreshToken: () => refreshToken,
|
||||
persistTokenPair: (tokens) => { token = tokens.accessToken; refreshToken = tokens.refreshToken },
|
||||
clearSessionTokens: () => { token = ''; refreshToken = '' },
|
||||
@@ -33,7 +41,7 @@ function harness(adapter) {
|
||||
'@/api/types': compile('./types.ts'),
|
||||
'@/api/crossTabRefresh': compile('./crossTabRefresh.ts'),
|
||||
})
|
||||
return http
|
||||
return { ...http, setSession: (access, refresh) => { token = access; refreshToken = refresh }, session: () => ({ token, refreshToken }) }
|
||||
}
|
||||
|
||||
test('order and lastleg 401s share one refresh and replay the unified access token', async () => {
|
||||
@@ -44,9 +52,9 @@ test('order and lastleg 401s share one refresh and replay the unified access tok
|
||||
if (config.url === '/auth/refresh') {
|
||||
refreshes++
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: 'new-access', refreshToken: 'new-refresh' } } }
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||
}
|
||||
if (config.headers.Authorization === 'Bearer old-access') {
|
||||
if (config.headers.Authorization === `Bearer ${oldAccess}`) {
|
||||
throw new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||
}
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: config.url } }
|
||||
@@ -56,7 +64,7 @@ test('order and lastleg 401s share one refresh and replay the unified access tok
|
||||
assert.equal(refreshes, 1)
|
||||
assert.ok(calls.every((call) => call.base === '/api'))
|
||||
assert.equal(calls.find((call) => call.url === '/auth/refresh').token, undefined)
|
||||
assert.equal(calls.filter((call) => call.token === 'Bearer new-access').length, 2)
|
||||
assert.equal(calls.filter((call) => call.token === `Bearer ${newAccess}`).length, 2)
|
||||
})
|
||||
|
||||
test('successful order submit with explicit null data is accepted', async () => {
|
||||
@@ -76,3 +84,139 @@ test('data-less security failures preserve diagnostics and malformed success is
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test('late refresh response cannot overwrite a session changed in another tab', async () => {
|
||||
let complete, started
|
||||
const ready = new Promise(resolve => { started = resolve })
|
||||
const response = new Promise(resolve => { complete = resolve })
|
||||
const http = harness(async config => { started(); await response; return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: oldAccess, refreshToken: 'stale-refresh' } } } })
|
||||
const pending = http.refreshAuthenticatedSession()
|
||||
await ready
|
||||
http.setSession(otherAccess, 'other-refresh')
|
||||
complete()
|
||||
await pending.catch(error => assert.equal(error.code, 'SESSION_CHANGED'))
|
||||
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'other-refresh' })
|
||||
})
|
||||
|
||||
function deferred() { let resolve; const promise = new Promise(yes => { resolve = yes }); return { promise, resolve } }
|
||||
|
||||
function unauthorized(config) {
|
||||
return new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||
}
|
||||
|
||||
test('late A write 401 after user, customer or membership switch never refreshes or replays under B', async () => {
|
||||
for (const next of [access(2), access(1, 2), access(1, 1, 2)]) {
|
||||
const sent = deferred(), release = deferred(), calls = []
|
||||
const http = harness(async config => {
|
||||
calls.push(config.url); sent.resolve(); await release.promise
|
||||
throw unauthorized(config)
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit', data: { expectedVersion: 1 } })
|
||||
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||
await sent.promise; http.setSession(next, 'refresh-b'); release.resolve(); await rejected
|
||||
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit'])
|
||||
assert.deepEqual(http.session(), { token: next, refreshToken: 'refresh-b' })
|
||||
}
|
||||
})
|
||||
|
||||
test('switch during in-flight refresh cannot reuse B token to replay an A write', async () => {
|
||||
const refreshing = deferred(), release = deferred(), calls = []
|
||||
const http = harness(async config => {
|
||||
calls.push(config.url)
|
||||
if (config.url === '/auth/refresh') {
|
||||
refreshing.resolve(); await release.promise
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||
}
|
||||
throw unauthorized(config)
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||
await refreshing.promise; http.setSession(otherAccess, 'refresh-b'); release.resolve(); await rejected
|
||||
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit', '/auth/refresh'])
|
||||
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'refresh-b' })
|
||||
})
|
||||
|
||||
test('refresh lock wait reuses same-identity rotation but rejects changed-identity reuse', async t => {
|
||||
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
|
||||
t.after(() => { if (originalNavigator) Object.defineProperty(globalThis, 'navigator', originalNavigator); else delete globalThis.navigator })
|
||||
for (const next of [newAccess, otherAccess]) {
|
||||
const waiting = deferred(), release = deferred(), calls = []
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: { request: async (_name, _options, run) => {
|
||||
waiting.resolve(); await release.promise; return run()
|
||||
} } } })
|
||||
const http = harness(async config => {
|
||||
calls.push({ url: config.url, authorization: config.headers.Authorization })
|
||||
if (config.headers.Authorization === `Bearer ${oldAccess}`) throw unauthorized(config)
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: null } }
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||
const outcome = next === otherAccess ? assert.rejects(pending, error => error.code === 'SESSION_CHANGED') : pending
|
||||
await waiting.promise; http.setSession(next, 'rotated-refresh'); release.resolve(); await outcome
|
||||
assert.equal(calls.some(call => call.url === '/auth/refresh'), false)
|
||||
assert.equal(calls.length, next === otherAccess ? 1 : 2)
|
||||
assert.deepEqual(http.session(), { token: next, refreshToken: 'rotated-refresh' })
|
||||
}
|
||||
})
|
||||
|
||||
function authApi(http) { return compile('../modules/auth/api/auth.ts', { '@/api/http': http }) }
|
||||
function ok(config, data = null) { return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data } } }
|
||||
test('logout after immediate local clear revokes captured Bearer and Refresh', async () => {
|
||||
const calls=[]; const http=harness(async c=>{calls.push(c);return ok(c)})
|
||||
http.setSession('', '');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||
assert.equal(calls.length,1);assert.equal(calls[0].headers.Authorization,`Bearer ${oldAccess}`)
|
||||
assert.deepEqual(JSON.parse(calls[0].data),{refreshToken:'old-refresh'});assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('only explicit logout401 refreshes once and revokes same-identity replacement without storing it', async () => {
|
||||
const calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'});if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||
http.setSession('','');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||
assert.deepEqual(calls.map(x=>x.url),['/auth/logout','/auth/refresh','/auth/logout']);assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[2].data).refreshToken,'new-refresh');assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('unknown logout failure never refreshes; changed identity cannot be revoked as replacement', async () => {
|
||||
for(const mode of ['network','wrongIdentity','second401']){const calls=[];const http=harness(async c=>{calls.push(c);if(mode==='network')throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c);if(c.url==='/auth/refresh')return ok(c,{accessToken:mode==='wrongIdentity'?otherAccess:newAccess,refreshToken:'replacement'});throw unauthorized(c)})
|
||||
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(oldAccess,'old-refresh'));assert.equal(calls.length,mode==='network'?1:mode==='wrongIdentity'?2:3);assert.deepEqual(http.session(),{token:'',refreshToken:''})}
|
||||
})
|
||||
test('logout consumes already inflight refresh once while old business caller cannot revive session',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}return ok(c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');release.resolve();await leaving;await rejected
|
||||
assert.deepEqual(calls.map(x=>x.url),['/auth/refresh','/auth/logout']);assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('late successful business response after logout rejects even after same-identity new login',async()=>{
|
||||
const started=deferred(),release=deferred();const http=harness(async c=>{if(c.url==='/merchant/v1/orders'){started.resolve();await release.promise}return ok(c,'old-data')})
|
||||
const pending=http.apiRequest({url:'/merchant/v1/orders'});const rejected=assert.rejects(pending,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||
await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected;assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||
})
|
||||
|
||||
test('inflight refresh unknown outcome stops logout without competing retry and preserves later login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);started.resolve();await release.promise;throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');const failure=assert.rejects(leaving,e=>e.code==='NETWORK_ERROR');http.setSession(otherAccess,'other-refresh');release.resolve();await failure;await rejected
|
||||
assert.equal(calls.length,1);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||
})
|
||||
test('logout401 refresh and replacement revocation cannot overwrite later login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');await started.promise;http.setSession(otherAccess,'other-refresh');release.resolve();await leaving
|
||||
assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||
})
|
||||
test('late old business401 after logout does not refresh or replay under same-identity new login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/merchant/v1/orders/first-leg/one/submit'){started.resolve();await release.promise;throw unauthorized(c)}return ok(c)})
|
||||
const request=http.apiRequest({method:'POST',url:'/merchant/v1/orders/first-leg/one/submit'});const rejected=assert.rejects(request,e=>e.code==='SESSION_CHANGED');await started.promise;await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected
|
||||
assert.deepEqual(calls.map(x=>x.url),['/merchant/v1/orders/first-leg/one/submit','/auth/logout']);assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||
})
|
||||
|
||||
test('same identity new pair logout does not adopt another session inflight refresh',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'old-session-rotated'})}return ok(c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise;http.setSession(newAccess,'new-login-refresh')
|
||||
const leaving=authApi(http).logoutMerchant(newAccess,'new-login-refresh');http.setSession('','');await leaving
|
||||
assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[1].data).refreshToken,'new-login-refresh');release.resolve();await rejected;assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
|
||||
test('logout rejects refreshed 19 digit identity differing only in low digit',async()=>{
|
||||
const raw='{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"}'
|
||||
const original=`test.${Buffer.from(raw).toString('base64url')}.test`
|
||||
for(const field of ['user_id','tenant_id','membership_id']){
|
||||
const changed=raw.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`),calls=[]
|
||||
const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:`test.${Buffer.from(changed).toString('base64url')}.test`,refreshToken:'replacement'});throw unauthorized(c)})
|
||||
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(original,'original-refresh'),e=>e.code==='SESSION_CHANGED');assert.equal(calls.length,2)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,9 +1,76 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { parse, compileScript } from 'vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./DataTable.vue', import.meta.url), 'utf8')
|
||||
|
||||
function paginationHarness(t) {
|
||||
const descriptor = parse(source).descriptor
|
||||
const compiled = compileScript(descriptor, { id: 'data-table-pagination-test' })
|
||||
const code = ts.transpileModule(compiled.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
const deps = { vue, '@lucide/vue': { ChevronLeft: {}, ChevronRight: {} }, './tableActions': {} }
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||
const component = exports.default
|
||||
component.render = () => null
|
||||
const state = vue.reactive({ page: 5, total: 5542, loading: false, error: false })
|
||||
const emitted = []
|
||||
const renderer = vue.createRenderer({
|
||||
createElement: tag => ({ tag }), createText: text => ({ text }), createComment: text => ({ text }),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const app = renderer.createApp({ render: () => vue.h(component, {
|
||||
data: [], columns: [], page: state.page, pageSize: 50, total: state.total, loading: state.loading,
|
||||
'onUpdate:page': value => { emitted.push(value); state.page = value },
|
||||
}, state.error ? { error: () => vue.h('div', 'Request failed') } : {}) })
|
||||
app.mount({})
|
||||
t.after(() => app.unmount())
|
||||
return { state, emitted }
|
||||
}
|
||||
|
||||
test('server-page loading must not reset the requested page when total temporarily clears', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.loading = true; state.total = 0
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
state.total = 5542; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
})
|
||||
|
||||
test('failed server page retains its page for explicit retry and emits no automatic fallback request', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.loading = true; state.total = 0
|
||||
await vue.nextTick()
|
||||
state.error = true; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
state.error = false; state.loading = true
|
||||
await vue.nextTick()
|
||||
state.total = 5542; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
})
|
||||
|
||||
test('settled successful totals still clamp out-of-range and empty pages', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.total = 120
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 3)
|
||||
state.total = 0
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 1)
|
||||
assert.deepEqual(emitted, [3, 1])
|
||||
})
|
||||
|
||||
test('keeps action-only table toolbars on the left', () => {
|
||||
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
|
||||
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
|
||||
|
||||
@@ -88,7 +88,9 @@ watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
|
||||
page.value = 1
|
||||
}, { immediate: true })
|
||||
|
||||
watch([page, pageCount], ([value, count]) => {
|
||||
watch([page, pageCount, () => props.loading, () => Boolean(slots.error)], ([value, count, loading, hasError]) => {
|
||||
// A cleared total is not an authoritative page count while loading or showing a request error.
|
||||
if (loading || hasError) return
|
||||
const nextValue = normalizePage(value, count)
|
||||
if (value !== nextValue) page.value = nextValue
|
||||
}, { immediate: true })
|
||||
|
||||
@@ -26,13 +26,12 @@ test('test deployment requires an explicit shared network, Gateway and version',
|
||||
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, /'java-builder' : '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(new URL(file, root)), false)
|
||||
}
|
||||
assert.match(jenkins, /scripts\/deploy-production\.sh/)
|
||||
assert.match(jenkins, /firstleg-production-ssh/)
|
||||
|
||||
})
|
||||
|
||||
test('application shell is revalidated and missing chunks remain 404', () => {
|
||||
@@ -52,3 +51,13 @@ test('container build excludes local environment values and waits for Nginx heal
|
||||
assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
|
||||
assert.match(jenkins, /up -d --wait --wait-timeout 120/)
|
||||
})
|
||||
|
||||
test('gray production is isolated from TEST and routes to the single Gateway', () => {
|
||||
const production = readFileSync(new URL('docker-compose.production.yml', root), 'utf8')
|
||||
assert.match(production, /name: firstleg-production-network/)
|
||||
assert.match(production, /API_UPSTREAM: "http:\/\/gateway:9000"/)
|
||||
assert.match(production, /127\.0\.0\.1:/)
|
||||
assert.match(production, /healthcheck:/)
|
||||
assert.doesNotMatch(production, /test-network|gateway-overseas|gateway-active|routing-network/)
|
||||
assert.doesNotMatch(jenkins, /wecom|sendProductionWeComNotification/)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
||||
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
||||
@@ -108,7 +110,7 @@ test('source contract: locks body scrolling while open and restores it on close
|
||||
})
|
||||
|
||||
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
|
||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*try \{/)
|
||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*const logoutToken = auth.token\s*try \{/)
|
||||
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
||||
})
|
||||
|
||||
@@ -148,3 +150,49 @@ test('source contract: routes denied pages to an explicit 403 state', () => {
|
||||
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
||||
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
||||
})
|
||||
|
||||
function logoutHarness(t) {
|
||||
const script = layoutSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('layout.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const nodes = ast.statements.filter(node => (ts.isFunctionDeclaration(node) && node.name?.text === 'handleLogout') || (ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes('() => auth.isAuthenticated')))
|
||||
const code = ts.transpileModule(nodes.map(node => node.getText(ast)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
let rejectLogout, confirm
|
||||
const remote = new Promise((_, no) => { rejectLogout = no })
|
||||
const confirmation = new Promise(yes => { confirm = yes })
|
||||
const calls = [], warnings = []
|
||||
const auth = vue.reactive({ token: 'A', isAuthenticated: true, logout: () => { calls.push('logout'); auth.token = ''; auth.isAuthenticated = false; return remote } })
|
||||
const scope = vue.effectScope(); t.after(() => scope.stop())
|
||||
const handler = scope.run(() => new Function('watch', 'auth', 'workspace', 'unsaved', 'router', 'ElMessageBox', 'ElMessage', code + ';return handleLogout')(vue.watch, auth, { clear: () => calls.push('workspace') }, { hasDirty: false, clear: () => calls.push('unsaved') }, { replace: path => { calls.push(path); return Promise.resolve() } }, { confirm: () => confirmation }, { warning: value => warnings.push(value) }))
|
||||
return { auth, handler, confirm, rejectLogout, calls, warnings }
|
||||
}
|
||||
|
||||
test('logout navigates before remote completion and late failure cannot affect a new login', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||
assert.deepEqual(h.calls, ['logout', 'workspace', 'unsaved', '/login'])
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
h.auth.token = 'B'; h.auth.isAuthenticated = true; await vue.nextTick()
|
||||
h.rejectLogout(new Error('SESSION_CHANGED')); await Promise.resolve(); await vue.nextTick()
|
||||
assert.equal(h.auth.token, 'B'); assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.calls.filter(item => item === '/login').length, 1)
|
||||
assert.equal(h.warnings.length, 0)
|
||||
})
|
||||
|
||||
test('cross-tab logout leaves protected route and stale confirmation never logs out a new identity', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler()
|
||||
h.auth.token = 'B'; h.confirm(); await clicked
|
||||
assert.equal(h.calls.length, 0)
|
||||
h.auth.token = ''; h.auth.isAuthenticated = false; await vue.nextTick()
|
||||
assert.deepEqual(h.calls, ['workspace', 'unsaved', '/login'])
|
||||
assert.match(layoutSource, /<div v-if="auth.isAuthenticated" class="client-shell"/)
|
||||
})
|
||||
|
||||
test('remote logout failure reports incomplete server revocation without leaving protected content visible', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||
h.rejectLogout(new Error('offline')); await Promise.resolve()
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.ok(h.calls.includes('/login'))
|
||||
assert.deepEqual(h.warnings, ['已退出本页,服务器会话注销未完成'])
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
||||
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
||||
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
||||
@@ -108,6 +108,7 @@ watch(
|
||||
watch(
|
||||
() => auth.permissionCodes.join('|'),
|
||||
() => {
|
||||
if (!auth.isAuthenticated) return
|
||||
const result = workspace.reconcile(isAllowedTab)
|
||||
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
||||
},
|
||||
@@ -119,6 +120,7 @@ watch(
|
||||
if (authenticated) return
|
||||
workspace.clear()
|
||||
unsaved.clear()
|
||||
void router.replace('/login')
|
||||
},
|
||||
)
|
||||
|
||||
@@ -163,6 +165,7 @@ function handleBeforeUnload(event: BeforeUnloadEvent) {
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
const logoutToken = auth.token
|
||||
try {
|
||||
await ElMessageBox.confirm(unsaved.hasDirty
|
||||
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
||||
@@ -176,15 +179,16 @@ async function handleLogout() {
|
||||
throw error
|
||||
}
|
||||
|
||||
workspace.clear()
|
||||
unsaved.clear()
|
||||
await auth.logout()
|
||||
await router.replace('/login')
|
||||
if (auth.token !== logoutToken) return
|
||||
void auth.logout().catch(() => {
|
||||
if (!auth.isAuthenticated) ElMessage.warning('已退出本页,服务器会话注销未完成')
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||
<div v-if="auth.isAuthenticated" class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
|
||||
<button
|
||||
ref="menuButtonRef"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiRequest } from '@/api/http'
|
||||
import { apiRequest, revokeCapturedSession } from '@/api/http'
|
||||
import type { TokenPair } from '@/api/session'
|
||||
|
||||
export interface RegisterMerchantRequest {
|
||||
@@ -35,8 +35,8 @@ export function registerMerchant(payload: RegisterMerchantRequest) {
|
||||
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
||||
}
|
||||
|
||||
export function logoutMerchant(refreshToken: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: '/auth/logout', data: { refreshToken } })
|
||||
export function logoutMerchant(accessToken: string, refreshToken: string) {
|
||||
return revokeCapturedSession(accessToken, refreshToken)
|
||||
}
|
||||
|
||||
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
||||
|
||||
+105
-99
@@ -61,18 +61,34 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
const permissionCodes = ref<string[]>([])
|
||||
const sessionRestored = ref(false)
|
||||
|
||||
let logoutRequest: { accessToken: string; refreshToken: string; promise: Promise<void> } | undefined
|
||||
let generation = 0
|
||||
let contextRequest: { generation: number; promise: Promise<void> } | undefined
|
||||
let restoreTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function identity(value: MerchantJwtPayload | null) {
|
||||
return value ? JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type]) : ''
|
||||
}
|
||||
|
||||
function applyToken(accessToken: string) {
|
||||
const decoded = decodeMerchantToken(accessToken)
|
||||
const changedIdentity = identity(decoded) !== identity(payload.value)
|
||||
if (accessToken === token.value && payload.value && !changedIdentity) return
|
||||
generation++
|
||||
if (changedIdentity) {
|
||||
user.value = null
|
||||
profile.value = { ...emptyProfile }
|
||||
permissionCodes.value = mapPermissions()
|
||||
}
|
||||
payload.value = decoded
|
||||
token.value = accessToken
|
||||
user.value = currentUser(decoded, user.value?.tenantName)
|
||||
profile.value.username = decoded.username
|
||||
profile.value.realName = decoded.username
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
clearSessionTokens()
|
||||
function resetLocalSession() {
|
||||
generation++
|
||||
token.value = ''
|
||||
payload.value = null
|
||||
user.value = null
|
||||
@@ -81,137 +97,123 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
sessionRestored.value = true
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
clearSessionTokens()
|
||||
resetLocalSession()
|
||||
}
|
||||
|
||||
function applyStoredSession() {
|
||||
const storedToken = getAccessToken()
|
||||
if (!storedToken) {
|
||||
token.value = ''
|
||||
payload.value = null
|
||||
user.value = null
|
||||
permissionCodes.value = []
|
||||
profile.value = { ...emptyProfile }
|
||||
sessionRestored.value = true
|
||||
resetLocalSession()
|
||||
return
|
||||
}
|
||||
try {
|
||||
applyToken(storedToken)
|
||||
sessionRestored.value = false
|
||||
} catch {
|
||||
clearSession()
|
||||
}
|
||||
}
|
||||
|
||||
if (token.value) {
|
||||
try {
|
||||
applyToken(token.value)
|
||||
} catch (error) {
|
||||
if (!(error instanceof MerchantTokenExpiredError && getRefreshToken())) clearSession()
|
||||
resetLocalSession()
|
||||
if (error instanceof MerchantTokenExpiredError && getRefreshToken()) sessionRestored.value = false
|
||||
}
|
||||
}
|
||||
|
||||
applyStoredSession()
|
||||
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
||||
|
||||
async function loadSessionContext() {
|
||||
if (!payload.value) return
|
||||
const currentPermissionCodes = await getCurrentMerchantPermissionCodes()
|
||||
const currentAccessToken = getAccessToken()
|
||||
if (currentAccessToken && currentAccessToken !== token.value) applyToken(currentAccessToken)
|
||||
permissionCodes.value = mapPermissions(currentPermissionCodes)
|
||||
const [tenant, personalProfile] = await Promise.all([
|
||||
getTenantProfile(),
|
||||
getMerchantPersonalProfile(),
|
||||
])
|
||||
user.value = currentUser(payload.value, tenant.tenantName)
|
||||
profile.value = {
|
||||
...profile.value,
|
||||
realName: personalProfile.displayName || payload.value.username,
|
||||
phone: personalProfile.phone || '',
|
||||
email: personalProfile.email || '',
|
||||
tenantName: tenant.tenantName,
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreSession() {
|
||||
if (sessionRestored.value) return
|
||||
if (!isAuthenticated.value) {
|
||||
if (!getRefreshToken()) {
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
if (contextRequest?.generation === generation) return contextRequest.promise
|
||||
let requestGeneration = generation
|
||||
let requestAccessToken = getAccessToken()
|
||||
const isCurrent = () => requestGeneration === generation && getAccessToken() === requestAccessToken
|
||||
const promise = (async () => {
|
||||
try {
|
||||
applyToken(await refreshAuthenticatedSession())
|
||||
if (!isAuthenticated.value) {
|
||||
if (!getRefreshToken()) return
|
||||
const refreshedToken = await refreshAuthenticatedSession()
|
||||
if (requestGeneration !== generation) return restoreSession()
|
||||
applyToken(refreshedToken)
|
||||
requestAccessToken = refreshedToken
|
||||
requestGeneration = generation
|
||||
if (contextRequest) contextRequest.generation = generation
|
||||
}
|
||||
const requestPayload = payload.value
|
||||
if (!requestPayload) return
|
||||
const [codes, tenant, personalProfile] = await Promise.all([
|
||||
getCurrentMerchantPermissionCodes(), getTenantProfile(), getMerchantPersonalProfile(),
|
||||
])
|
||||
if (!isCurrent()) {
|
||||
applyStoredSession()
|
||||
return restoreSession()
|
||||
}
|
||||
permissionCodes.value = mapPermissions(codes)
|
||||
user.value = currentUser(requestPayload, tenant.tenantName)
|
||||
profile.value = {
|
||||
username: requestPayload.username,
|
||||
realName: personalProfile.displayName || requestPayload.username,
|
||||
phone: personalProfile.phone || '', email: personalProfile.email || '', tenantName: tenant.tenantName,
|
||||
}
|
||||
sessionRestored.value = true
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
sessionRestored.value = false
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
})()
|
||||
contextRequest = { generation: requestGeneration, promise }
|
||||
try { await promise } finally {
|
||||
if (contextRequest?.promise === promise) contextRequest = undefined
|
||||
}
|
||||
try {
|
||||
await loadSessionContext()
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
sessionRestored.value = true
|
||||
}
|
||||
|
||||
function synchronizeSession() {
|
||||
// Identity changes and logout revoke local rights immediately. Coalesce pair writes
|
||||
// before loading the new context; same-identity rotation retains confirmed rights.
|
||||
applyStoredSession()
|
||||
if (restoreTimer) clearTimeout(restoreTimer)
|
||||
restoreTimer = setTimeout(() => {
|
||||
restoreTimer = undefined
|
||||
void restoreSession().catch(() => {})
|
||||
}, 0)
|
||||
}
|
||||
|
||||
async function login(loginId: string, password: string, remember = false) {
|
||||
const attempt = ++generation
|
||||
const tokens = await loginMerchant(loginId, password)
|
||||
const decoded = decodeMerchantToken(tokens.accessToken)
|
||||
if (attempt !== generation) return
|
||||
decodeMerchantToken(tokens.accessToken)
|
||||
persistTokenPair(tokens)
|
||||
persistRememberedLoginId(loginId, remember)
|
||||
token.value = tokens.accessToken
|
||||
payload.value = decoded
|
||||
user.value = currentUser(decoded)
|
||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
try {
|
||||
await loadSessionContext()
|
||||
sessionRestored.value = true
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
}
|
||||
applyToken(tokens.accessToken)
|
||||
await restoreSession()
|
||||
}
|
||||
|
||||
async function acceptImpersonationCode(code: string) {
|
||||
const attempt = ++generation
|
||||
const exchanged = await exchangeImpersonationCode(code)
|
||||
const decoded = decodeMerchantToken(exchanged.accessToken)
|
||||
if (attempt !== generation) return
|
||||
decodeMerchantToken(exchanged.accessToken)
|
||||
persistTemporaryAccessToken(exchanged.accessToken)
|
||||
token.value = exchanged.accessToken
|
||||
payload.value = decoded
|
||||
user.value = currentUser(decoded)
|
||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
try {
|
||||
await loadSessionContext()
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
sessionRestored.value = true
|
||||
applyToken(exchanged.accessToken)
|
||||
await restoreSession()
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
function logout() {
|
||||
const accessToken = getAccessToken()
|
||||
const refreshToken = getRefreshToken()
|
||||
try {
|
||||
if (refreshToken) await logoutMerchant(refreshToken)
|
||||
} finally {
|
||||
clearSession()
|
||||
}
|
||||
if (logoutRequest && ((!accessToken && !refreshToken)
|
||||
|| (logoutRequest.accessToken === accessToken && logoutRequest.refreshToken === refreshToken))) return logoutRequest.promise
|
||||
const pending = accessToken || refreshToken
|
||||
? logoutMerchant(accessToken, refreshToken)
|
||||
: Promise.resolve()
|
||||
clearSession()
|
||||
const request = { accessToken, refreshToken, promise: pending.finally(() => {
|
||||
if (logoutRequest === request) logoutRequest = undefined
|
||||
}) }
|
||||
logoutRequest = request
|
||||
return request.promise
|
||||
}
|
||||
|
||||
function hasPermission(permission?: string) {
|
||||
@@ -224,10 +226,13 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
}
|
||||
|
||||
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
|
||||
const requestGeneration = generation
|
||||
const requestToken = getAccessToken()
|
||||
const updated = await updateMerchantPersonalProfile({
|
||||
displayName: next.realName.trim(),
|
||||
email: next.email.trim(),
|
||||
})
|
||||
if (requestGeneration !== generation || requestToken !== getAccessToken()) return
|
||||
updateProfile({
|
||||
realName: updated.displayName,
|
||||
phone: updated.phone || '',
|
||||
@@ -236,8 +241,9 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
}
|
||||
|
||||
window.addEventListener('cc-client-session-expired', clearSession)
|
||||
window.addEventListener('cc-client-session-updated', synchronizeSession)
|
||||
window.addEventListener('storage', (event) => {
|
||||
if (event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token') applyStoredSession()
|
||||
if (event.storageArea === localStorage && (event.key === null || event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token')) synchronizeSession()
|
||||
})
|
||||
|
||||
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
function compile(path, dependencies = {}) {
|
||||
const code = ts.transpileModule(readFileSync(new URL(path, import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function storage() {
|
||||
const values = new Map()
|
||||
return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key) }
|
||||
}
|
||||
function token(user = 1, tenant = 1, membership = 1, nonce = 'a') {
|
||||
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, username: `user-${user}`, app_code: 'MERCHANT', exp: 4102444800, nonce })).toString('base64url')}.test`
|
||||
}
|
||||
const flush = () => new Promise(resolve => setTimeout(resolve, 10))
|
||||
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
|
||||
function harness(t, expired = false) {
|
||||
globalThis.localStorage = storage(); globalThis.sessionStorage = storage()
|
||||
const listeners = new Map()
|
||||
globalThis.window = { addEventListener: (name, fn) => listeners.set(name, fn) }
|
||||
const session = compile('../../../api/session.ts')
|
||||
const initial = expired ? `test.${Buffer.from(JSON.stringify({ user_id: 1, tenant_id: 1, membership_id: 1, username: 'user-1', app_code: 'MERCHANT', exp: 1 })).toString('base64url')}.test` : token()
|
||||
session.persistTokenPair({ accessToken: initial, refreshToken: 'refresh-a' })
|
||||
let reads = 0
|
||||
const behavior = { permissions: async () => ['edit'], tenant: async () => ({ tenantName: 'company' }) }
|
||||
class ApiError extends Error { constructor(status) { super('failed'); this.status = status } }
|
||||
const module = compile('./auth.ts', {
|
||||
vue, pinia, '@/api/session': session,
|
||||
'@/modules/auth/api/auth': { logoutMerchant: async (access, refresh) => behavior.logout?.(refresh, access) },
|
||||
'@/modules/auth/utils/jwt': compile('../utils/jwt.ts'),
|
||||
'@/api/http': { ApiError, refreshAuthenticatedSession: async () => {
|
||||
session.persistTokenPair({ accessToken: token(1, 1, 1, 'refreshed'), refreshToken: 'refresh-new' })
|
||||
listeners.get('cc-client-session-updated')()
|
||||
return session.getAccessToken()
|
||||
} },
|
||||
'@/modules/tenant-management/public': {
|
||||
FRONTEND_TO_MERCHANT_PERMISSION_CODES: { 'order:first-leg:edit': 'edit' },
|
||||
hasMappedMerchantPermission: (_, codes) => codes.has('edit'),
|
||||
getCurrentMerchantPermissionCodes: () => { reads++; return behavior.permissions() },
|
||||
getTenantProfile: () => behavior.tenant(), getMerchantPersonalProfile: async () => ({}),
|
||||
},
|
||||
})
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(async () => { await flush(); pinia.disposePinia(context) })
|
||||
const auth = module.useAuthStore()
|
||||
const event = key => listeners.get('storage')({ key, storageArea: localStorage })
|
||||
function rotate(nextToken = token(1, 1, 1, 'b')) {
|
||||
session.persistTokenPair({ accessToken: nextToken, refreshToken: 'refresh-b' })
|
||||
event(session.ACCESS_TOKEN_KEY); event(session.REFRESH_TOKEN_KEY)
|
||||
}
|
||||
return { auth, session, event, rotate, behavior, listeners, ApiError, reads: () => reads }
|
||||
}
|
||||
|
||||
test('pair storage rotation retains same-identity rights and automatically reloads once without navigation', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
assert.equal(h.auth.sessionRestored, false)
|
||||
await flush()
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false, 'new server rights replace the retained snapshot')
|
||||
assert.equal(h.reads(), 2)
|
||||
h.listeners.get('cc-client-session-updated')()
|
||||
await flush()
|
||||
assert.equal(h.reads(), 2, 'already applied token does not reload twice')
|
||||
})
|
||||
|
||||
test('startup expired-token refresh waits for restored rights even when local rotation emits an event', async t => {
|
||||
const h = harness(t, true)
|
||||
await h.auth.restoreSession()
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.reads(), 1)
|
||||
})
|
||||
|
||||
test('logout storage event immediately clears rights and late context cannot restore them', async t => {
|
||||
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
const pending = h.auth.restoreSession()
|
||||
h.session.clearSessionTokens(); h.event(h.session.ACCESS_TOKEN_KEY)
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.deepEqual(h.auth.permissionCodes, [])
|
||||
old.resolve(['edit']); await pending; await flush()
|
||||
assert.equal(h.auth.user, null)
|
||||
assert.deepEqual(h.auth.permissionCodes, [])
|
||||
})
|
||||
|
||||
test('account, customer and membership switches revoke rights immediately and reject stale request results', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
h.rotate(); await flush()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate(token(2, 2, 2, 'new'))
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
await flush(); old.resolve(['edit']); await flush()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
h.behavior.permissions = async () => ['edit']; h.rotate(token(2, 3, 3, 'next')); await flush()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
h.rotate(token(2, 3, 4, 'membership'))
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
})
|
||||
|
||||
test('context failure is not marked restored and explicit retry coalesces concurrent callers', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.permissions = async () => { throw new Error('offline') }
|
||||
await h.auth.restoreSession()
|
||||
assert.equal(h.auth.sessionRestored, false)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
const pending = deferred(); h.behavior.permissions = () => pending.promise
|
||||
const first = h.auth.restoreSession(), second = h.auth.restoreSession()
|
||||
assert.equal(h.reads(), 2)
|
||||
pending.resolve(['edit']); await Promise.all([first, second])
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
})
|
||||
|
||||
test('stale unauthorized context response cannot clear a newer account', async t => {
|
||||
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
const pending = h.auth.restoreSession()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate(token(2, 2, 2)); await flush()
|
||||
old.reject(new h.ApiError(401)); await pending
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
})
|
||||
|
||||
test('store logout clears immediately and late revocation failure preserves a later cross-tab login', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
const remote = deferred(); let sentRefresh
|
||||
h.behavior.logout = refresh => { sentRefresh = refresh; return remote.promise }
|
||||
const pending = h.auth.logout()
|
||||
const rejected = assert.rejects(pending, /offline/)
|
||||
assert.equal(sentRefresh, 'refresh-a')
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.equal(h.session.getAccessToken(), '')
|
||||
h.rotate(token(2, 2, 2)); await flush()
|
||||
remote.reject(new Error('offline')); await rejected
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.session.getRefreshToken(), 'refresh-b')
|
||||
})
|
||||
|
||||
test('duplicate logout joins captured pair revocation and does not send again',async t=>{
|
||||
const h=harness(t);const remote=deferred();let count=0,sent
|
||||
h.behavior.logout=(refresh,access)=>{count++;sent={refresh,access};return remote.promise}
|
||||
const a=h.auth.logout(),b=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(sent.access,token());assert.equal(sent.refresh,'refresh-a');assert.equal(count,1);remote.resolve();await Promise.all([a,b])
|
||||
})
|
||||
|
||||
test('B logout during A pending revokes B; A finally cannot release B deduplication',async t=>{
|
||||
const h=harness(t);const a=deferred(),b=deferred(),calls=[]
|
||||
h.behavior.logout=(refresh,access)=>{calls.push({refresh,access});return calls.length===1?a.promise:b.promise}
|
||||
const leavingA=h.auth.logout();h.rotate(token(2,2,2));await flush();assert.equal(h.auth.isAuthenticated,true)
|
||||
const leavingB=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(h.session.getAccessToken(),'');assert.equal(calls.length,2);assert.equal(calls[1].access,token(2,2,2))
|
||||
a.resolve();await leavingA;const duplicateB=h.auth.logout();assert.equal(calls.length,2);let duplicateFinished=false;void duplicateB.then(()=>{duplicateFinished=true});await flush();assert.equal(duplicateFinished,false);b.resolve();await Promise.all([leavingB,duplicateB])
|
||||
})
|
||||
@@ -102,7 +102,8 @@ test('opens complete service and privacy documents from registration', () => {
|
||||
test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||
assert.match(authApiSource, /\/auth\/login/)
|
||||
assert.match(authApiSource, /\/auth\/register/)
|
||||
assert.match(authApiSource, /\/auth\/logout/)
|
||||
assert.match(authApiSource, /revokeCapturedSession\(accessToken, refreshToken\)/)
|
||||
assert.match(httpSource, /\/auth\/logout/)
|
||||
assert.match(httpSource, /refreshPromise/)
|
||||
assert.match(httpSource, /\/auth\/refresh/)
|
||||
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
||||
@@ -117,7 +118,8 @@ test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
||||
assert.match(authStoreSource, /decodeMerchantToken/)
|
||||
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
|
||||
assert.match(authStoreSource, /applyToken\(await refreshAuthenticatedSession\(\)\)/)
|
||||
assert.match(authStoreSource, /const refreshedToken = await refreshAuthenticatedSession\(\)/)
|
||||
assert.match(authStoreSource, /applyToken\(refreshedToken\)/)
|
||||
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
||||
})
|
||||
|
||||
@@ -152,7 +154,7 @@ test('shows a forced re-login notice after login identifiers change', () => {
|
||||
test('keeps a valid local session during temporary context and refresh outages', () => {
|
||||
assert.match(authStoreSource, /function isExpiredSessionError/)
|
||||
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
||||
assert.match(authStoreSource, /sessionRestored\.value = true\s+return/)
|
||||
assert.match(authStoreSource, /if \(!isCurrent\(\)\) return\s+sessionRestored\.value = false/)
|
||||
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
||||
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
||||
})
|
||||
|
||||
@@ -75,10 +75,11 @@ export interface ProcurementCreate {
|
||||
}
|
||||
|
||||
export interface TransportSummary {
|
||||
fleetArrangement: import('../fleetArrangement').FleetArrangement | null
|
||||
orderNo: string
|
||||
transportType: string
|
||||
transportMode?: string
|
||||
palletRequired?: string
|
||||
palletRequired?: string | null
|
||||
origin: string
|
||||
destination: string
|
||||
containerType: string | null
|
||||
|
||||
@@ -1,11 +1,38 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
|
||||
const api = readFileSync(new URL('./api/businessOrders.ts', import.meta.url), 'utf8')
|
||||
const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8')
|
||||
const view = readFileSync(new URL('./components/BusinessOrdersView.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('renders unknown pallet service and container type as dashes while preserving explicit values', () => {
|
||||
const helpers = view.slice(view.indexOf('function read('), view.indexOf('function idempotencyKey('))
|
||||
const compiled = ts.transpileModule(helpers, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const { displayCell, yesNo, text } = runInNewContext(`${compiled}\n({ displayCell, yesNo, text })`)
|
||||
assert.equal(displayCell({ palletRequired: null }, 'palletRequired'), '—')
|
||||
assert.equal(displayCell({ palletRequired: 'NO' }, 'palletRequired'), '否')
|
||||
assert.equal(displayCell({ palletRequired: 'YES' }, 'palletRequired'), '是')
|
||||
assert.equal(displayCell({ containerType: null }, 'containerType'), '—')
|
||||
assert.equal(displayCell({ containerType: '40HQ' }, 'containerType'), '40HQ')
|
||||
assert.equal(yesNo(null), '—')
|
||||
assert.equal(text(null), '—')
|
||||
assert.match(api, /palletRequired\?: string \| null/)
|
||||
const create = api.slice(api.indexOf('export interface TransportCreate'), api.indexOf('export interface TransportUpdate'))
|
||||
assert.doesNotMatch(create, /palletRequired\?: string \| null/)
|
||||
})
|
||||
|
||||
test('shows merchant-owned arrangement facts without a pool request or editable status control', () => {
|
||||
assert.match(api, /fleetArrangement: import\('\.\.\/fleetArrangement'\)\.FleetArrangement \| null/)
|
||||
assert.match(view, /aria-label="承运安排"/)
|
||||
for (const field of ['signedPackages', 'unsignedPackages', 'returnedPackages', 'readOnlyReason']) assert.ok(view.includes(`fleetArrangement.${field}`))
|
||||
assert.doesNotMatch(api, /capacity-offers|fleet\/trips/)
|
||||
assert.match(view, /if \(query\.page !== 1\) query\.page = 1\s+else void load\(\)/)
|
||||
assert.match(view, /if \(reloadDirectly\) void load\(\)/)
|
||||
})
|
||||
|
||||
test('activates all three customer cross-border pages with frozen permissions', () => {
|
||||
for (const [path, permission] of [
|
||||
['cross-border/procurement', 'merchant:cross-border:procurement:list'],
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type TransportSummary,
|
||||
} from '../api/businessOrders'
|
||||
import { CONTAINER_SPECIFICATIONS, DEFAULT_CONTAINER_TYPE } from '../containerSpecifications'
|
||||
import { poolOrderStatusLabels } from '../fleetArrangement'
|
||||
|
||||
const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
|
||||
const auth = useAuthStore()
|
||||
@@ -105,6 +106,7 @@ function transportColumns(looseboard: boolean): ColumnDefinition[] {
|
||||
{ key: 'budgetAmount', label: '预算总价', width: 110 },
|
||||
{ key: 'requestedDate', label: '要求时间', width: 120 },
|
||||
{ key: 'status', label: '状态', width: 130 },
|
||||
{ key: 'fleetArrangement', label: '承运安排', width: 190 },
|
||||
]
|
||||
}
|
||||
|
||||
@@ -115,6 +117,7 @@ const submitKey = ref('')
|
||||
const error = ref('')
|
||||
const rows = ref<BusinessRow[]>([])
|
||||
const detail = ref<BusinessDetail | null>(null)
|
||||
const fleetArrangement = computed(() => detail.value && props.kind !== 'procurement' ? (detail.value as TransportDetail).summary.fleetArrangement : null)
|
||||
const formRef = ref<FormInstance>()
|
||||
const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' })
|
||||
const total = ref(0)
|
||||
@@ -157,6 +160,7 @@ const queryFields = computed<QueryField[]>(() => [
|
||||
{ label: '部分出库', value: 'PARTIALLY_OUTBOUND' },
|
||||
{ label: '全部出库', value: 'OUTBOUNDED' },
|
||||
{ label: '待接单', value: 'PENDING_ACCEPTANCE' },
|
||||
...(props.kind === 'procurement' ? [] : Object.entries(poolOrderStatusLabels).filter(([value]) => !['IN_TRANSIT', 'COMPLETED', 'CANCELLED'].includes(value)).map(([value, label]) => ({ value, label }))),
|
||||
{ label: '处理中', value: 'PROCESSING' },
|
||||
{ label: '运输中', value: 'IN_TRANSIT' },
|
||||
{ label: '已完成', value: 'COMPLETED' },
|
||||
@@ -198,7 +202,7 @@ const detailFields = computed(() => {
|
||||
}
|
||||
const current = detail.value as TransportDetail
|
||||
return [
|
||||
['运输方式', read(summary, 'transportMode')],
|
||||
['运输方式', transportModeLabel(read(summary, 'transportMode'))],
|
||||
['是否打盘', yesNo(read(summary, 'palletRequired'))], ['运输类型', transportTypeLabel(read(summary, 'transportType'))],
|
||||
['起运地', read(summary, 'origin')], ['起运地址', current.originAddress],
|
||||
['目的地', read(summary, 'destination')], ['目的地址', current.destinationAddress],
|
||||
@@ -215,7 +219,7 @@ const tableColumns = computed<DataTableColumn[]>(() => [
|
||||
...configuration.value.columns.map((column) => ({
|
||||
...column,
|
||||
prop: column.key,
|
||||
slotName: ['orderNo', 'status'].includes(column.key) ? column.key : undefined,
|
||||
slotName: ['orderNo', 'status', 'fleetArrangement'].includes(column.key) ? column.key : undefined,
|
||||
formatter: (row: object) => displayCell(row, column.key),
|
||||
})),
|
||||
])
|
||||
@@ -242,6 +246,7 @@ function yesNo(value: unknown) { return value === 'YES' ? '是' : value === 'NO'
|
||||
function transportTypeLabel(value: unknown) { return ({ PORT_PICKUP: '港口提柜', WAREHOUSE_TO_WAREHOUSE: '仓到仓', WAREHOUSE_TO_DOOR: '仓到门' } as Record<string, string>)[String(value)] || text(value) }
|
||||
function transportModeLabel(value: unknown) { return ({ SHARED_TRUCK: '拼车', PRIORITY_CONSOLIDATION: '优先拼载' } as Record<string, string>)[String(value)] || text(value) }
|
||||
function statusLabel(value: unknown) {
|
||||
if (poolOrderStatusLabels[String(value)]) return poolOrderStatusLabels[String(value)]
|
||||
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_OUTBOUND: '待出库', PARTIALLY_OUTBOUND: '部分出库', OUTBOUNDED: '全部出库', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
|
||||
}
|
||||
function statusTone(value: unknown) {
|
||||
@@ -283,13 +288,14 @@ async function load() {
|
||||
}
|
||||
|
||||
function resetQuery() {
|
||||
const reloadDirectly = query.page === 1
|
||||
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' })
|
||||
void load()
|
||||
if (reloadDirectly) void load()
|
||||
}
|
||||
|
||||
function searchOrders() {
|
||||
query.page = 1
|
||||
void load()
|
||||
if (query.page !== 1) query.page = 1
|
||||
else void load()
|
||||
}
|
||||
|
||||
function getRowActions(candidate: object): TableAction[] {
|
||||
@@ -397,6 +403,7 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
<template v-if="error" #error><div class="business-load-error" role="alert"><span>{{ error }}</span><el-button size="small" @click="load">重新加载</el-button></div></template>
|
||||
<template #orderNo="{ row }"><button class="business-order-link" type="button" @click="openDetail(row)">{{ (row as BusinessRow).orderNo }}</button></template>
|
||||
<template #status="{ row }"><el-tag :type="statusTone((row as BusinessRow).status)" effect="light" size="small">{{ statusLabel((row as BusinessRow).status) }}</el-tag></template>
|
||||
<template #fleetArrangement="{ row }"><template v-if="(row as TransportSummary).fleetArrangement"><div>{{ poolOrderStatusLabels[(row as TransportSummary).fleetArrangement!.fulfillmentStage] || '待核对履约进度' }}</div><small>{{ dateTime((row as TransportSummary).fleetArrangement!.plannedDepartureAt) }}</small></template><span v-else>—</span></template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
@@ -413,6 +420,24 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
<div v-for="field in detailFields" :key="String(field[0])" :class="detailFieldClass(field[0])"><dt>{{ field[0] }}</dt><dd>{{ text(field[1]) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
<section v-if="!error && fleetArrangement" class="business-detail-section" aria-label="承运安排">
|
||||
<h3>承运安排</h3><p>{{ fleetArrangement.readOnlyReason }}</p>
|
||||
<dl class="detail-grid arrangement-grid">
|
||||
<div><dt>预订号</dt><dd>{{ fleetArrangement.bookingNo }}</dd></div>
|
||||
<div><dt>计划发车</dt><dd>{{ dateTime(fleetArrangement.plannedDepartureAt) }}</dd></div>
|
||||
<div><dt>起运仓</dt><dd>{{ text(fleetArrangement.originWarehouseName) }}</dd></div>
|
||||
<div><dt>目的地</dt><dd>{{ text(fleetArrangement.destinationLabel) }}</dd></div>
|
||||
<div><dt>交货方式</dt><dd>{{ fleetArrangement.deliveryMode === 'SELF_DELIVERY' ? '自行送至起运仓' : '线下安排提货至起运仓' }}</dd></div>
|
||||
<div><dt>履约进度</dt><dd>{{ poolOrderStatusLabels[fleetArrangement.fulfillmentStage] || '待核对履约进度' }}</dd></div>
|
||||
<div><dt>更新时间</dt><dd>{{ dateTime(fleetArrangement.stageOccurredAt) }}</dd></div>
|
||||
<div><dt>约定运费(非实收)</dt><dd>{{ money(fleetArrangement.agreedFreightAmount, fleetArrangement.currency) }}</dd></div>
|
||||
<div><dt>来货单号</dt><dd>{{ text(fleetArrangement.incomingNo) }}</dd></div>
|
||||
<div><dt>派送单号</dt><dd>{{ text(fleetArrangement.deliveryNo) }}</dd></div>
|
||||
<div><dt>已签 / 未签 / 退回箱数</dt><dd>{{ fleetArrangement.signedPackages ?? '—' }} / {{ fleetArrangement.unsignedPackages ?? '—' }} / {{ fleetArrangement.returnedPackages ?? '—' }}</dd></div>
|
||||
<div class="is-wide"><dt>交货说明</dt><dd>{{ text(fleetArrangement.deliveryInstructions) }}</dd></div>
|
||||
<div v-if="fleetArrangement.exceptionSummary" class="is-wide"><dt>履约说明</dt><dd>{{ fleetArrangement.exceptionSummary }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<el-card v-else shadow="never" class="form-card">
|
||||
@@ -472,6 +497,8 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
.detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 76px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
.detail-grid div.is-wide { grid-column: span 2; }
|
||||
.detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
|
||||
.arrangement-grid div { grid-template-columns: 124px minmax(0, 1fr); }
|
||||
.arrangement-grid dt { white-space: normal; overflow-wrap: anywhere; }
|
||||
.detail-grid dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--navy); font-size: 12px; font-weight: 600; line-height: 1.4; }
|
||||
.form-card :deep(.el-form) { max-width: 860px; }
|
||||
.form-card :deep(.el-input), .form-card :deep(.el-textarea), .form-card :deep(.el-select) { width: 100%; }
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
export interface FleetArrangement {
|
||||
sourceType: 'FLEET_CAPACITY_OFFER'
|
||||
businessType: 'LOCAL_LOOSEBOARD' | 'US_TRUCK'
|
||||
businessOrderNo: string
|
||||
bookingNo: string
|
||||
tripNo: string
|
||||
plannedDepartureAt: string | null
|
||||
originWarehouseName: string
|
||||
destinationLabel: string
|
||||
deliveryMode: 'SELF_DELIVERY' | 'MANUAL_PICKUP_TO_WAREHOUSE'
|
||||
deliveryInstructions: string | null
|
||||
fulfillmentStage: string
|
||||
stageOccurredAt: string | null
|
||||
agreedFreightAmount: number | null
|
||||
currency: string | null
|
||||
incomingNo: string | null
|
||||
dispatchNo: string | null
|
||||
deliveryNo: string | null
|
||||
signedPackages: number | null
|
||||
unsignedPackages: number | null
|
||||
returnedPackages: number | null
|
||||
exceptionSummary: string | null
|
||||
readOnlyReason: string
|
||||
}
|
||||
export const poolOrderStatusLabels: Record<string, string> = {
|
||||
WAITING_INBOUND: '待入仓', RECEIVING: '收货中', WAITING_CONSOLIDATION: '待合托',
|
||||
PENDING_DISPATCH: '待派车', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消',
|
||||
}
|
||||
@@ -566,14 +566,19 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
|
||||
})
|
||||
}
|
||||
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload })
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) {
|
||||
export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number }, idempotencyKey: string) {
|
||||
return apiRequest<void>({
|
||||
method: 'POST',
|
||||
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
||||
data: payload,
|
||||
headers: { 'Idempotency-Key': idempotencyKey },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('forwards optional tax mode and pagination through the current GET endpoint', async () => {
|
||||
const calls = []
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||
const api = {}
|
||||
new Function('require', 'exports', code)(id => {
|
||||
assert.equal(id, '@/api/http')
|
||||
return { apiRequest: async config => { calls.push(config); return { records: [] } } }
|
||||
}, api)
|
||||
await api.getMerchantUnifiedOrders({ page: 2, size: 200, taxMode: 'TAX_REFUND' })
|
||||
await api.getMerchantUnifiedOrders({ taxMode: 'BUY_DECLARATION' })
|
||||
await api.getMerchantUnifiedOrders()
|
||||
assert.deepEqual(calls, [
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 2, size: 200, taxMode: 'TAX_REFUND' } },
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200, taxMode: 'BUY_DECLARATION' } },
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200 } },
|
||||
])
|
||||
})
|
||||
|
||||
test('keeps the merchant unified-order boundary and one-click palletization status', () => {
|
||||
assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
|
||||
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApiError, apiRequest } from '@/api/http'
|
||||
import { apiRequest } from '@/api/http'
|
||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||
|
||||
export type ApiUnifiedOrderMainStatus =
|
||||
@@ -60,11 +60,12 @@ export interface MerchantUnifiedTransportSummary {
|
||||
|
||||
export interface MerchantUnifiedOrderRow {
|
||||
orderId: number | string
|
||||
orderVersion: number
|
||||
tenantId: number | string
|
||||
orderNo: string | null
|
||||
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||
lxCode?: string | null
|
||||
mainStatus: ApiUnifiedOrderMainStatus
|
||||
mainStatus: ApiUnifiedOrderMainStatus | 'DRAFT' | 'CANCELLED'
|
||||
nextAction: string | null
|
||||
customerFeeConfirmationRequired: boolean
|
||||
internalOrderStatus: ApiFirstLegStatus | null
|
||||
@@ -132,7 +133,25 @@ export interface MerchantUnifiedCustomNode {
|
||||
attachmentIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface MerchantTransportNode {
|
||||
standardNode: string
|
||||
nodeSequence: number
|
||||
providerCode: string | null
|
||||
estimatedAt: string | null
|
||||
actualAt: string | null
|
||||
locationCode: string | null
|
||||
locationName: string | null
|
||||
}
|
||||
|
||||
export interface MerchantTransportFragment {
|
||||
inboundCode: string | null
|
||||
cabinetNo: string | null
|
||||
containerNo: string | null
|
||||
nodes: MerchantTransportNode[]
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderDetail {
|
||||
transportFragments: MerchantTransportFragment[]
|
||||
summary: MerchantUnifiedOrderRow
|
||||
order: MerchantFirstLegOrderDetail
|
||||
timeline: MerchantUnifiedTimelineEvent[]
|
||||
@@ -141,6 +160,8 @@ export interface MerchantUnifiedOrderDetail {
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderQuery {
|
||||
taxMode?: ApiTaxMode
|
||||
loaded?: boolean
|
||||
keyword?: string
|
||||
fbaCode?: string
|
||||
orderNo?: string
|
||||
@@ -156,6 +177,31 @@ export interface MerchantUnifiedOrderQuery {
|
||||
|
||||
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
||||
|
||||
export interface MerchantOrderWorkbenchQuery {
|
||||
cargoKeyword?: string
|
||||
receivingWarehouseId?: string
|
||||
channelName?: string
|
||||
destinationType?: string
|
||||
trackingNumber?: string
|
||||
mainStatus?: string
|
||||
createdFrom?: string
|
||||
createdTo?: string
|
||||
queue?: 'all' | 'fee' | 'customs' | 'draft'
|
||||
page?: number
|
||||
size?: number
|
||||
}
|
||||
|
||||
export interface MerchantOrderWorkbench {
|
||||
page: PageResult<MerchantUnifiedOrderRow>
|
||||
queues: { all: number; fee: number; customs: number; draft: number }
|
||||
channelNames: string[]
|
||||
}
|
||||
|
||||
export function getMerchantOrderWorkbench(params: MerchantOrderWorkbenchQuery = {}) {
|
||||
return apiRequest<MerchantOrderWorkbench>({ method: 'GET', url: `${unifiedOrderBaseUrl}/workbench`,
|
||||
params: { ...params, page: params.page ?? 1, size: params.size ?? 10 } })
|
||||
}
|
||||
|
||||
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
||||
const { page, size, ...filters } = params
|
||||
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
||||
@@ -171,7 +217,3 @@ export function getMerchantUnifiedOrder(orderId: number | string) {
|
||||
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
||||
})
|
||||
}
|
||||
|
||||
export function isUnifiedOrderQueryUnavailable(error: unknown) {
|
||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
function harness(t) {
|
||||
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const code = ts.transpileModule(source + '\nexport { loadDetail, detail, clearanceResults, loading, errorMessage, selectedInboundIds, clearanceError, clearanceLoading, retryClearanceResults, close }', { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const props = vue.reactive({ modelValue: false, orderId: 'A', canEdit: true }), requests = [], clearances = [], updates = [], view = {}
|
||||
const unmounts = []
|
||||
const dependencies = { vue: { ...vue, onBeforeUnmount: fn => unmounts.push(fn) }, 'element-plus': { ElMessage: {} }, '@/modules/first-leg/api/customs': {
|
||||
getMerchantCustomsForOrder: id => { const pending = deferred(); requests.push({ id, ...pending }); return pending.promise },
|
||||
getMerchantClearanceResults: id => { const pending = deferred(); clearances.push({ id, ...pending }); return pending.promise },
|
||||
merchantCustomsErrorMessage: error => error.message,
|
||||
} }
|
||||
const scope = vue.effectScope()
|
||||
scope.run(() => new Function('require', 'exports', 'defineProps', 'defineEmits', code)(id => {
|
||||
assert.ok(id in dependencies, id); return dependencies[id]
|
||||
}, view, () => props, () => (...args) => updates.push(args)))
|
||||
t.after(() => scope.stop())
|
||||
return { props, requests, clearances, updates, view, unmount: () => unmounts.forEach(fn => fn()) }
|
||||
}
|
||||
const detail = id => ({ loadingPlanId: id, inbounds: [{ orderId: id, inboundId: `IN-${id}`, taxMode: 'TAX_REFUND' }] })
|
||||
const tick = async () => { await Promise.resolve(); await vue.nextTick(); await Promise.resolve() }
|
||||
|
||||
test('result section stays pending while the refreshed detail is still loading', async t => {
|
||||
const h = harness(t)
|
||||
h.props.initialDetail = detail('A')
|
||||
h.props.modelValue = true
|
||||
await tick()
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'A')
|
||||
assert.equal(h.view.loading.value, true)
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
assert.equal(h.clearances.length, 0)
|
||||
const template = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||
assert.match(template, /v-else-if="loading \|\| clearanceLoading"/)
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.clearanceLoading.value, true)
|
||||
h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.view.loading.value, false)
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||
})
|
||||
|
||||
test('switching orders while open starts the new request and ignores stale detail', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.orderId = 'B'; await tick()
|
||||
assert.deepEqual(h.requests.map(r => r.id), ['A', 'B'])
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||
assert.deepEqual(h.view.selectedInboundIds.value, ['IN-B'])
|
||||
assert.deepEqual(h.clearances.map(r => r.id), ['B'])
|
||||
assert.equal(h.updates.length, 1)
|
||||
})
|
||||
|
||||
test('closing before detail response prevents stale data and events', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.modelValue = false; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.detail.value, null); assert.equal(h.view.loading.value, false)
|
||||
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0)
|
||||
})
|
||||
|
||||
test('closing and reopening ignores the previous clearance response', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
h.props.modelValue = false; await tick(); h.props.orderId = 'B'; h.props.modelValue = true; await tick()
|
||||
h.requests[1].resolve(detail('B')); await tick()
|
||||
h.clearances[1].resolve([{ kind: 'B' }]); await tick()
|
||||
h.clearances[0].resolve([{ kind: 'A' }]); await tick()
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ kind: 'B' }])
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'B'); assert.equal(h.updates.length, 1)
|
||||
})
|
||||
|
||||
test('stale detail failure cannot clear the next request loading or show an error', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.orderId = 'B'; await tick(); h.requests[0].reject(new Error('old failure')); await tick()
|
||||
assert.equal(h.view.loading.value, true); assert.equal(h.view.errorMessage.value, '')
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.view.loading.value, false); assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||
})
|
||||
|
||||
test('unmount invalidates pending detail requests', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick(); h.unmount()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0); assert.equal(h.view.detail.value, null)
|
||||
})
|
||||
|
||||
test('result failure retains documents and exposes error; retry queries only results and deduplicates clicks', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve({ ...detail('A'), documents: [{ documentId: 'document-A' }] }); await tick()
|
||||
h.clearances[0].reject(new Error('结果服务暂不可用')); await tick()
|
||||
assert.equal(h.view.errorMessage.value, '')
|
||||
assert.equal(h.view.clearanceError.value, '结果服务暂不可用')
|
||||
assert.equal(h.view.detail.value.documents[0].documentId, 'document-A')
|
||||
assert.equal(h.view.loading.value, false)
|
||||
const retry = h.view.retryClearanceResults()
|
||||
await h.view.retryClearanceResults()
|
||||
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 2)
|
||||
assert.equal(h.view.clearanceLoading.value, true)
|
||||
h.clearances[1].resolve([{ id: 'result-A' }]); await retry
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'result-A' }])
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
})
|
||||
|
||||
test('normal open requests detail and results exactly once and distinguishes successful empty results', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 1)
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
})
|
||||
|
||||
for (const transition of ['switch', 'close', 'unmount']) {
|
||||
for (const outcome of ['resolve', 'reject']) {
|
||||
test(`${transition} ignores stale result retry ${outcome}`, async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].reject(new Error('first failure')); await tick()
|
||||
const retry = h.view.retryClearanceResults()
|
||||
if (transition === 'switch') { h.props.orderId = 'B'; await tick() }
|
||||
else if (transition === 'close') { h.view.close(); h.props.modelValue = false; await tick() }
|
||||
else h.unmount()
|
||||
if (outcome === 'resolve') h.clearances[1].resolve([{ id: 'old-A' }])
|
||||
else h.clearances[1].reject(new Error('old retry failure'))
|
||||
await retry
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||
if (transition === 'switch') {
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[2].resolve([{ id: 'B' }]); await tick()
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'B' }])
|
||||
} else {
|
||||
await h.view.retryClearanceResults()
|
||||
assert.equal(h.clearances.length, 2)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
test('result error and retry reuse existing section error styling before the empty state', () => {
|
||||
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||
assert.match(source, /v-if="clearanceError" class="customs-error" role="alert"/)
|
||||
assert.match(source, /@click="retryClearanceResults"/)
|
||||
assert.match(source, /v-else-if="loading \|\| clearanceLoading"/)
|
||||
assert.match(source, /v-else-if="!clearanceResults.length"/)
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue'
|
||||
import {
|
||||
@@ -46,6 +46,12 @@ const replaceInput = ref<HTMLInputElement>()
|
||||
const mutating = ref(false)
|
||||
const downloadingKey = ref('')
|
||||
const clearanceResults = ref<MerchantClearanceResult[]>([])
|
||||
const clearanceError = ref('')
|
||||
const clearanceLoading = ref(false)
|
||||
let clearanceRequest = 0
|
||||
let disposed = false
|
||||
let detailRequest = 0
|
||||
onBeforeUnmount(() => { disposed = true; detailRequest += 1; resetClearanceResults() })
|
||||
|
||||
const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? [])
|
||||
const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED')
|
||||
@@ -66,32 +72,80 @@ function initializeSelection(value: MerchantCustomsContainer) {
|
||||
selectedInboundIds.value = currentOrderIds
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
if (!props.orderId) return
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
function resetClearanceResults() {
|
||||
clearanceRequest += 1
|
||||
clearanceResults.value = []
|
||||
clearanceError.value = ''
|
||||
clearanceLoading.value = false
|
||||
}
|
||||
|
||||
async function loadClearanceResults() {
|
||||
if (disposed || !props.modelValue || !props.orderId || !detail.value || clearanceLoading.value) return
|
||||
const request = ++clearanceRequest
|
||||
const parentRequest = detailRequest
|
||||
const orderId = props.orderId
|
||||
const isCurrent = () => !disposed && request === clearanceRequest && parentRequest === detailRequest && props.modelValue && props.orderId === orderId
|
||||
clearanceLoading.value = true
|
||||
clearanceError.value = ''
|
||||
try {
|
||||
const result = await getMerchantCustomsForOrder(props.orderId)
|
||||
detail.value = result
|
||||
initializeSelection(result)
|
||||
try { clearanceResults.value = await getMerchantClearanceResults(props.orderId) } catch { clearanceResults.value = [] }
|
||||
emit('updated', result)
|
||||
const results = await getMerchantClearanceResults(orderId)
|
||||
if (isCurrent()) clearanceResults.value = results
|
||||
} catch (error) {
|
||||
detail.value = null
|
||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||
if (isCurrent()) clearanceError.value = merchantCustomsErrorMessage(error, '海关申报结果加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (isCurrent()) clearanceLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (open) => {
|
||||
async function retryClearanceResults() {
|
||||
if (loading.value) return
|
||||
await loadClearanceResults()
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
if (disposed || !props.modelValue || !props.orderId) return
|
||||
const request = ++detailRequest
|
||||
resetClearanceResults()
|
||||
const orderId = props.orderId
|
||||
const isCurrent = () => request === detailRequest && props.modelValue && props.orderId === orderId
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const result = await getMerchantCustomsForOrder(orderId)
|
||||
if (!isCurrent()) return
|
||||
detail.value = result
|
||||
initializeSelection(result)
|
||||
await loadClearanceResults()
|
||||
if (!isCurrent()) return
|
||||
emit('updated', result)
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
detail.value = null
|
||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||
} finally {
|
||||
if (isCurrent()) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.modelValue, props.orderId] as const, ([open]) => {
|
||||
detailRequest += 1
|
||||
detail.value = null
|
||||
resetClearanceResults()
|
||||
selectedInboundIds.value = []
|
||||
editingDocument.value = null
|
||||
replacingDocument.value = null
|
||||
errorMessage.value = ''
|
||||
loading.value = false
|
||||
if (!open) return
|
||||
detail.value = props.initialDetail ?? null
|
||||
const initial = props.initialDetail
|
||||
detail.value = initial?.inbounds.some((item) => item.orderId === props.orderId) ? initial : null
|
||||
if (detail.value) initializeSelection(detail.value)
|
||||
void loadDetail()
|
||||
})
|
||||
}, { immediate: true })
|
||||
|
||||
function close() {
|
||||
detailRequest += 1
|
||||
resetClearanceResults()
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
@@ -326,7 +380,13 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
||||
<div class="customs-section-title">
|
||||
<div><h3>海关申报结果</h3><p>平台完成正式申报后,客户可查看与本订单相关的查验、补充资料和放行结果。</p></div>
|
||||
</div>
|
||||
<el-empty v-if="!clearanceResults.length" description="暂无海关结果" :image-size="48" />
|
||||
<div v-if="clearanceError" class="customs-error" role="alert">
|
||||
<strong>海关申报结果加载失败</strong>
|
||||
<span>{{ clearanceError }}</span>
|
||||
<el-button :loading="clearanceLoading" @click="retryClearanceResults">重新加载</el-button>
|
||||
</div>
|
||||
<el-skeleton v-else-if="loading || clearanceLoading" :rows="2" animated />
|
||||
<el-empty v-else-if="!clearanceResults.length" description="暂无海关结果" :image-size="48" />
|
||||
<div v-else class="clearance-result-list">
|
||||
<div v-for="item in clearanceResults" :key="item.id" class="clearance-result-row">
|
||||
<div><strong>{{ clearanceResultLabel(item) }}</strong><span>{{ formatDateTime(item.occurredAt) }} · 报关单号 {{ item.customsEntryNo || '—' }}</span></div>
|
||||
@@ -383,6 +443,9 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:global(.customs-documents-dialog.el-dialog) { display: flex; max-height: 70vh; flex-direction: column; overflow: hidden; }
|
||||
:global(.customs-documents-dialog .el-dialog__header), :global(.customs-documents-dialog .el-dialog__footer) { flex: 0 0 auto; }
|
||||
:global(.customs-documents-dialog .el-dialog__body) { min-height: 0; flex: 1 1 auto; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.customs-error { display: grid; gap: 10px; justify-items: start; padding: 22px; border: 1px solid #f1b8b8; background: #fff7f7; color: #9f2d2d; }
|
||||
.customs-error span { overflow-wrap: anywhere; font-size: 12px; }
|
||||
.customs-summary { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)) auto; align-items: center; gap: 18px; padding: 16px 18px; border: 1px solid var(--border); background: #f8faf9; }
|
||||
|
||||
@@ -26,14 +26,15 @@ function stageState(index: number) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ol class="progress-stages" aria-label="订单主状态阶段">
|
||||
<p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消,不再继续履约。</p>
|
||||
<ol v-else class="progress-stages" aria-label="订单主状态阶段">
|
||||
<li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined">
|
||||
<span class="stage-marker" aria-hidden="true"><Check v-if="index < currentIndex" :size="13" /><CircleDot v-else :size="13" /></span>
|
||||
<span class="stage-label">{{ stage.label }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">订单提交后开始记录主状态进度。</p>
|
||||
<div class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||
<div v-if="order.status !== 'CANCELLED'" class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
import { customerTransportRows } from '../utils/transportFacts'
|
||||
|
||||
const props = defineProps<{ fragments: MerchantTransportFragment[] }>()
|
||||
const rows = computed(() => customerTransportRows(props.fragments))
|
||||
function time(value: string | null) { return value ? value.replace('T', ' ') : '—' }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="transport-facts" aria-label="实际装载片段运输节点">
|
||||
<strong>运输节点</strong>
|
||||
<el-table v-if="rows.length" :data="rows" row-key="key" border size="small">
|
||||
<el-table-column prop="inboundCode" label="入仓码" min-width="155" />
|
||||
<el-table-column prop="cabinetNo" label="柜次" width="90" />
|
||||
<el-table-column prop="containerNo" label="集装箱号" min-width="145" />
|
||||
<el-table-column prop="nodeLabel" label="节点" min-width="150" />
|
||||
<el-table-column label="实际时间" min-width="175"><template #default="{ row }">{{ time(row.actualAt) }}</template></el-table-column>
|
||||
<el-table-column label="预计时间" min-width="175"><template #default="{ row }">{{ time(row.estimatedAt) }}</template></el-table-column>
|
||||
<el-table-column prop="location" label="地点" min-width="130" />
|
||||
<el-table-column prop="source" label="来源" width="105" />
|
||||
</el-table>
|
||||
<p v-else>暂无实际装载片段的运输节点。预计时间不表示实际发生。</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.transport-facts { margin-top: 9px; }
|
||||
.transport-facts > strong { display: block; padding: 7px 0 5px; color: var(--navy); font-size: 11px; }
|
||||
.transport-facts > p { color: var(--muted); font-size: 11px; }
|
||||
</style>
|
||||
@@ -0,0 +1,430 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
function compile(path, dependencies) {
|
||||
const source = readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function harness(t) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = []
|
||||
const behavior = { failWrite: false, failRead: false, version: 9, status: 'DRAFT' }
|
||||
const api = compile('../api/firstLeg.ts', { '@/api/http': { apiRequest: async config => {
|
||||
calls.push(structuredClone(config))
|
||||
if (config.method === 'GET') {
|
||||
if (behavior.failRead) throw new Error('读取失败')
|
||||
return { order: { id: 'one', orderNo: 'FL-ONE', version: behavior.version, status: behavior.status, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress, destinationCountryCode: 'US' }, cargoes: [] }
|
||||
}
|
||||
if (behavior.failWrite || (behavior.failSubmit && config.url.endsWith('/submit'))) throw new Error('响应丢失')
|
||||
if (config.url.endsWith('/submit') && behavior.failSubmitRead) behavior.failRead = true
|
||||
if (config.method === 'POST' && config.url === '/merchant/v1/orders/first-leg') return 'one'
|
||||
} } })
|
||||
const module = compile('./firstLegOrders.ts', {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': api,
|
||||
'@/modules/first-leg/api/unifiedOrders': {
|
||||
getMerchantUnifiedOrder: async () => ({ summary: { orderId: 'one', mainStatus: null }, order: { order: { id: 'one', status: behavior.status, version: behavior.version, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress } }, timeline: [] }),
|
||||
},
|
||||
'@/modules/first-leg/utils/firstLegOrder': { canClientEditFirstLegOrder: status => status === 'DRAFT', getFirstLegStatusLabel: value => value },
|
||||
'@/modules/first-leg/utils/warehousePagination': {},
|
||||
})
|
||||
const store = module.useFirstLegOrdersStore()
|
||||
store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC' }]
|
||||
const draft = { receivingWarehouseId: 'warehouse', destinationType: 'PRIVATE', destinationCountryCode: 'US', items: [], customerRemark: '原草稿' }
|
||||
return { store, api, calls, behavior, draft }
|
||||
}
|
||||
|
||||
function displayedWarehouseAddress(order) {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const expressions = [...view.matchAll(/\{\{ (detailOrder\.receivingWarehouseSnapshot\.(?:province|city|address)) \}\}/g)]
|
||||
assert.equal(expressions.length, 3)
|
||||
return expressions.map(([, expression]) => new Function('detailOrder', `return ${expression}`)(order)).join('')
|
||||
}
|
||||
|
||||
test('complete address is identical for cold unified, warm unified, raw detail and remark-only save', async t => {
|
||||
const h = harness(t)
|
||||
const fullAddress = 'CN 浙江省 义乌市 仓库路 8 号 322000'
|
||||
h.behavior.receivingWarehouseAddress = fullAddress
|
||||
h.store.warehouses = []
|
||||
const cold = await h.store.loadDetail('one')
|
||||
assert.equal(displayedWarehouseAddress(cold), fullAddress)
|
||||
h.store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC', province: '浙江省', city: '义乌市', address: '主档已更新的地址' }]
|
||||
h.store.orders = []
|
||||
const warm = await h.store.loadDetail('one')
|
||||
const raw = await h.store.loadDraftDetail('one')
|
||||
for (const detail of [warm, raw]) {
|
||||
assert.equal(displayedWarehouseAddress(detail), fullAddress)
|
||||
assert.equal(detail.receivingWarehouseSnapshot.province, '')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.city, '')
|
||||
}
|
||||
const session = h.store.beginDraftEdit(raw)
|
||||
h.draft.customerRemark = '仅修改备注'
|
||||
const saved = await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
assert.equal(displayedWarehouseAddress(saved), fullAddress)
|
||||
const write = h.calls.find(call => call.method === 'PUT')
|
||||
assert.equal(write.data.draft.customerRemark, '仅修改备注')
|
||||
assert.equal(Object.hasOwn(write.data.draft, 'receivingWarehouseAddress'), false)
|
||||
assert.equal(h.behavior.receivingWarehouseAddress, fullAddress)
|
||||
assert.equal(h.store.warehouses[0].province, '浙江省')
|
||||
assert.equal(h.store.warehouses[0].address, '主档已更新的地址')
|
||||
})
|
||||
|
||||
test('structured master address stays structured when no order address snapshot exists', async t => {
|
||||
const h = harness(t)
|
||||
h.store.warehouses = [{ id: 'warehouse', name: '国内仓', province: '浙江省', city: '义乌市', address: '仓库路 8 号', warehouseType: 'DOMESTIC' }]
|
||||
const detail = await h.store.loadDetail('one')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.province, '浙江省')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.city, '义乌市')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.address, '仓库路 8 号')
|
||||
assert.equal(displayedWarehouseAddress(detail), '浙江省义乌市仓库路 8 号')
|
||||
})
|
||||
|
||||
test('raw and unified cancelled detail remain CANCELLED even when unified mainStatus is null', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.status = 'CANCELLED'
|
||||
const raw = await h.store.loadDraftDetail('one')
|
||||
assert.equal(raw.status, 'CANCELLED')
|
||||
const unified = await h.store.loadDetail('one')
|
||||
assert.equal(unified.status, 'CANCELLED')
|
||||
h.behavior.status = 'APPROVED'
|
||||
const unknown = await h.store.loadDetail('one')
|
||||
assert.notEqual(unknown.status, 'CANCELLED', 'unknown summary must not be reclassified as cancellation')
|
||||
})
|
||||
|
||||
test('fresh direct draft detail preserves raw DRAFT with null unified summary and opens an edit session', async t => {
|
||||
const h = harness(t)
|
||||
assert.equal(h.store.orders.length, 0)
|
||||
const direct = await h.store.loadDetail('one')
|
||||
assert.equal(direct.status, 'DRAFT')
|
||||
assert.equal(h.store.beginDraftEdit(direct).expectedVersion, 9)
|
||||
h.store.orders = []
|
||||
const refreshed = await h.store.loadDetail('one')
|
||||
assert.equal(refreshed.status, 'DRAFT')
|
||||
h.store.orders = []
|
||||
h.behavior.status = 'APPROVED'
|
||||
const unknown = await h.store.loadDetail('one')
|
||||
assert.notEqual(unknown.status, 'DRAFT')
|
||||
assert.notEqual(unknown.status, 'CANCELLED')
|
||||
assert.throws(() => h.store.beginDraftEdit(unknown), /重新打开/)
|
||||
})
|
||||
|
||||
test('cancelled detail summary has no pending overseas synchronization entries', () => {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const declaration = ast.statements.flatMap(node => ts.isVariableStatement(node) ? [...node.declarationList.declarations] : []).find(node => node.name.getText(ast) === 'progressSummaryItems')
|
||||
const code = ts.transpileModule('const progressSummaryItems = ' + declaration.initializer.getText(ast), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const summary = new Function('computed', 'detailOrder', code + '; return progressSummaryItems.value')(vue.computed, { value: { status: 'CANCELLED' } })
|
||||
assert.deepEqual(summary, [])
|
||||
})
|
||||
|
||||
test('edit freezes detail version rather than cached list version and replays same key/body after uncertain result', async t => {
|
||||
const h = harness(t)
|
||||
const original = await h.store.loadDraftDetail('one')
|
||||
const session = h.store.beginDraftEdit(original)
|
||||
h.store.orders = [{ ...original, version: 0 }]
|
||||
h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '测试企业', 'one', session), /响应丢失/)
|
||||
const first = h.calls.find(call => call.method === 'PUT')
|
||||
assert.equal(first.data.expectedVersion, 9)
|
||||
assert.equal(first.data.draft.customerRemark, '原草稿')
|
||||
assert.ok(first.headers['Idempotency-Key'])
|
||||
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT'], 'no pre-save version refresh')
|
||||
h.behavior.failWrite = false; h.behavior.version = 10
|
||||
const result = await h.store.saveDraft(h.draft, '测试企业', 'one', session)
|
||||
const writes = h.calls.filter(call => call.method === 'PUT')
|
||||
assert.deepEqual(writes[1], first)
|
||||
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT', 'GET', 'PUT', 'GET'])
|
||||
assert.equal(result.version, 10)
|
||||
})
|
||||
|
||||
test('changed retry payload or missing edit session fails closed without issuing a new write', async t => {
|
||||
const h = harness(t)
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
|
||||
assert.equal(h.calls.length, 0)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session))
|
||||
h.draft.customerRemark = '不同内容'
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /重试原内容/)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
assert.equal(session.expectedVersion, 9)
|
||||
assert.ok(Object.isFrozen(session))
|
||||
})
|
||||
|
||||
test('read failure after successful edit preserves the same command for retry', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.behavior.failRead = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /读取失败/)
|
||||
h.behavior.failRead = false
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
const writes = h.calls.filter(call => call.method === 'PUT')
|
||||
assert.deepEqual(writes[0], writes[1])
|
||||
})
|
||||
|
||||
test('cancel forwards version and reason without rejecting submitted orders locally; retry keeps key and body', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.status = 'SUBMITTED'
|
||||
h.store.orders = [{ id: 'one', status: 'PENDING_REVIEW', version: 0 }]
|
||||
h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.cancelOrder('one', 12, '客户要求取消'), /响应丢失/)
|
||||
const first = h.calls[0]
|
||||
assert.equal(first.method, 'POST')
|
||||
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/cancel')
|
||||
assert.deepEqual(first.data, { expectedVersion: 12, reason: '客户要求取消' })
|
||||
await assert.rejects(h.store.cancelOrder('one', 13, '其他原因'), /原版本和原因/)
|
||||
assert.equal(h.calls.length, 1)
|
||||
h.behavior.failWrite = false
|
||||
await h.store.cancelOrder('one', 12, '客户要求取消')
|
||||
assert.deepEqual(h.calls[2], first)
|
||||
assert.equal(h.calls[1].method, 'GET')
|
||||
assert.equal(h.store.orders.length, 0)
|
||||
})
|
||||
|
||||
test('cancel requires a detail version and a nonempty reason', async t => {
|
||||
const h = harness(t)
|
||||
await assert.rejects(h.store.cancelOrder('one', undefined, '理由'))
|
||||
await assert.rejects(h.store.cancelOrder('one', 1, ' '))
|
||||
assert.equal(h.calls.length, 0)
|
||||
})
|
||||
|
||||
test('cancellation decision reads raw server status and version including SUBMITTED', async t => {
|
||||
const h = harness(t)
|
||||
for (const status of ['DRAFT', 'SUBMITTED', 'APPROVED', 'ACCEPTED', 'REJECTED']) {
|
||||
h.behavior.status = status
|
||||
const target = await h.store.prepareCancellation('one')
|
||||
assert.equal(target.expectedVersion, 9)
|
||||
assert.equal(target.businessNo, 'FL-ONE')
|
||||
}
|
||||
for (const status of ['PROCESSING', 'COMPLETED', 'CANCELLED']) {
|
||||
h.behavior.status = status
|
||||
await assert.rejects(h.store.prepareCancellation('one'), /不允许取消/)
|
||||
}
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
})
|
||||
|
||||
function cancellationViewHarness() {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['canOfferCancellation', 'cancelOrder'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const calls = [], messages = [], prompts = []
|
||||
const canCancelOrder = vue.ref(true), cancellingOrderId = vue.ref(''), pendingCancellation = vue.shallowRef()
|
||||
class ApiError extends Error { constructor() { super('订单版本已变化'); this.code = 'A0409'; this.status = 409 } }
|
||||
const behavior = { error: null }
|
||||
const store = {
|
||||
prepareCancellation: async id => { calls.push(['prepare', id]); return { id, expectedVersion: 12, businessNo: 'FL-ONE', statusLabel: '审核中' } },
|
||||
cancelOrder: async (...args) => { calls.push(['cancel', ...args]); if (behavior.error) throw behavior.error },
|
||||
load: async query => calls.push(['load', query]),
|
||||
}
|
||||
const ElMessageBox = {
|
||||
prompt: async (message, title, options) => { prompts.push({ message, title, options }); return { value: '客户申请取消' } },
|
||||
confirm: async (...args) => calls.push(['confirm', ...args]),
|
||||
}
|
||||
const ElMessage = { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) }
|
||||
const globals = { canCancelOrder, cancellingOrderId, pendingCancellation, store, ElMessageBox, ElMessage, ApiError,
|
||||
loadOrderPage: async () => calls.push(['load']),
|
||||
isDetailPage: vue.ref(true), router: { push: async route => calls.push(['route', route]) } }
|
||||
const handler = new Function(...Object.keys(globals), code + '\nreturn cancelOrder')(...Object.values(globals))
|
||||
return { handler, calls, messages, prompts, canCancelOrder, pendingCancellation, behavior, ApiError }
|
||||
}
|
||||
|
||||
test('cancel UI uses mandatory-reason centered prompt and refreshes after successful submitted-order cancellation', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
await h.handler({ id: 'one', status: 'PENDING_REVIEW' })
|
||||
assert.match(h.prompts[0].message, /FL-ONE.*审核中/)
|
||||
const validate = h.prompts[0].options.inputValidator
|
||||
assert.notEqual(validate(' '), true)
|
||||
assert.notEqual(validate('x'.repeat(501)), true)
|
||||
assert.equal(validate('合理原因'), true)
|
||||
assert.deepEqual(h.calls.map(call => call[0]), ['prepare', 'cancel', 'load', 'route'])
|
||||
assert.deepEqual(h.calls[1], ['cancel', 'one', 12, '客户申请取消'])
|
||||
})
|
||||
|
||||
test('cancel UI keeps an uncertain command for explicit retry, but conflict requires a fresh decision', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
const order = { id: 'one', status: 'DRAFT' }
|
||||
h.behavior.error = new Error('网络无响应')
|
||||
await h.handler(order)
|
||||
assert.equal(h.pendingCancellation.value.expectedVersion, 12)
|
||||
h.behavior.error = null
|
||||
await h.handler(order)
|
||||
assert.equal(h.prompts.length, 1)
|
||||
assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 1)
|
||||
assert.equal(h.calls.filter(call => call[0] === 'confirm').length, 1)
|
||||
assert.deepEqual(h.calls.filter(call => call[0] === 'cancel')[0], h.calls.filter(call => call[0] === 'cancel')[1])
|
||||
h.behavior.error = new h.ApiError()
|
||||
await h.handler(order)
|
||||
assert.equal(h.pendingCancellation.value, undefined)
|
||||
assert.match(h.messages.at(-1), /刷新订单后重新确认/)
|
||||
})
|
||||
|
||||
test('cancel UI blocks unavailable permission and irreversible visible stages before reads or writes', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
h.canCancelOrder.value = false
|
||||
await h.handler({ id: 'one', status: 'DRAFT' })
|
||||
h.canCancelOrder.value = true
|
||||
await h.handler({ id: 'one', status: 'LOADED' })
|
||||
assert.equal(h.calls.length, 0)
|
||||
assert.equal(h.prompts.length, 0)
|
||||
})
|
||||
|
||||
test('both editor entry points capture detail sessions and both save paths pass them', () => {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
assert.equal((view.match(/editingSession\.value = store\.beginDraftEdit\(detailedOrder\)/g) ?? []).length, 2)
|
||||
assert.equal((view.match(/store\.saveDraft(?:ForSubmission)?\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2)
|
||||
})
|
||||
|
||||
test('submit reads raw detail version rather than list zero and replays original key and version after timeout', async t => {
|
||||
const h = harness(t)
|
||||
h.store.orders = [{ id: 'one', status: 'DRAFT', version: 0 }]
|
||||
h.behavior.failSubmit = true
|
||||
await assert.rejects(h.store.submitSaved('one', 'ACTIVE'), /响应丢失/)
|
||||
const first = h.calls[1]
|
||||
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/submit')
|
||||
assert.deepEqual(first.data, { expectedVersion: 9 })
|
||||
assert.ok(first.headers['Idempotency-Key'])
|
||||
h.behavior.version = 10; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
|
||||
await h.store.submitSaved('one', 'ACTIVE')
|
||||
assert.deepEqual(h.calls[3], first)
|
||||
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'POST', 'GET', 'POST', 'GET'])
|
||||
assert.equal(h.store.hasPendingSubmission('one'), false)
|
||||
})
|
||||
|
||||
test('submit refuses missing version or non-draft first decision and preserves command after failed readback', async t => {
|
||||
const h = harness(t)
|
||||
for (const version of [undefined, -1, 1.5]) {
|
||||
h.behavior.version = version
|
||||
await assert.rejects(h.store.submitSaved('one'), /版本缺失/)
|
||||
}
|
||||
h.behavior.version = 0; h.behavior.status = 'SUBMITTED'
|
||||
await assert.rejects(h.store.submitSaved('one'), /不是草稿/)
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
h.behavior.status = 'DRAFT'; h.behavior.failSubmitRead = true
|
||||
await assert.rejects(h.store.submitSaved('one'), /读取失败/)
|
||||
assert.equal(h.store.hasPendingSubmission('one'), true)
|
||||
h.behavior.failRead = false; h.behavior.failSubmitRead = false
|
||||
await h.store.submitSaved('one')
|
||||
const posts = h.calls.filter(call => call.method === 'POST')
|
||||
assert.deepEqual(posts[0], posts[1])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 0 }, 'raw detail zero is valid')
|
||||
})
|
||||
|
||||
test('save then submit retries without another save and changed form requires an explicit new decision', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
h.behavior.failSubmit = true
|
||||
await assert.rejects(h.store.submitSaved('one'))
|
||||
const first = h.calls.find(call => call.url.endsWith('/submit'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
h.draft.customerRemark = '新决定'
|
||||
await assert.rejects(h.store.saveDraftForSubmission(h.draft, '客户', 'one', session), /重新编辑/)
|
||||
h.behavior.status = 'SUBMITTED'
|
||||
await assert.rejects(h.store.beginNewSubmissionEdit('one'), /不能重新编辑/)
|
||||
assert.equal(h.store.hasPendingSubmission('one'), true)
|
||||
h.behavior.status = 'DRAFT'; h.behavior.version = 12
|
||||
const newSession = await h.store.beginNewSubmissionEdit('one')
|
||||
assert.equal(newSession.expectedVersion, 12)
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', newSession)
|
||||
h.behavior.version = 13; h.behavior.failSubmit = false
|
||||
await h.store.submitSaved('one')
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.notEqual(posts[1].headers['Idempotency-Key'], first.headers['Idempotency-Key'])
|
||||
assert.deepEqual(posts[1].data, { expectedVersion: 13 })
|
||||
})
|
||||
|
||||
test('failed initial submit read does not resave the prepared draft on retry', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
h.behavior.failRead = true
|
||||
await assert.rejects(h.store.submitSaved('one'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
})
|
||||
|
||||
async function submissionViewHarness(t) {
|
||||
const h = harness(t)
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['submitOrder', 'confirmSubmissionEdit', 'submitSelectedDraftOrders'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const messages = [], confirmations = []
|
||||
const globals = {
|
||||
store: h.store, saving: vue.ref(false), form: h.draft, cloneDraft: draft => structuredClone(draft),
|
||||
editingId: vue.ref('one'), editingSession: vue.shallowRef(h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))),
|
||||
companySubmissionBlocked: vue.ref(false), companyAuditLoaded: vue.ref(true), tenantStore: { company: { companyName: '客户', auditStatus: 'ACTIVE' } },
|
||||
validateEditorForm: async () => true, markEditorClean: () => {}, editorOpen: vue.ref(true), isCreatePage: vue.ref(false), loadPageData: async () => {},
|
||||
batchSubmitting: vue.ref(false), selectedDraftOrders: vue.ref([{ id: 'one', version: 0 }]), pendingBatchSubmissionIds: vue.ref([]),
|
||||
searchOrders: async () => { globals.selectedDraftOrders.value = [] }, appliedFilters: vue.ref({}),
|
||||
ElMessageBox: { confirm: async message => { confirmations.push(message); if (h.behavior.cancelConfirm) throw 'cancel' } },
|
||||
ElMessage: { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) },
|
||||
}
|
||||
const handlers = new Function(...Object.keys(globals), code + '\nreturn {submitOrder, submitSelectedDraftOrders}')(...Object.values(globals))
|
||||
return { ...h, ...handlers, globals, messages, confirmations }
|
||||
}
|
||||
|
||||
test('real editor submit handler retries original submission without PUT and requires confirmation for changed form', async t => {
|
||||
const h = await submissionViewHarness(t)
|
||||
h.behavior.failSubmit = true
|
||||
await h.submitOrder()
|
||||
await h.submitOrder()
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.deepEqual(posts[0], posts[1])
|
||||
h.draft.customerRemark = '修改后的决定'
|
||||
h.behavior.cancelConfirm = true
|
||||
await h.submitOrder()
|
||||
assert.equal(h.confirmations.length, 1)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
h.behavior.cancelConfirm = false; h.behavior.failSubmit = false; h.behavior.version = 12
|
||||
await h.submitOrder()
|
||||
assert.equal(h.confirmations.length, 2)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
|
||||
const last = h.calls.filter(call => call.url.endsWith('/submit')).at(-1)
|
||||
assert.deepEqual(last.data, { expectedVersion: 12 })
|
||||
assert.notEqual(last.headers['Idempotency-Key'], posts[0].headers['Idempotency-Key'])
|
||||
assert.equal(h.globals.saving.value, false)
|
||||
})
|
||||
|
||||
test('real batch handler retains uncertain IDs across list refresh and retries original commands even if now submitted', async t => {
|
||||
const h = await submissionViewHarness(t)
|
||||
h.behavior.failSubmit = true
|
||||
await h.submitSelectedDraftOrders()
|
||||
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, ['one'])
|
||||
assert.deepEqual(h.globals.selectedDraftOrders.value, [])
|
||||
h.behavior.failSubmit = false; h.behavior.status = 'SUBMITTED'; h.behavior.version = 10
|
||||
await h.submitSelectedDraftOrders()
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.equal(posts.length, 2)
|
||||
assert.deepEqual(posts[1], posts[0])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 9 })
|
||||
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, [])
|
||||
assert.equal(h.globals.batchSubmitting.value, false)
|
||||
})
|
||||
|
||||
test('real new-order handler creates once and retries the saved order submission with the original version', async t => {
|
||||
const h = await submissionViewHarness(t)
|
||||
h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined
|
||||
h.behavior.version = 0; h.behavior.failSubmit = true
|
||||
await h.submitOrder()
|
||||
assert.equal(h.globals.editingId.value, 'one')
|
||||
h.behavior.version = 1; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
|
||||
await h.submitOrder()
|
||||
assert.equal(h.calls.filter(call => call.method === 'POST' && call.url === '/merchant/v1/orders/first-leg').length, 1)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 0)
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.deepEqual(posts[0], posts[1])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 0 })
|
||||
})
|
||||
@@ -27,22 +27,10 @@ test('renders estimated sailing from the current API without substituting actual
|
||||
assert.equal(map({ transport: null }).estimatedPortArrivalAt, '')
|
||||
})
|
||||
|
||||
test('maps the first-leg aggregate list fields without loading detail rows', () => {
|
||||
assert.match(apiSource, /interface MerchantFirstLegOrderRow/)
|
||||
assert.match(apiSource, /skuNos: string \| string\[\] \| null/)
|
||||
assert.match(apiSource, /cargoes\?: Array<\{ skuNo\?: string \| null \}>/)
|
||||
assert.match(apiSource, /apiRequest<PageResult<MerchantFirstLegOrderRow>>/)
|
||||
assert.match(storeSource, /function mapFirstLegOrderRow/)
|
||||
for (const field of ['inboundId', 'inboundCode', 'channelName', 'destinationWarehouseName', 'pickupMethod', 'packageCount', 'expressCompany', 'trackingNo', 'totalGrossWeightKg', 'totalNetWeightKg', 'totalVolumeCbm', 'totalQuantity', 'remark', 'shipmentId', 'fulfillmentType', 'lxCode', 'referenceId', 'createdAt']) {
|
||||
assert.match(storeSource, new RegExp(`row\\.${field}`))
|
||||
}
|
||||
assert.match(storeSource, /row\.skuNos/)
|
||||
assert.match(storeSource, /row\.cargoes/)
|
||||
assert.match(storeSource, /chargeableWeightKg: null/)
|
||||
assert.match(storeSource, /chargeableVolumeCbm: null/)
|
||||
assert.match(apiSource, /pickupMethod: ApiPickupMethod \\| null/)
|
||||
assert.match(storeSource, /orderResult\.value\.records\.map\(mapFirstLegOrderRow\)/)
|
||||
assert.match(storeSource, /orderResult\.value\.records\.map\(\(item\) => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||
test('maps the current workbench row without loading detail rows', () => {
|
||||
assert.match(storeSource, /result\.page\.records\.map\(item => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||
assert.match(storeSource, /version: summary\.orderVersion/)
|
||||
assert.doesNotMatch(storeSource, /function mapFirstLegOrderRow/)
|
||||
})
|
||||
|
||||
test('declares the documented merchant warehouse and first-leg endpoints', () => {
|
||||
@@ -85,14 +73,10 @@ test('maps transport and status fields instead of treating container mode as tra
|
||||
assert.doesNotMatch(storeSource, /status === 'COMPLETED'\) return 'DELIVERED'/)
|
||||
})
|
||||
|
||||
test('prefers unified reads and only falls back to the real legacy API when C02 is unavailable', () => {
|
||||
test('uses only the formal workbench read and surfaces failures', () => {
|
||||
assert.match(storeSource, /getMerchantOrderWorkbench\(query\)/)
|
||||
assert.match(storeSource, /orders\.value = \[\]/)
|
||||
assert.match(storeSource, /warehouses\.value = \[\]/)
|
||||
assert.match(storeSource, /Promise\.allSettled\(\[getOrdersForClient\(query\), loadWarehouseType\('DOMESTIC', true\)\]\)/)
|
||||
assert.match(storeSource, /getMerchantUnifiedOrders\(unifiedQuery\)/)
|
||||
assert.match(storeSource, /isUnifiedOrderQueryUnavailable\(error\)/)
|
||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query\)\)/)
|
||||
assert.doesNotMatch(storeSource, /DEMO_PLATFORM_RECEIVING_WAREHOUSES|initialOrders/)
|
||||
assert.doesNotMatch(storeSource, /isUnifiedOrderQueryUnavailable|getOrdersForClient|getMerchantFirstLegOrders|initialOrders/)
|
||||
})
|
||||
|
||||
test('declares the final C02 row and detail contract in the API adapter', () => {
|
||||
@@ -115,7 +99,6 @@ test('declares the final C02 row and detail contract in the API adapter', () =>
|
||||
assert.match(unifiedApiSource, /order: MerchantFirstLegOrderDetail/)
|
||||
assert.match(unifiedApiSource, /timeline: MerchantUnifiedTimelineEvent\[\]/)
|
||||
assert.match(unifiedApiSource, /customNodes\?: MerchantUnifiedCustomNode\[\]/)
|
||||
assert.match(unifiedApiSource, /error\.status === 404 \|\| error\.code === 'A0404'/)
|
||||
})
|
||||
|
||||
test('keeps unified order pagination valid when the store omits page and size', () => {
|
||||
@@ -123,21 +106,10 @@ test('keeps unified order pagination valid when the store omits page and size',
|
||||
assert.match(unifiedApiSource, /params: \{ page: page \?\? 1, size: size \?\? 200, \.\.\.filters \}/)
|
||||
})
|
||||
|
||||
test('keeps drafts on the legacy read path without assigning a unified main status', () => {
|
||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query, 'DRAFT'\)\)/)
|
||||
assert.match(storeSource, /const listOrder = getById\(id\)/)
|
||||
assert.match(storeSource, /listOrder\?\.status === 'DRAFT' \? loadLegacyDetail\(id, listOrder\) : loadUnifiedDetail\(id\)/)
|
||||
assert.match(storeSource, /detail\.order\.lxCode == null && listOrder\?\.lxCode/)
|
||||
assert.match(storeSource, /return loadLegacyDetail\(String\(createdId\)\)/)
|
||||
assert.match(storeSource, /draftLoadError/)
|
||||
})
|
||||
|
||||
test('routes supported filters to C02 without sending DRAFT as a main status', () => {
|
||||
assert.match(storeSource, /interface ClientOrderReadQuery extends MerchantUnifiedOrderQuery/)
|
||||
assert.match(storeSource, /if \(query\.draftOnly\)/)
|
||||
assert.match(storeSource, /const unifiedQuery: MerchantUnifiedOrderQuery/)
|
||||
assert.match(storeSource, /inboundCode: query\.inboundCode/)
|
||||
assert.match(storeSource, /getMerchantUnifiedOrders\(unifiedQuery\)/)
|
||||
test('draft editing reads the order aggregate while navigation uses unified detail', () => {
|
||||
assert.match(storeSource, /return loadOrderAggregate\(id\)/)
|
||||
assert.match(storeSource, /const detail = await getMerchantUnifiedOrder\(id\)/)
|
||||
assert.doesNotMatch(storeSource, /loadLegacyDetail|draftOnly|includeDrafts/)
|
||||
})
|
||||
|
||||
test('maps C02 authoritative status, transport, cargo and pickup snapshots', () => {
|
||||
@@ -195,7 +167,7 @@ test('separates domestic receiving warehouses from public destinations', () => {
|
||||
assert.match(apiSource, /warehouseType\?: MerchantWarehouseType/)
|
||||
assert.match(apiSource, /params: \{ page: 1, size: 200, status: 'ACTIVE', \.\.\.params \}/)
|
||||
assert.match(storeSource, /loadAllWarehouseRecords\(warehouseType, getMerchantWarehouses\)/)
|
||||
assert.match(storeSource, /loadWarehouseType\('DOMESTIC', true\)/)
|
||||
assert.match(storeSource, /loadWarehouseType\('DOMESTIC'\)/)
|
||||
assert.match(storeSource, /warehouse\.warehouseType !== 'DOMESTIC'/)
|
||||
assert.match(storeSource, /item\.warehouseType === draft\.destinationType/)
|
||||
assert.match(storeSource, /draft\.amazonWarehouseCode = draft\.destinationType === 'FBA' \? destinationWarehouse\.code : ''/)
|
||||
@@ -206,20 +178,20 @@ test('only blocks submission when a known company audit status is not active', (
|
||||
assert.match(storeSource, /if \(companyAuditStatus && companyAuditStatus !== 'ACTIVE'\)/)
|
||||
})
|
||||
|
||||
test('does not expose the out-of-scope cancellation write', () => {
|
||||
assert.doesNotMatch(storeSource, /cancelMerchant|function cancel|\/cancel/)
|
||||
assert.doesNotMatch(apiSource, /\/cancel/)
|
||||
test('uses the versioned merchant cancellation contract', () => {
|
||||
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
|
||||
})
|
||||
|
||||
test('sends an idempotency key for create and submit writes', () => {
|
||||
assert.match(apiSource, /'Idempotency-Key': createIdempotencyKey\('first-leg-create'\)/)
|
||||
assert.match(apiSource, /submitMerchantFirstLegOrder\(id: number \| string, idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /submitMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number \}, idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /'Idempotency-Key': idempotencyKey/)
|
||||
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
||||
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
|
||||
assert.match(storeSource, /pendingSubmitKeys\.get\(id\) \?\? createIdempotencyKey\(`first-leg-submit-\$\{id\}`\)/)
|
||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, idempotencyKey\)/)
|
||||
assert.match(storeSource, /pendingSubmissions\.get\(id\)/)
|
||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||
})
|
||||
|
||||
test('does not expose the contradictory backend rejected state in the client model', () => {
|
||||
@@ -264,5 +236,5 @@ test('keeps failed order loads distinct from empty results', () => {
|
||||
assert.match(storeSource, /const loadError = ref\(''\)/)
|
||||
assert.match(storeSource, /orderResult\.reason instanceof Error/)
|
||||
assert.match(storeSource, /warehouseLoadError/)
|
||||
assert.match(storeSource, /return \{ orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError/)
|
||||
assert.match(storeSource, /return \{ orders, orderDetails, total, queueCounts, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError/)
|
||||
})
|
||||
|
||||
@@ -1,29 +1,27 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import {
|
||||
createMerchantFirstLegOrderBatch,
|
||||
createMerchantFirstLegOrder,
|
||||
createIdempotencyKey,
|
||||
getMerchantFirstLegOrder,
|
||||
getMerchantFirstLegOrders,
|
||||
getMerchantWarehouseDetail,
|
||||
getMerchantWarehouses,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantFirstLegOrder,
|
||||
cancelMerchantFirstLegOrder,
|
||||
type ApiFirstLegStatus,
|
||||
type FirstLegOrderSaveRequest,
|
||||
type MerchantFirstLegOrder,
|
||||
type MerchantFirstLegOrderRow,
|
||||
type MerchantFirstLegOrderDetail,
|
||||
type MerchantBatchDraftResponse,
|
||||
type MerchantWarehouse,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import {
|
||||
getMerchantUnifiedOrder,
|
||||
getMerchantUnifiedOrders,
|
||||
isUnifiedOrderQueryUnavailable,
|
||||
getMerchantOrderWorkbench,
|
||||
type MerchantUnifiedOrderDetail,
|
||||
type MerchantUnifiedOrderQuery,
|
||||
type MerchantOrderWorkbenchQuery,
|
||||
type MerchantUnifiedOrderRow,
|
||||
} from '@/modules/first-leg/api/unifiedOrders'
|
||||
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
|
||||
@@ -46,7 +44,7 @@ function clientStatus(status: ApiFirstLegStatus): FirstLegOrder['status'] {
|
||||
if (status === 'REJECTED') return 'PENDING_REVIEW'
|
||||
if (status === 'APPROVED' || status === 'ACCEPTED' || status === 'PROCESSING') return 'WAIT_MEASURE'
|
||||
if (status === 'COMPLETED') return 'COMPLETED'
|
||||
if (status === 'CANCELLED') return 'PENDING_REVIEW'
|
||||
if (status === 'CANCELLED') return 'CANCELLED'
|
||||
return 'PENDING_REVIEW'
|
||||
}
|
||||
|
||||
@@ -159,8 +157,10 @@ function orderWarehouseSnapshot(order: MerchantFirstLegOrder, warehouse?: Platfo
|
||||
id: String(order.receivingWarehouseId),
|
||||
code: warehouse?.code ?? '',
|
||||
name: order.receivingWarehouseName,
|
||||
province: warehouse?.province ?? '',
|
||||
city: warehouse?.city ?? '',
|
||||
// Order stores the complete formatted address, including province and city.
|
||||
// Do not prefix this snapshot with fields from the current warehouse master.
|
||||
province: '',
|
||||
city: '',
|
||||
address: order.receivingWarehouseAddress,
|
||||
}
|
||||
}
|
||||
@@ -198,6 +198,7 @@ function timeline(detail: MerchantFirstLegOrderDetail): FirstLegOrderTimelineIte
|
||||
|
||||
function businessSummary(summary?: MerchantUnifiedOrderRow): FirstLegOrder['businessSummary'] {
|
||||
return {
|
||||
transportFragments: [],
|
||||
customerFeeConfirmationRequired: summary?.customerFeeConfirmationRequired ?? false,
|
||||
totalPackageCount: summary?.totalPackageCount ?? null,
|
||||
actualGrossWeightKg: summary?.actualGrossWeightKg ?? null,
|
||||
@@ -339,7 +340,7 @@ function mapUnifiedOrderRow(summary: MerchantUnifiedOrderRow, warehouses: Platfo
|
||||
trackingNumber: summary.expressTrackingNo ?? summary.delivery?.trackingNo ?? '', skuNos: summary.skuNos ?? [], totalNetWeightKg: summary.totalNetWeightKg ?? null,
|
||||
totalQuantity: summary.totalQuantity ?? null, chargeableVolumeCbm: summary.chargeableVolumeCbm ?? null,
|
||||
inboundedAt: summary.inboundCompletedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: summary.customerRemark ?? '', operatorName: '',
|
||||
status: summary.mainStatus, version: 0, items: [], timeline: [], businessSummary: businessSummary(summary),
|
||||
status: summary.mainStatus, version: summary.orderVersion, items: [], timeline: [], businessSummary: businessSummary(summary),
|
||||
createdAt: summary.createdAt, updatedAt: summary.updatedAt, tradeTerm: '', destinationCountryCode: '',
|
||||
destinationWarehouseId: summary.destinationWarehouseId == null ? '' : String(summary.destinationWarehouseId),
|
||||
destinationWarehouseName: summary.destinationWarehouseName ?? '', pickupMethod: summary.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||
@@ -349,44 +350,15 @@ function mapUnifiedOrderRow(summary: MerchantUnifiedOrderRow, warehouses: Platfo
|
||||
}
|
||||
}
|
||||
|
||||
function mapFirstLegOrderRow(row: MerchantFirstLegOrderRow): FirstLegOrder {
|
||||
const skuNos = Array.isArray(row.skuNos)
|
||||
? row.skuNos
|
||||
: (row.skuNos ?? '').split('、').map((value) => value.trim()).filter(Boolean)
|
||||
const resolvedSkuNos = skuNos.length ? skuNos : (row.cargoes ?? [])
|
||||
.map((cargo) => cargo.skuNo?.trim())
|
||||
.filter((value): value is string => Boolean(value))
|
||||
const uniqueSkuNos = [...new Set(resolvedSkuNos)]
|
||||
return {
|
||||
id: String(row.orderId), orderNo: row.orderNo, referenceNo: row.referenceId ?? '', transportMode: null,
|
||||
businessType: 'EXPORT', fulfillmentType: row.fulfillmentType ?? 'STANDARD', lxCode: row.lxCode ?? '', origin: '', destination: row.destinationWarehouseName ?? '', receivingWarehouseId: '',
|
||||
receivingWarehouseName: '', receivingWarehouseSnapshot: null, expectedDepartureDate: '', etd: '', eta: '',
|
||||
shipperPartyId: '', shipperPartySnapshot: null, shipper: '', consigneePartyId: '', consigneePartySnapshot: null,
|
||||
consignee: row.receivingCompanyName ?? '', expressCompanyName: row.expressCompany ?? '', trackingNumber: row.trackingNo ?? '',
|
||||
skuNos: uniqueSkuNos, totalNetWeightKg: row.totalNetWeightKg, totalQuantity: row.totalQuantity,
|
||||
chargeableVolumeCbm: null, inboundedAt: row.inboundedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: row.remark ?? '',
|
||||
operatorName: '', status: clientStatus(row.status), version: 0, items: [], timeline: [],
|
||||
businessSummary: {
|
||||
...businessSummary(), totalPackageCount: row.packageCount, actualGrossWeightKg: row.totalGrossWeightKg ?? row.weightKg,
|
||||
actualVolumeCbm: row.totalVolumeCbm, chargeableWeightKg: null,
|
||||
inboundId: row.inboundId == null ? '' : String(row.inboundId), inboundCode: row.inboundCode ?? '',
|
||||
},
|
||||
createdAt: row.createdAt, updatedAt: row.createdAt, tradeTerm: '', destinationCountryCode: '', destinationWarehouseId: '',
|
||||
destinationWarehouseName: row.destinationWarehouseName ?? '', pickupMethod: row.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||
channelName: row.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: 'BUY_DECLARATION',
|
||||
customsInspection: false, destinationType: row.destinationType ?? 'PRIVATE', amazonWarehouseCode: '',
|
||||
shipmentId: row.shipmentId ?? row.internationalOrderNo ?? '', requestedPickupAt: '', receivingTime: '', submittedAt: '', completedAt: '',
|
||||
}
|
||||
}
|
||||
|
||||
function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: PlatformReceivingWarehouse[]): FirstLegOrder {
|
||||
if (!detail?.summary || !detail.order?.order) throw new Error('订单详情数据不完整,请刷新列表后重试')
|
||||
const mapped = mapOrder(detail.order.order, warehouses, detail.order)
|
||||
mapped.id = String(detail.summary.orderId)
|
||||
mapped.status = detail.summary.mainStatus
|
||||
const rawStatus = detail.order.order.status
|
||||
mapped.status = rawStatus === 'CANCELLED' || rawStatus === 'DRAFT' ? rawStatus : detail.summary.mainStatus
|
||||
mapped.fulfillmentType = detail.summary.fulfillmentType ?? mapped.fulfillmentType
|
||||
mapped.lxCode = detail.summary.lxCode ?? mapped.lxCode
|
||||
mapped.businessSummary = businessSummary(detail.summary)
|
||||
mapped.businessSummary = { ...businessSummary(detail.summary), transportFragments: detail.transportFragments }
|
||||
mapped.timeline = unifiedTimeline(detail)
|
||||
const summary = mapUnifiedOrderRow(detail.summary, warehouses)
|
||||
mapped.referenceNo = summary.referenceNo
|
||||
@@ -406,59 +378,6 @@ function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: P
|
||||
return mapped
|
||||
}
|
||||
|
||||
type OrderListReadResult =
|
||||
| { source: 'first-leg'; records: MerchantFirstLegOrderRow[] }
|
||||
| { source: 'unified'; records: MerchantUnifiedOrderRow[]; drafts: MerchantFirstLegOrderRow[] }
|
||||
|
||||
interface ClientOrderReadQuery extends MerchantUnifiedOrderQuery {
|
||||
fbaCode?: string
|
||||
draftOnly?: boolean
|
||||
includeDrafts?: boolean
|
||||
}
|
||||
|
||||
function legacyQuery(query: ClientOrderReadQuery, status?: ApiFirstLegStatus) {
|
||||
return {
|
||||
keyword: query.keyword,
|
||||
status,
|
||||
createdFrom: query.createdFrom,
|
||||
createdTo: query.createdTo,
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrdersForClient(query: ClientOrderReadQuery = {}): Promise<OrderListReadResult> {
|
||||
if (query.draftOnly) {
|
||||
const response = await getMerchantFirstLegOrders(legacyQuery(query, 'DRAFT'))
|
||||
return { source: 'first-leg', records: response.records }
|
||||
}
|
||||
|
||||
const unifiedQuery: MerchantUnifiedOrderQuery = {
|
||||
keyword: query.keyword,
|
||||
orderNo: query.orderNo,
|
||||
mainStatus: query.mainStatus,
|
||||
receivingWarehouseId: query.receivingWarehouseId,
|
||||
destinationWarehouseId: query.destinationWarehouseId,
|
||||
inboundCode: query.inboundCode,
|
||||
createdFrom: query.createdFrom,
|
||||
createdTo: query.createdTo,
|
||||
fbaCode: query.fbaCode,
|
||||
page: query.page,
|
||||
size: query.size,
|
||||
}
|
||||
try {
|
||||
const [response, draftResponse] = await Promise.all([
|
||||
getMerchantUnifiedOrders(unifiedQuery),
|
||||
query.includeDrafts
|
||||
? getMerchantFirstLegOrders(legacyQuery(query, 'DRAFT'))
|
||||
: Promise.resolve({ records: [] as MerchantFirstLegOrderRow[] }),
|
||||
])
|
||||
return { source: 'unified', records: response.records, drafts: draftResponse.records }
|
||||
} catch (error) {
|
||||
if (!isUnifiedOrderQueryUnavailable(error)) throw error
|
||||
const response = await getMerchantFirstLegOrders(legacyQuery(query))
|
||||
return { source: 'first-leg', records: response.records }
|
||||
}
|
||||
}
|
||||
|
||||
function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
return {
|
||||
id: String(item.id), code: item.warehouseCode, name: item.warehouseName, province: '',
|
||||
@@ -468,21 +387,37 @@ function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
}
|
||||
}
|
||||
|
||||
export interface DraftEditSession {
|
||||
readonly orderId: string
|
||||
readonly expectedVersion: number
|
||||
}
|
||||
|
||||
export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', () => {
|
||||
const orders = ref<FirstLegOrder[]>([])
|
||||
const pendingSubmitKeys = new Map<string, string>()
|
||||
const orderDetails = ref<Record<string, FirstLegOrder>>({})
|
||||
const total = ref(0)
|
||||
const queueCounts = ref({ all: 0, fee: 0, customs: 0, draft: 0 })
|
||||
const queryChannelNames = ref<string[]>([])
|
||||
let listRequest = 0
|
||||
const pendingSubmissions = new Map<string, { key: string; payload: { expectedVersion: number } }>()
|
||||
const submissionForms = new Map<string, { snapshot: string; order: FirstLegOrder }>()
|
||||
const submittingIds = new Set<string>()
|
||||
const pendingEdits = new WeakMap<DraftEditSession, { key: string; payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest } }>()
|
||||
const pendingCancellations = new Map<string, { key: string; payload: { expectedVersion: number; reason: string } }>()
|
||||
|
||||
function beginDraftEdit(detail: FirstLegOrder): DraftEditSession {
|
||||
if (!canClientEditFirstLegOrder(detail.status) || !Number.isSafeInteger(detail.version) || detail.version < 0) throw new Error('请重新打开草稿详情后编辑')
|
||||
return Object.freeze({ orderId: detail.id, expectedVersion: detail.version })
|
||||
}
|
||||
const warehouses = ref<ClientWarehouse[]>([])
|
||||
const loading = ref(false)
|
||||
const loadedFromApi = ref(false)
|
||||
const loadError = ref('')
|
||||
const warehouseLoadError = ref('')
|
||||
const draftLoadError = ref('')
|
||||
const loadedWarehouseTypes = ref<ClientWarehouseType[]>([])
|
||||
const warehouseTypeRequests = new Map<ClientWarehouseType, Promise<ClientWarehouse[]>>()
|
||||
const activeCount = computed(() => orders.value.filter((item) => item.status !== 'DRAFT' && item.status !== 'DELIVERED').length)
|
||||
const pendingCount = computed(() => orders.value.filter((item) => item.status === 'PENDING_REVIEW').length)
|
||||
|
||||
function getById(id: string) { return orders.value.find((item) => item.id === id) }
|
||||
function getById(id: string) { return orders.value.find((item) => item.id === id) ?? orderDetails.value[id] }
|
||||
|
||||
async function loadWarehouseType(warehouseType: ClientWarehouseType, force = false) {
|
||||
if (warehouseType === 'DOMESTIC' && force) warehouseLoadError.value = ''
|
||||
@@ -509,28 +444,40 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
}
|
||||
}
|
||||
|
||||
async function load(query: ClientOrderReadQuery = {}) {
|
||||
async function load(query: MerchantOrderWorkbenchQuery = {}) {
|
||||
const request = ++listRequest
|
||||
loading.value = true
|
||||
loadedFromApi.value = true
|
||||
loadError.value = ''
|
||||
warehouseLoadError.value = ''
|
||||
draftLoadError.value = ''
|
||||
loadedWarehouseTypes.value = []
|
||||
warehouseTypeRequests.clear()
|
||||
orders.value = []
|
||||
warehouses.value = []
|
||||
const [orderResult, warehouseResult] = await Promise.allSettled([getOrdersForClient(query), loadWarehouseType('DOMESTIC', true)])
|
||||
if (warehouseResult.status === 'rejected' && !warehouseLoadError.value) warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||
total.value = 0
|
||||
queueCounts.value = { all: 0, fee: 0, customs: 0, draft: 0 }
|
||||
const [orderResult, warehouseResult] = await Promise.allSettled([
|
||||
getMerchantOrderWorkbench(query), loadWarehouseType('DOMESTIC'),
|
||||
])
|
||||
if (request !== listRequest) return 0
|
||||
if (warehouseResult.status === 'rejected') warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||
if (orderResult.status === 'fulfilled') {
|
||||
orders.value = orderResult.value.source === 'unified'
|
||||
? [
|
||||
...orderResult.value.drafts.map(mapFirstLegOrderRow),
|
||||
...orderResult.value.records.map((item) => mapUnifiedOrderRow(item, warehouses.value)),
|
||||
]
|
||||
: orderResult.value.records.map(mapFirstLegOrderRow)
|
||||
} else {
|
||||
loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||
}
|
||||
try {
|
||||
const result = orderResult.value
|
||||
const expectedPage = query.page ?? 1, size = query.size ?? 10
|
||||
const count = Number(result.page.total), pages = Math.ceil(count / size)
|
||||
if (!Number.isSafeInteger(count) || count < 0 || Number(result.page.page) !== expectedPage
|
||||
|| Number(result.page.size) !== size || Number(result.page.pages) !== pages
|
||||
|| result.page.records.length !== Math.min(size, Math.max(0, count - (expectedPage - 1) * size))
|
||||
|| new Set(result.page.records.map(row => String(row.orderId))).size !== result.page.records.length
|
||||
|| ['all', 'fee', 'customs', 'draft'].some(key => { const value = result.queues[key as keyof typeof result.queues]; return !Number.isSafeInteger(Number(value)) || Number(value) < 0 })
|
||||
|| Number(result.queues[query.queue ?? 'all']) !== count
|
||||
|| !Array.isArray(result.channelNames)) {
|
||||
loadError.value = '订单分页数据不完整,请重新加载'
|
||||
} else {
|
||||
orders.value = result.page.records.map(item => mapUnifiedOrderRow(item, warehouses.value))
|
||||
total.value = count
|
||||
queueCounts.value = { all: Number(result.queues.all), fee: Number(result.queues.fee), customs: Number(result.queues.customs), draft: Number(result.queues.draft) }
|
||||
queryChannelNames.value = result.channelNames
|
||||
}
|
||||
} catch { loadError.value = '订单分页数据不完整,请重新加载' }
|
||||
} else loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||
loading.value = false
|
||||
return orders.value.length
|
||||
}
|
||||
@@ -538,38 +485,18 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
function upsertOrder(mapped: FirstLegOrder) {
|
||||
const index = orders.value.findIndex((item) => item.id === mapped.id)
|
||||
if (index >= 0) orders.value[index] = mapped
|
||||
else orders.value.unshift(mapped)
|
||||
orderDetails.value[mapped.id] = mapped
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function loadLegacyDetail(id: string, listOrder?: FirstLegOrder) {
|
||||
async function loadOrderAggregate(id: string) {
|
||||
const detail = await getMerchantFirstLegOrder(id)
|
||||
const mapped = mapOrder(detail.order, warehouses.value, detail)
|
||||
// Older detail responses may omit newly added dropship fields. Keep the
|
||||
// values already returned by the list row so editing a draft does not
|
||||
// clear the persisted LX code in the form.
|
||||
if (detail.order.fulfillmentType == null && listOrder?.fulfillmentType) {
|
||||
mapped.fulfillmentType = listOrder.fulfillmentType
|
||||
}
|
||||
if (detail.order.lxCode == null && listOrder?.lxCode) {
|
||||
mapped.lxCode = listOrder.lxCode
|
||||
}
|
||||
return upsertOrder(mapped)
|
||||
}
|
||||
|
||||
async function loadUnifiedDetail(id: string) {
|
||||
try {
|
||||
const detail = await getMerchantUnifiedOrder(id)
|
||||
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value))
|
||||
} catch (error) {
|
||||
if (!isUnifiedOrderQueryUnavailable(error)) throw error
|
||||
return loadLegacyDetail(id)
|
||||
}
|
||||
return upsertOrder(mapOrder(detail.order, warehouses.value, detail))
|
||||
}
|
||||
|
||||
async function loadDetail(id: string) {
|
||||
const listOrder = getById(id)
|
||||
return listOrder?.status === 'DRAFT' ? loadLegacyDetail(id, listOrder) : loadUnifiedDetail(id)
|
||||
const detail = await getMerchantUnifiedOrder(id)
|
||||
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value))
|
||||
}
|
||||
|
||||
async function loadWarehouseDetail(id: string) {
|
||||
@@ -588,16 +515,51 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string) {
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||
if (hasPendingSubmission(id)) throw new Error('上次提交结果未确认,请重试原提交,或确认重新编辑后再保存')
|
||||
const warehouse = prepareDraftForSave(draft, warehouses.value)
|
||||
if (id) {
|
||||
const order = getById(id)
|
||||
if (!order || !canClientEditFirstLegOrder(order.status)) throw new Error('当前订单状态不允许编辑')
|
||||
await updateMerchantFirstLegOrder(id, savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(id)
|
||||
if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑')
|
||||
const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) }
|
||||
let pending = pendingEdits.get(editSession)
|
||||
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次保存结果未确认,请重试原内容,或重新打开详情后编辑')
|
||||
// Observe an uncertain previous outcome without replacing its frozen version.
|
||||
if (pending) await getMerchantFirstLegOrder(id)
|
||||
if (!pending) {
|
||||
pending = { key: createIdempotencyKey(`first-leg-edit-${id}`), payload: JSON.parse(JSON.stringify(payload)) }
|
||||
pendingEdits.set(editSession, pending)
|
||||
}
|
||||
await updateMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||
const saved = await loadOrderAggregate(id)
|
||||
pendingEdits.delete(editSession)
|
||||
return saved
|
||||
}
|
||||
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(String(createdId))
|
||||
return loadOrderAggregate(String(createdId))
|
||||
}
|
||||
|
||||
async function cancelOrder(id: string, expectedVersion: number, reason: string) {
|
||||
if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0 || !reason.trim() || reason.trim().length > 500) throw new Error('取消订单需要详情版本及 1–500 字取消原因')
|
||||
const payload = { expectedVersion, reason: reason.trim() }
|
||||
let pending = pendingCancellations.get(id)
|
||||
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次取消结果未确认,请使用原版本和原因重试')
|
||||
if (pending) await getMerchantFirstLegOrder(id)
|
||||
if (!pending) {
|
||||
pending = { key: createIdempotencyKey(`first-leg-cancel-${id}`), payload }
|
||||
pendingCancellations.set(id, pending)
|
||||
}
|
||||
await cancelMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||
pendingCancellations.delete(id)
|
||||
orders.value = orders.value.filter(order => order.id !== id)
|
||||
}
|
||||
|
||||
async function prepareCancellation(id: string) {
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '审核中', APPROVED: '已审核', ACCEPTED: '已接单', REJECTED: '已退回' }
|
||||
if (!Object.hasOwn(labels, order.status)) throw new Error('当前订单状态不允许取消,请刷新订单查看最新进度')
|
||||
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
pendingCancellations.delete(id)
|
||||
return { id, expectedVersion: order.version, businessNo: order.orderNo || order.inboundCode || '—', statusLabel: labels[order.status] }
|
||||
}
|
||||
|
||||
async function saveDraftBatch(
|
||||
@@ -614,21 +576,58 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
|
||||
async function submitSaved(id: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
if (companyAuditStatus && companyAuditStatus !== 'ACTIVE') throw new Error('企业资料尚未审核通过,请先完善企业资料并等待平台审核')
|
||||
const idempotencyKey = pendingSubmitKeys.get(id) ?? createIdempotencyKey(`first-leg-submit-${id}`)
|
||||
pendingSubmitKeys.set(id, idempotencyKey)
|
||||
await submitMerchantFirstLegOrder(id, idempotencyKey)
|
||||
pendingSubmitKeys.delete(id)
|
||||
return loadUnifiedDetail(id)
|
||||
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||
submittingIds.add(id)
|
||||
try {
|
||||
let pending = pendingSubmissions.get(id)
|
||||
// Always observe the raw detail; a retry must retain the original command.
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
if (!pending) {
|
||||
if (order.status !== 'DRAFT') throw new Error('当前订单不是草稿,请刷新订单查看最新状态')
|
||||
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
pending = { key: createIdempotencyKey(`first-leg-submit-${id}`), payload: { expectedVersion: order.version } }
|
||||
pendingSubmissions.set(id, pending)
|
||||
}
|
||||
await submitMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||
const submitted = await loadOrderAggregate(id)
|
||||
pendingSubmissions.delete(id)
|
||||
submissionForms.delete(id)
|
||||
return submitted
|
||||
} finally {
|
||||
submittingIds.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(draft: FirstLegOrderDraft, customerName: string, id?: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
const order = await saveDraft(draft, customerName, id)
|
||||
return submitSaved(order.id, companyAuditStatus)
|
||||
function hasPendingSubmission(id?: string) { return !!id && (pendingSubmissions.has(id) || submissionForms.has(id)) }
|
||||
|
||||
function isSubmissionRetry(id: string | undefined, draft: FirstLegOrderDraft) {
|
||||
return !!id && hasPendingSubmission(id) && submissionForms.get(id)?.snapshot === JSON.stringify(draft)
|
||||
}
|
||||
|
||||
async function beginNewSubmissionEdit(id: string) {
|
||||
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||
const detail = await getMerchantFirstLegOrder(id)
|
||||
if (detail.order.status !== 'DRAFT') throw new Error('订单已不在草稿状态,不能重新编辑,请刷新订单查看最新状态')
|
||||
if (!Number.isSafeInteger(detail.order.version) || detail.order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
const order = mapOrder(detail.order, warehouses.value, detail)
|
||||
const session = beginDraftEdit(order)
|
||||
pendingSubmissions.delete(id)
|
||||
submissionForms.delete(id)
|
||||
upsertOrder(order)
|
||||
return session
|
||||
}
|
||||
|
||||
async function saveDraftForSubmission(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||
if (id && isSubmissionRetry(id, draft)) return submissionForms.get(id)!.order
|
||||
const snapshot = JSON.stringify(draft)
|
||||
const order = await saveDraft(JSON.parse(snapshot), customerName, id, editSession)
|
||||
submissionForms.set(order.id, { snapshot, order })
|
||||
return order
|
||||
}
|
||||
|
||||
async function loadDraftDetail(id: string) {
|
||||
return loadLegacyDetail(id, getById(id))
|
||||
return loadOrderAggregate(id)
|
||||
}
|
||||
|
||||
return { orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError, activeCount, pendingCount, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, saveDraft, saveDraftBatch, submitSaved, submit }
|
||||
return { orders, orderDetails, total, queueCounts, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved, hasPendingSubmission, isSubmissionRetry, beginNewSubmissionEdit, saveDraftForSubmission }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
const source = readFileSync(new URL('./firstLegOrders.ts', import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const row = (id, mainStatus = 'LOADED') => ({ orderId: String(id), orderNo: `FL-${id}`, mainStatus, orderVersion: 7 })
|
||||
function result(page = 1, size = 10, total = 215) {
|
||||
return {
|
||||
page: { page, size, total, pages: Math.ceil(total / size), records: Array.from({ length: Math.min(size, Math.max(0, total - (page - 1) * size)) }, (_, i) => row((page - 1) * size + i + 1)) },
|
||||
queues: { all: total, fee: 2, customs: 1, draft: 3 }, channelNames: ['AIR', 'SEA'],
|
||||
}
|
||||
}
|
||||
function deferred() { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b }); return { promise, resolve, reject } }
|
||||
function harness(t, read) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = [], details = [], warehouseCalls = []
|
||||
const deps = {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': {},
|
||||
'@/modules/first-leg/api/unifiedOrders': {
|
||||
getMerchantOrderWorkbench: query => { calls.push(structuredClone(query)); return read(query) },
|
||||
getMerchantUnifiedOrder: async id => {
|
||||
details.push(id)
|
||||
return { summary: row(id, 'DRAFT'), order: { order: { id, status: 'DRAFT', version: 7 } }, timeline: [] }
|
||||
},
|
||||
},
|
||||
'@/modules/first-leg/utils/firstLegOrder': { getFirstLegStatusLabel: value => value },
|
||||
'@/modules/first-leg/utils/warehousePagination': { loadAllWarehouseRecords: async type => { warehouseCalls.push(type); return [] } },
|
||||
}
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||
return { store: exports.useFirstLegOrdersStore(), calls, details, warehouseCalls }
|
||||
}
|
||||
|
||||
test('loads beyond 200 with server totals and forwards every filter using one request per page', async t => {
|
||||
const h = harness(t, q => result(q.page, q.size))
|
||||
const query = { page: 21, size: 10, cargoKeyword: 'SKU', channelName: 'SEA', receivingWarehouseId: '42', destinationType: 'FBA', trackingNumber: 'TRACK', mainStatus: 'LOADED', queue: 'all', createdFrom: '2026-10-01T00:00:00', createdTo: '2026-10-03T23:59:59.999' }
|
||||
assert.equal(await h.store.load(query), 10)
|
||||
assert.equal(h.store.orders[0].id, '201')
|
||||
assert.equal(h.store.total, 215)
|
||||
assert.deepEqual(h.calls, [query])
|
||||
assert.deepEqual(h.store.queueCounts, { all: 215, fee: 2, customs: 1, draft: 3 })
|
||||
assert.deepEqual(h.store.queryChannelNames, ['AIR', 'SEA'])
|
||||
await h.store.load({ page: 22, size: 10 })
|
||||
assert.deepEqual(h.store.orders.map(item => item.id), ['211', '212', '213', '214', '215'])
|
||||
assert.equal(h.calls.length, 2)
|
||||
assert.deepEqual(h.warehouseCalls, ['DOMESTIC'])
|
||||
})
|
||||
|
||||
test('late success cannot replace newer rows, counts, channels or loading state', async t => {
|
||||
const a = deferred(), b = deferred()
|
||||
const h = harness(t, q => q.page === 1 ? a.promise : b.promise)
|
||||
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||
b.resolve(result(2)); await second
|
||||
a.resolve(result(1, 10, 999)); await first
|
||||
assert.equal(h.store.orders[0].id, '11'); assert.equal(h.store.total, 215)
|
||||
assert.equal(h.store.queueCounts.all, 215); assert.equal(h.store.loading, false)
|
||||
})
|
||||
|
||||
test('late failure cannot clear the current page and an older completion cannot stop loading a newer page', async t => {
|
||||
const a = deferred(), b = deferred(), c = deferred()
|
||||
const h = harness(t, q => [a, b, c][q.page - 1].promise)
|
||||
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||
a.resolve(result(1)); await first
|
||||
assert.equal(h.store.loading, true); assert.equal(h.store.orders.length, 0)
|
||||
const third = h.store.load({ page: 3 })
|
||||
c.resolve(result(3)); await third
|
||||
b.reject(new Error('old failure')); await second
|
||||
assert.equal(h.store.orders[0].id, '21'); assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
test('current failure clears stale records and totals, never falls back, and retry restores the page', async t => {
|
||||
let fail = false
|
||||
const h = harness(t, () => fail ? Promise.reject(new Error('查询失败')) : result())
|
||||
await h.store.load(); fail = true; await h.store.load()
|
||||
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||
assert.equal(h.store.queueCounts.all, 0); assert.equal(h.store.loadError, '查询失败')
|
||||
assert.equal(h.store.loading, false)
|
||||
fail = false; await h.store.load(); assert.equal(h.store.orders.length, 10)
|
||||
assert.equal(h.calls.length, 3); assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
test('rejects inconsistent metadata, truncated pages and duplicate rows without displaying partial data', async t => {
|
||||
let response
|
||||
const h = harness(t, () => response)
|
||||
const corruptions = [r => { r.page.total = -1 }, r => { r.page.pages = 1 }, r => { r.page.page = 2 }, r => { r.page.records.pop() }, r => { r.page.records[1] = r.page.records[0] }, r => { r.queues.all = 99 }, r => { delete r.queues }, r => { r.channelNames = null }]
|
||||
for (const corrupt of corruptions) {
|
||||
response = result(); corrupt(response); await h.store.load()
|
||||
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||
assert.match(h.store.loadError, /分页数据不完整/); assert.equal(h.store.loading, false)
|
||||
}
|
||||
})
|
||||
|
||||
test('draft and cancelled rows retain authoritative versions; off-page detail cannot inflate list or totals', async t => {
|
||||
const response = result(1, 10, 2)
|
||||
response.page.records = [row(1, 'DRAFT'), row(2, 'CANCELLED')]
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load()
|
||||
assert.deepEqual(h.store.orders.map(item => [item.status, item.version]), [['DRAFT', 7], ['CANCELLED', 7]])
|
||||
await h.store.loadDetail('900')
|
||||
assert.equal(h.store.orders.length, 2); assert.equal(h.store.total, 2)
|
||||
assert.equal(h.store.getById('900').status, 'DRAFT')
|
||||
})
|
||||
|
||||
test('queue total is checked against the selected queue rather than all orders', async t => {
|
||||
const response = result(1, 10, 2)
|
||||
response.queues = { all: 215, fee: 2, customs: 1, draft: 3 }
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load({ queue: 'fee' })
|
||||
assert.equal(h.store.total, 2); assert.equal(h.store.queueCounts.all, 215)
|
||||
assert.equal(h.store.loadError, '')
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
import type {
|
||||
FirstLegOrderStatus,
|
||||
FirstLegTransportMode,
|
||||
@@ -64,6 +65,7 @@ export interface FirstLegOrderTimelineItem {
|
||||
}
|
||||
|
||||
export interface FirstLegOrderBusinessSummary {
|
||||
transportFragments: MerchantTransportFragment[]
|
||||
customerFeeConfirmationRequired: boolean
|
||||
totalPackageCount: number | null
|
||||
actualGrossWeightKg: number | null
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { getMerchantUnifiedOrders } from '../api/unifiedOrders'
|
||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { isCustomsOrderCandidate } from './customsEligibility'
|
||||
|
||||
export interface CustomsDocumentRow {
|
||||
order: { id: string; orderNo: string | null; businessSummary: { inboundCode: string } }
|
||||
detail: MerchantCustomsContainer
|
||||
}
|
||||
|
||||
// Isolated from the shared order store: scan sequential pages, with at most
|
||||
// four document requests in flight. Inconsistent pagination must be visible.
|
||||
export async function readCustomsDocuments() {
|
||||
const records: CustomsDocumentRow[] = []
|
||||
const seen = new Set<string>()
|
||||
let expectedTotal: number | undefined
|
||||
let failedCount = 0
|
||||
const size = 200
|
||||
for (let page = 1; ; page += 1) {
|
||||
const response = await getMerchantUnifiedOrders({ page, size, taxMode: 'TAX_REFUND', loaded: true })
|
||||
const total = Number(response.total)
|
||||
const pages = Number(response.pages)
|
||||
if (!Number.isSafeInteger(total) || total < 0 || Number(response.page) !== page
|
||||
|| Number(response.size) !== size || pages !== Math.ceil(total / size)
|
||||
|| (expectedTotal !== undefined && total !== expectedTotal)
|
||||
|| response.records.length !== Math.min(size, Math.max(0, total - (page - 1) * size))) {
|
||||
throw new Error('订单分页数据不完整或已变化,请重新加载报关资料')
|
||||
}
|
||||
expectedTotal = total
|
||||
for (const row of response.records) {
|
||||
const id = String(row.orderId)
|
||||
if (seen.has(id)) throw new Error('订单分页存在重复记录,请重新加载报关资料')
|
||||
seen.add(id)
|
||||
}
|
||||
const candidates = response.records.filter(row => isCustomsOrderCandidate({ status: row.mainStatus, taxMode: row.taxMode ?? 'BUY_DECLARATION' }))
|
||||
for (let offset = 0; offset < candidates.length; offset += 4) {
|
||||
const results = await Promise.all(candidates.slice(offset, offset + 4).map(async row => {
|
||||
const id = String(row.orderId)
|
||||
try {
|
||||
const detail = await getMerchantCustomsForOrder(id)
|
||||
if (!detail.inbounds.some(item => item.orderId === id && item.taxMode === 'TAX_REFUND')) return null
|
||||
return { order: { id, orderNo: row.orderNo, businessSummary: { inboundCode: row.inboundCode ?? '' } }, detail }
|
||||
} catch (error) {
|
||||
if (!isMerchantCustomsUnavailable(error)) failedCount += 1
|
||||
return null
|
||||
}
|
||||
}))
|
||||
for (const result of results) if (result) records.push(result)
|
||||
}
|
||||
if (page >= pages) break
|
||||
}
|
||||
return { records, failedCount }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./customsEligibility.ts', import.meta.url), 'utf8')
|
||||
const exports = {}
|
||||
new Function('exports', ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText)(exports)
|
||||
|
||||
test('upload queue contains only customer uploads still required, while completed documents stay accessible', () => {
|
||||
const states = [null, {}, { status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED' },
|
||||
{ status: 'READY_TO_START', merchantStatus: 'DOCUMENT_UPLOADED' },
|
||||
{ status: 'DECLARING', merchantStatus: 'DECLARING' }, { status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED' }]
|
||||
for (const detail of states) assert.equal(exports.needsCustomsUpload(detail), false)
|
||||
assert.equal(exports.needsCustomsUpload({ status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }), true)
|
||||
for (const status of ['LOADED', 'DELIVERED', 'COMPLETED']) assert.equal(exports.isCustomsOrderCandidate({ status, taxMode: 'TAX_REFUND' }), true)
|
||||
})
|
||||
|
||||
test('upload status changes refresh server counts while initial detail reads do not reload the list', async () => {
|
||||
const page = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const block = page.slice(page.indexOf('function updateCustomsDetail('), page.indexOf('const detailOrder ='))
|
||||
const js = ts.transpileModule(block, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const states = {}, id = ref('one'), create = ref(false), detail = ref(false)
|
||||
let reloads = 0
|
||||
const update = new Function('customsByOrder', 'customsDialogOrderId', 'isCreatePage', 'isDetailPage', 'loadOrderPage', js + ';return updateCustomsDetail')(states, id, create, detail, async () => reloads++)
|
||||
update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 0)
|
||||
update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 0)
|
||||
update({ merchantStatus: 'DOCUMENT_UPLOADED' }); assert.equal(reloads, 1)
|
||||
assert.equal(states.one.merchantStatus, 'DOCUMENT_UPLOADED')
|
||||
detail.value = true; update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 1)
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { FirstLegOrder } from '../types/firstLegOrder'
|
||||
import type { MerchantCustomsContainer } from '../api/customs'
|
||||
|
||||
export function isCustomsOrderCandidate(order: Pick<FirstLegOrder, 'status' | 'taxMode'>): boolean {
|
||||
return order.taxMode === 'TAX_REFUND'
|
||||
&& (order.status === 'LOADED' || order.status === 'DELIVERED' || order.status === 'COMPLETED')
|
||||
}
|
||||
|
||||
export function needsCustomsUpload(detail: MerchantCustomsContainer | null | undefined): boolean {
|
||||
return detail?.status === 'WAITING_CUSTOMER_DOCUMENTS' && detail.merchantStatus === 'WAITING_UPLOAD'
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
FIRST_LEG_PROGRESS_STAGES,
|
||||
getFirstLegProgressIndex,
|
||||
getFirstLegStatusLabel,
|
||||
getFirstLegPickingStatusLabel,
|
||||
getFirstLegStatusTone,
|
||||
getFirstLegTransportModeLabel,
|
||||
summarizeFirstLegCargo,
|
||||
@@ -59,7 +60,22 @@ function validDraft() {
|
||||
}
|
||||
}
|
||||
|
||||
test('keeps picking states distinct from order completion and hides unknown internal codes', () => {
|
||||
assert.equal(getFirstLegPickingStatusLabel('PENDING'), '待拣货')
|
||||
assert.equal(getFirstLegPickingStatusLabel('IN_PROGRESS'), '拣货中')
|
||||
assert.equal(getFirstLegPickingStatusLabel('COMPLETED'), '拣货完成')
|
||||
assert.equal(getFirstLegPickingStatusLabel('NEW_INTERNAL_STATE'), '未知状态')
|
||||
assert.equal(getFirstLegPickingStatusLabel(null), '待更新')
|
||||
assert.equal(getFirstLegPickingStatusLabel(''), '待更新')
|
||||
})
|
||||
|
||||
test('uses the confirmed status and transport labels', () => {
|
||||
assert.equal(getFirstLegStatusLabel('CANCELLED'), '已取消')
|
||||
assert.equal(getFirstLegStatusLabel('NOT_A_STATUS'), '未知状态')
|
||||
assert.equal(getFirstLegStatusTone('CANCELLED'), 'info')
|
||||
assert.equal(getFirstLegProgressIndex('CANCELLED'), -1)
|
||||
assert.equal(canClientEditFirstLegOrder('CANCELLED'), false)
|
||||
assert.equal(canClientCancelFirstLegOrder('CANCELLED'), false)
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_MEASURE'), '待测量数据')
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_PALLETIZE'), '待组托')
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_SPLIT'), '待分柜')
|
||||
|
||||
@@ -19,6 +19,16 @@ export function getFirstLegStatusLabel(status: string) {
|
||||
return statusLabels.get(canonicalStatus as FirstLegOrderStatus) ?? '未知状态'
|
||||
}
|
||||
|
||||
export function getFirstLegPickingStatusLabel(status: string | null | undefined) {
|
||||
if (!status) return '待更新'
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
PENDING: '待拣货',
|
||||
IN_PROGRESS: '拣货中',
|
||||
COMPLETED: '拣货完成',
|
||||
}
|
||||
return labels[status] ?? '未知状态'
|
||||
}
|
||||
|
||||
export function getFirstLegTransportModeLabel(mode: FirstLegTransportMode | null) {
|
||||
if (!mode) return '运输方式待更新'
|
||||
return transportModeLabels.get(mode) ?? mode
|
||||
@@ -41,11 +51,11 @@ export function canClientCancelFirstLegOrder(status: FirstLegOrderStatus) {
|
||||
}
|
||||
|
||||
export const FIRST_LEG_PROGRESS_STAGES = FIRST_LEG_ORDER_STATUSES.filter(
|
||||
(item): item is (typeof FIRST_LEG_ORDER_STATUSES)[number] & { code: Exclude<FirstLegOrderStatus, 'DRAFT'> } => item.code !== 'DRAFT',
|
||||
(item): item is (typeof FIRST_LEG_ORDER_STATUSES)[number] & { code: Exclude<FirstLegOrderStatus, 'DRAFT' | 'CANCELLED'> } => item.code !== 'DRAFT' && item.code !== 'CANCELLED',
|
||||
)
|
||||
|
||||
export function getFirstLegProgressIndex(status: FirstLegOrderStatus) {
|
||||
if (status === 'DRAFT') return -1
|
||||
if (status === 'DRAFT' || status === 'CANCELLED') return -1
|
||||
return FIRST_LEG_PROGRESS_STAGES.findIndex((item) => item.code === status)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./transportFacts.ts', import.meta.url), 'utf8')
|
||||
const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
runInNewContext(javascript, { exports })
|
||||
const rows = exports.customerTransportRows
|
||||
|
||||
test('split inbound fragments retain separate cabinet facts and actual/estimated times', () => {
|
||||
const result = rows([
|
||||
{ inboundCode: 'NY-1', cabinetNo: 'D1', containerNo: 'TSTU0000001', nodes: [
|
||||
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-05T09:00:00', estimatedAt: null, providerCode: 'MANUAL' },
|
||||
{ standardNode: 'DEPARTED_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-07T08:00:00', providerCode: 'MATSON' },
|
||||
] },
|
||||
{ inboundCode: 'NY-2', cabinetNo: 'D2', containerNo: 'TSTU0000002', nodes: [
|
||||
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-06T10:00:00', estimatedAt: null, providerCode: 'MATSON' },
|
||||
] },
|
||||
])
|
||||
assert.equal(result.length, 3)
|
||||
assert.equal(result[0].nodeLabel, '已进港')
|
||||
assert.equal(result[0].source, '人工记录')
|
||||
assert.equal(result[1].nodeLabel, '预计开航')
|
||||
assert.equal(result[1].actualAt, null)
|
||||
assert.equal(result[1].estimatedAt, '2026-10-07T08:00:00')
|
||||
assert.equal(result[2].cabinetNo, 'D2')
|
||||
assert.equal(result[2].inboundCode, 'NY-2')
|
||||
assert.equal(result[2].actualAt, '2026-10-06T10:00:00')
|
||||
})
|
||||
|
||||
test('empty actual scope creates no invented nodes or database identifier fallback', () => {
|
||||
assert.equal(rows([]).length, 0)
|
||||
assert.equal(rows([{ inboundCode: 'NY-1', nodes: [] }]).length, 0)
|
||||
const [row] = rows([{ id: 'INTERNAL', nodes: [{ standardNode: 'AT_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-05T09:00:00' }] }])
|
||||
assert.equal(row.cabinetNo, '—')
|
||||
assert.equal(row.containerNo, '—')
|
||||
assert.equal(row.inboundCode, '—')
|
||||
assert.equal(row.actualAt, null)
|
||||
})
|
||||
|
||||
test('detail consumes the existing merchant detail API and displays times separately', () => {
|
||||
const store = readFileSync(new URL('../store/firstLegOrders.ts', import.meta.url), 'utf8')
|
||||
const table = readFileSync(new URL('../components/TransportFactsTable.vue', import.meta.url), 'utf8')
|
||||
assert.match(store, /transportFragments: detail\.transportFragments/)
|
||||
assert.match(table, /label="实际时间".*time\(row\.actualAt\)/)
|
||||
assert.match(table, /label="预计时间".*time\(row\.estimatedAt\)/)
|
||||
assert.doesNotMatch(table, /platform\/|fetch\(|actualAt\s*\|\|\s*.*estimatedAt/)
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
DEPARTED_WAREHOUSE: '已离仓', AT_ORIGIN_PORT: '已进港', LOADED_ON_VESSEL: '已装船',
|
||||
DEPARTED_ORIGIN_PORT: '已开航', IN_TRANSIT: '海运途中', ARRIVED_DESTINATION_PORT: '船舶已到目的港',
|
||||
DISCHARGED_FROM_VESSEL: '已卸船', PICKUP_READY: '已清关、可提柜', PICKED_UP: '已提柜', EMPTY_RETURNED: '已还柜',
|
||||
}
|
||||
const estimatedLabels: Readonly<Record<string, string>> = {
|
||||
DEPARTED_WAREHOUSE: '预计离仓', AT_ORIGIN_PORT: '预计进港', LOADED_ON_VESSEL: '预计装船',
|
||||
DEPARTED_ORIGIN_PORT: '预计开航', IN_TRANSIT: '预计海运途中', ARRIVED_DESTINATION_PORT: '预计船舶到目的港',
|
||||
DISCHARGED_FROM_VESSEL: '预计卸船', PICKUP_READY: '预计可提柜', PICKED_UP: '预计提柜', EMPTY_RETURNED: '预计还柜',
|
||||
}
|
||||
|
||||
export function customerTransportRows(fragments: MerchantTransportFragment[]) {
|
||||
return fragments.flatMap((fragment, index) => fragment.nodes.map((node, nodeIndex) => ({
|
||||
key: `${index}-${nodeIndex}`,
|
||||
inboundCode: fragment.inboundCode || '—', cabinetNo: fragment.cabinetNo || '—',
|
||||
containerNo: fragment.containerNo || '—',
|
||||
nodeLabel: (node.actualAt ? labels : estimatedLabels)[node.standardNode] || '运输节点',
|
||||
actualAt: node.actualAt, estimatedAt: node.estimatedAt,
|
||||
location: [node.locationCode, node.locationName].filter(Boolean).join(' · ') || '—',
|
||||
source: node.providerCode === 'MANUAL' ? '人工记录' : node.providerCode === 'FIRSTLEG' ? '平台记录' : node.providerCode ? '承运轨迹' : '—',
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function evaluate(source, dependencies = {}) {
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => {
|
||||
assert.ok(id in dependencies, `Unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports)
|
||||
return exports
|
||||
}
|
||||
const eligibility = evaluate(readFileSync(new URL('../utils/customsEligibility.ts', import.meta.url), 'utf8'))
|
||||
const customsApi = evaluate(readFileSync(new URL('../api/customs.ts', import.meta.url), 'utf8'), {
|
||||
'@/api/http': {}, '@/modules/first-leg/api/firstLeg': {},
|
||||
})
|
||||
const order = (id, status = 'LOADED', taxMode = 'TAX_REFUND') => ({ id, status, taxMode, hasCompletedLoadingPlan: ['LOADED', 'DELIVERED', 'COMPLETED'].includes(status), orderNo: `ORDER-${id}`, businessSummary: { inboundCode: `IN-${id}` } })
|
||||
const detail = id => ({ status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED', inbounds: [{ orderId: id, taxMode: 'TAX_REFUND' }] })
|
||||
function harness(t, orders, getDetail = async id => detail(id)) {
|
||||
const store = { loadError: '', failPage: 0, transformPage: value => value }, calls = [], pageCalls = []
|
||||
const unifiedApi = evaluate(readFileSync(new URL('../api/unifiedOrders.ts', import.meta.url), 'utf8'), {
|
||||
'@/api/http': { apiRequest: async ({ method, url, params: { page, size, taxMode, loaded } }) => {
|
||||
assert.equal(method, 'GET')
|
||||
assert.equal(url, '/merchant/v1/orders')
|
||||
pageCalls.push({ page, size, taxMode, loaded })
|
||||
if (store.loadError || store.failPage === page) throw new Error(store.loadError || '第二页订单查询失败')
|
||||
// Model server filtering BEFORE pagination and COUNT, using the actual
|
||||
// request produced by the production API. Missing taxMode scans all rows.
|
||||
const filtered = orders.filter(row => (!taxMode || row.taxMode === taxMode)
|
||||
&& (loaded === undefined || row.hasCompletedLoadingPlan === loaded))
|
||||
return store.transformPage({ page, size, total: filtered.length, pages: Math.ceil(filtered.length / size),
|
||||
records: filtered.slice((page - 1) * size, page * size).map(row => ({ orderId: row.id, orderNo: row.orderNo, mainStatus: row.status, taxMode: row.taxMode, inboundCode: row.businessSummary.inboundCode })) })
|
||||
} },
|
||||
})
|
||||
const reader = evaluate(readFileSync(new URL('../utils/customsDocumentsReader.ts', import.meta.url), 'utf8'), {
|
||||
'./customsEligibility': eligibility,
|
||||
'../api/unifiedOrders': unifiedApi,
|
||||
'../api/customs': { getMerchantCustomsForOrder: id => { calls.push(id); return getDetail(id) }, isMerchantCustomsUnavailable: error => error?.code === 'A0404' },
|
||||
})
|
||||
const source = readFileSync(new URL('./CustomsDocumentsView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const scope = vue.effectScope()
|
||||
const view = scope.run(() => evaluate(source + '\nexport { load, records, loading, errorMessage, openDetail, selectedOrderId, selectedDetail, dialogOpen, search, queryModel, filteredRecords, pagedRecords, page, pageSize, queryFields, statusLabel, statusType, updateDetail }', {
|
||||
vue: { ...vue, onMounted() {} },
|
||||
'../utils/customsDocumentsReader': reader,
|
||||
'../api/customs': customsApi,
|
||||
}))
|
||||
t.after(() => scope.stop())
|
||||
return { view, store, calls, pageCalls }
|
||||
}
|
||||
|
||||
test('server-filtered request reaches five refund records originally on page 28 without scanning buy orders', async t => {
|
||||
const orders = Array.from({ length: 5528 }, (_, i) => order(`buy-${i}`, 'COMPLETED', 'BUY_DECLARATION'))
|
||||
orders.push(...Array.from({ length: 2613 }, (_, i) => order(`not-loaded-${i}`, 'WAIT_MEASURE')))
|
||||
orders.push(...Array.from({ length: 5 }, (_, i) => order(`historical-${i}`, 'COMPLETED')))
|
||||
const { view, calls, pageCalls } = harness(t, orders)
|
||||
await view.load()
|
||||
assert.deepEqual(calls, Array.from({ length: 5 }, (_, i) => `historical-${i}`))
|
||||
assert.equal(view.records.value.length, 5)
|
||||
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||
view.queryModel.value.inboundCode = 'historical-4'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 1)
|
||||
view.queryModel.value = { orderNo: '', inboundCode: '', containerNo: '', status: '' }; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 5)
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 5)
|
||||
})
|
||||
|
||||
test('second page failure is explicit and retry does not retain an incomplete result', async t => {
|
||||
const orders = Array.from({ length: 201 }, (_, i) => order(String(i)))
|
||||
const { view, store, pageCalls } = harness(t, orders)
|
||||
store.failPage = 2
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '第二页订单查询失败')
|
||||
store.failPage = 0
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 201)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
assert.equal(pageCalls.length, 4)
|
||||
})
|
||||
|
||||
test('display pagination reaches the final refund order without refetching or opening the wrong detail', async t => {
|
||||
const { view, calls, pageCalls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`, 'COMPLETED')))
|
||||
await view.load()
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
view.page.value = 2
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
view.openDetail(view.pagedRecords.value[0])
|
||||
assert.equal(view.selectedOrderId.value, 'refund-20')
|
||||
assert.deepEqual(view.selectedDetail.value.inbounds, [{ orderId: 'refund-20', taxMode: 'TAX_REFUND' }])
|
||||
view.pageSize.value = 10
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 10)
|
||||
view.page.value = 3
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 21)
|
||||
})
|
||||
|
||||
test('searching from a later display page resets pagination and clearing filters restores all documents', async t => {
|
||||
const { view, calls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||
await view.load()
|
||||
view.page.value = 2
|
||||
view.queryModel.value.inboundCode = 'IN-refund-20'
|
||||
view.search()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
view.queryModel.value.inboundCode = 'does-not-exist'
|
||||
view.search()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 0)
|
||||
view.queryModel.value.inboundCode = ''
|
||||
view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 21)
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
assert.equal(calls.length, 21)
|
||||
})
|
||||
|
||||
test('refresh failure on a later page clears stale rows and retry returns to a valid page', async t => {
|
||||
const { view, store } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||
await view.load()
|
||||
view.page.value = 2
|
||||
store.loadError = '资料列表请求失败'
|
||||
await view.load()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '资料列表请求失败')
|
||||
store.loadError = ''
|
||||
await view.load()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
assert.equal(view.filteredRecords.value.length, 21)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('empty pages, duplicate records and changing totals cannot silently truncate history', async t => {
|
||||
for (const change of [
|
||||
response => response.page === 2 ? { ...response, records: [] } : response,
|
||||
response => response.page === 2 ? { ...response, records: [{ ...response.records[0], orderId: '0' }] } : response,
|
||||
response => response.page === 2 ? { ...response, total: 202 } : response,
|
||||
]) {
|
||||
const { view, store, pageCalls } = harness(t, Array.from({ length: 201 }, (_, i) => order(String(i), 'COMPLETED')))
|
||||
store.transformPage = change
|
||||
await view.load()
|
||||
assert.ok(view.errorMessage.value)
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(pageCalls.length, 2)
|
||||
}
|
||||
})
|
||||
|
||||
test('document fetch concurrency never exceeds four and each candidate is requested once', async t => {
|
||||
let active = 0, peak = 0
|
||||
const { view, calls, pageCalls } = harness(t, Array.from({ length: 205 }, (_, i) => order(String(i))), async id => {
|
||||
active += 1; peak = Math.max(peak, active)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
active -= 1
|
||||
return detail(id)
|
||||
})
|
||||
await view.load()
|
||||
assert.equal(peak, 4)
|
||||
assert.equal(new Set(calls).size, 205)
|
||||
assert.equal(calls.length, 205)
|
||||
assert.equal(pageCalls.length, 2)
|
||||
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }, { page: 2, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||
assert.equal(view.records.value.length, 205)
|
||||
})
|
||||
|
||||
test('empty result uses one page request and no document requests', async t => {
|
||||
const { view, calls, pageCalls } = harness(t, [])
|
||||
await view.load()
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 0)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('tax-refund documents remain accessible through delivered and completed orders; buy orders and preloading are excluded', async t => {
|
||||
const stages = ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE', 'WAIT_PALLETIZE', 'WAIT_SPLIT', 'LOADING', 'LOADED', 'DELIVERED', 'COMPLETED']
|
||||
const orders = stages.flatMap(status => [order(status, status), order(`BUY-${status}`, status, 'BUY_DECLARATION')])
|
||||
const { view, calls } = harness(t, orders)
|
||||
await view.load()
|
||||
assert.deepEqual(calls, ['LOADED', 'DELIVERED', 'COMPLETED'])
|
||||
assert.deepEqual(view.records.value.map(row => row.order.id), calls)
|
||||
const completed = view.records.value.find(row => row.order.id === 'COMPLETED')
|
||||
view.openDetail(completed)
|
||||
assert.equal(view.selectedOrderId.value, 'COMPLETED')
|
||||
assert.equal(view.selectedDetail.value.status, 'COMPLETED')
|
||||
assert.equal(view.dialogOpen.value, true)
|
||||
view.queryModel.value.status = 'CUSTOMS_COMPLETED'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 3)
|
||||
assert.equal(calls.length, 3, 'local filtering does not refetch documents')
|
||||
})
|
||||
|
||||
test('only matching server-returned tax-refund ownership is displayed', async t => {
|
||||
const { view } = harness(t, [order('one'), order('two')], async id => id === 'one' ? detail('someone-else') : { inbounds: [{ orderId: id, taxMode: 'BUY_DECLARATION' }] })
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
})
|
||||
|
||||
test('partial failures are visible and retry replaces the result; unavailable customs is not a transport failure', async t => {
|
||||
let fail = true
|
||||
const { view } = harness(t, [order('ok'), order('retry'), order('unavailable')], async id => {
|
||||
if (id === 'unavailable') throw Object.assign(new Error('not associated'), { code: 'A0404' })
|
||||
if (id === 'retry' && fail) throw new Error('network')
|
||||
return detail(id)
|
||||
})
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 1)
|
||||
assert.equal(view.errorMessage.value, '1 票订单的报关资料加载失败,请重新加载')
|
||||
fail = false; await view.load()
|
||||
assert.equal(view.records.value.length, 2)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('order query failure is shown instead of a successful empty result', async t => {
|
||||
const { view, store, calls } = harness(t, [order('old')])
|
||||
await view.load()
|
||||
store.loadError = '订单查询失败'; await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '订单查询失败')
|
||||
assert.equal(calls.length, 1)
|
||||
assert.equal(view.loading.value, false)
|
||||
})
|
||||
|
||||
test('repeated refresh during an active load does not duplicate requests', async t => {
|
||||
let resolve
|
||||
const pending = new Promise(done => { resolve = done })
|
||||
const { view, calls } = harness(t, [order('one')], () => pending)
|
||||
const first = view.load()
|
||||
await Promise.resolve()
|
||||
await view.load()
|
||||
assert.deepEqual(calls, ['one'])
|
||||
resolve(detail('one')); await first
|
||||
assert.equal(view.loading.value, false)
|
||||
})
|
||||
|
||||
test('mixed-container labels and filters use only the current customer status', async t => {
|
||||
const states = [
|
||||
['uploaded', 'WAITING_CUSTOMER_DOCUMENTS', 'DOCUMENT_UPLOADED', 1, '资料已上传', 'success'],
|
||||
['waiting', 'WAITING_CUSTOMER_DOCUMENTS', 'WAITING_UPLOAD', 0, '待上传资料', 'warning'],
|
||||
['declaring', 'DECLARING', 'DECLARING', 1, '报关中', 'primary'],
|
||||
['completed', 'COMPLETED', 'CUSTOMS_COMPLETED', 1, '报关完成', 'success'],
|
||||
]
|
||||
const { view, calls } = harness(t, states.map(([id]) => order(id)), async id => {
|
||||
const [, status, merchantStatus, coveredTaxRefundCount] = states.find(row => row[0] === id)
|
||||
return { ...detail(id), status, merchantStatus, coveredTaxRefundCount, taxRefundCount: 1 }
|
||||
})
|
||||
await view.load()
|
||||
for (const [id, , merchantStatus, , label, tone] of states) {
|
||||
const row = view.records.value.find(item => item.order.id === id)
|
||||
assert.equal(view.statusLabel(row.detail), label)
|
||||
assert.equal(view.statusType(row.detail), tone)
|
||||
view.queryModel.value.status = merchantStatus; view.search()
|
||||
assert.deepEqual(view.filteredRecords.value.map(item => item.order.id), [id])
|
||||
}
|
||||
assert.deepEqual(view.queryFields.find(field => field.key === 'status').options,
|
||||
states.map(([, , value, , label]) => ({ value, label })).sort((a, b) =>
|
||||
['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(a.value)
|
||||
- ['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(b.value)))
|
||||
view.queryModel.value.status = 'WAITING_CUSTOMER_DOCUMENTS'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 0, 'container statuses are not customer filter values')
|
||||
view.queryModel.value.status = ''; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 4)
|
||||
assert.equal(calls.length, 4, 'filtering does not requery or infer status from coverage')
|
||||
})
|
||||
|
||||
test('dialog update refreshes customer status and active filter without inferring from container status', async t => {
|
||||
const { view } = harness(t, [order('one')], async id => ({ ...detail(id), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }))
|
||||
await view.load(); view.openDetail(view.records.value[0])
|
||||
view.queryModel.value.status = 'WAITING_UPLOAD'; view.search()
|
||||
view.updateDetail({ ...detail('one'), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED', coveredTaxRefundCount: 1, taxRefundCount: 1 })
|
||||
assert.equal(view.filteredRecords.value.length, 0)
|
||||
view.queryModel.value.status = 'DOCUMENT_UPLOADED'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 1)
|
||||
assert.equal(view.statusLabel(view.filteredRecords.value[0].detail), '资料已上传')
|
||||
assert.equal(view.statusLabel({ status: 'COMPLETED', coveredTaxRefundCount: 1, taxRefundCount: 1 }), '—')
|
||||
assert.equal(view.statusType({ status: 'COMPLETED' }), 'info')
|
||||
})
|
||||
@@ -4,12 +4,10 @@ import { RefreshCcw } from '@lucide/vue'
|
||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||
import type { TableAction } from '@/components/common/tableActions'
|
||||
import { useFirstLegOrdersStore } from '../public'
|
||||
import { getMerchantCustomsForOrder, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { MERCHANT_CUSTOMS_STATUS_LABELS, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { readCustomsDocuments, type CustomsDocumentRow } from '../utils/customsDocumentsReader'
|
||||
import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue'
|
||||
import type { FirstLegOrder } from '../types/firstLegOrder'
|
||||
|
||||
const store = useFirstLegOrdersStore()
|
||||
const loading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const queryModel = ref<QueryModel>({ orderNo: '', inboundCode: '', containerNo: '', status: '' })
|
||||
@@ -20,23 +18,18 @@ const queryFields: QueryField[] = [
|
||||
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||
{ key: 'inboundCode', label: '入仓码', type: 'input', placeholder: '请输入入仓码' },
|
||||
{ key: 'containerNo', label: '柜号', type: 'input', placeholder: '请输入柜号' },
|
||||
{ key: 'status', label: '状态', type: 'select', placeholder: '全部', options: [
|
||||
{ label: '待上传资料', value: 'WAITING_CUSTOMER_DOCUMENTS' },
|
||||
{ label: '待报关', value: 'READY_TO_START' },
|
||||
{ label: '报关中', value: 'DECLARING' },
|
||||
{ label: '报关完成', value: 'COMPLETED' },
|
||||
] },
|
||||
{ key: 'status', label: '状态', type: 'select', placeholder: '全部', options: Object.entries(MERCHANT_CUSTOMS_STATUS_LABELS).map(([value, label]) => ({ label, value })) },
|
||||
]
|
||||
const columns: DataTableColumn[] = [
|
||||
{ label: '操作', slotName: 'actions', width: 120, fixed: 'left' },
|
||||
{ label: '订单号', slotName: 'orderNo', minWidth: 230 },
|
||||
{ label: '入仓码', slotName: 'inboundCode', minWidth: 190 },
|
||||
{ label: '柜号', slotName: 'containerNo', minWidth: 170 },
|
||||
{ label: '实际箱数', prop: 'detail.actualBoxCount', width: 110, align: 'center' },
|
||||
{ label: '资料覆盖', slotName: 'coverage', width: 110, align: 'center' },
|
||||
{ label: '柜内退税箱数', prop: 'detail.actualBoxCount', width: 110, align: 'center' },
|
||||
{ label: '柜内资料覆盖', slotName: 'coverage', width: 110, align: 'center' },
|
||||
{ label: '状态', slotName: 'status', width: 130 },
|
||||
]
|
||||
const records = ref<Array<{ order: FirstLegOrder; detail: MerchantCustomsContainer }>>([])
|
||||
const records = ref<CustomsDocumentRow[]>([])
|
||||
const dialogOpen = ref(false)
|
||||
const selectedOrderId = ref('')
|
||||
const selectedDetail = ref<MerchantCustomsContainer | null>(null)
|
||||
@@ -48,7 +41,7 @@ const filteredRecords = computed(() => {
|
||||
matches(order.orderNo, 'orderNo')
|
||||
&& matches(order.businessSummary.inboundCode, 'inboundCode')
|
||||
&& (matches(detail.containerNo, 'containerNo') || matches(detail.cabinetNo, 'containerNo'))
|
||||
&& (!query.status || detail.status === query.status),
|
||||
&& (!query.status || detail.merchantStatus === query.status),
|
||||
)
|
||||
})
|
||||
const pagedRecords = computed(() => filteredRecords.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
@@ -67,26 +60,26 @@ function rowActions(row: object): TableAction[] {
|
||||
}
|
||||
|
||||
function statusLabel(detail: MerchantCustomsContainer) {
|
||||
return ({ WAITING_CUSTOMER_DOCUMENTS: '待上传资料', READY_TO_START: '待报关', DECLARING: '报关中', COMPLETED: '报关完成' } as Record<string, string>)[detail.status] ?? detail.status
|
||||
return detail.merchantStatus ? MERCHANT_CUSTOMS_STATUS_LABELS[detail.merchantStatus] ?? '—' : '—'
|
||||
}
|
||||
function statusType(detail: MerchantCustomsContainer) {
|
||||
return detail.status === 'COMPLETED' ? 'success' : detail.status === 'DECLARING' ? 'primary' : 'warning'
|
||||
return detail.merchantStatus === 'CUSTOMS_COMPLETED' || detail.merchantStatus === 'DOCUMENT_UPLOADED'
|
||||
? 'success' : detail.merchantStatus === 'DECLARING' ? 'primary' : detail.merchantStatus === 'WAITING_UPLOAD' ? 'warning' : 'info'
|
||||
}
|
||||
async function load() {
|
||||
if (loading.value) return
|
||||
loading.value = true; errorMessage.value = ''
|
||||
try {
|
||||
await store.load()
|
||||
const candidates = store.orders.filter((order) => order.status === 'LOADED' && order.taxMode === 'TAX_REFUND')
|
||||
const results = await Promise.allSettled(candidates.map(async (order) => ({ order, detail: await getMerchantCustomsForOrder(order.id) })))
|
||||
records.value = results.flatMap((result) => result.status === 'fulfilled' && result.value.detail.inbounds.some((item) => item.orderId === result.value.order.id && item.taxMode === 'TAX_REFUND') ? [result.value] : [])
|
||||
const { records: loadedRecords, failedCount } = await readCustomsDocuments()
|
||||
records.value = loadedRecords
|
||||
if (failedCount) errorMessage.value = `${failedCount} 票订单的报关资料加载失败,请重新加载`
|
||||
} catch (error) {
|
||||
records.value = []
|
||||
errorMessage.value = error instanceof Error ? error.message : '报关资料加载失败,请稍后重试'
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
function openDetail(item: unknown) {
|
||||
const value = item as { order: FirstLegOrder; detail: MerchantCustomsContainer }
|
||||
const value = item as CustomsDocumentRow
|
||||
selectedOrderId.value = value.order.id; selectedDetail.value = value.detail; dialogOpen.value = true
|
||||
}
|
||||
function updateDetail(value: MerchantCustomsContainer) {
|
||||
@@ -101,7 +94,7 @@ onMounted(() => { void load() })
|
||||
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" />
|
||||
<section class="customs-card">
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRecords" :columns="columns" :loading="loading" :total="filteredRecords.length" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="order.id" :empty-text="emptyText">
|
||||
<template #toolbar><strong>资料列表</strong></template>
|
||||
<template #toolbar><strong>资料列表</strong><span>统计为本客户同柜退税货物汇总,资料覆盖按入仓码计。</span></template>
|
||||
<template #toolbar-actions><el-button :loading="loading" @click="load"><RefreshCcw :size="16" />刷新</el-button></template>
|
||||
<template v-if="errorMessage" #error><div class="state-error" role="alert"><span>{{ errorMessage }}</span><el-button :loading="loading" @click="load">重新加载</el-button></div></template>
|
||||
<template #orderNo="{ row }">{{ row.order.orderNo || '—' }}</template>
|
||||
|
||||
@@ -35,17 +35,16 @@ test('opens order creation as a dedicated protected page while keeping draft edi
|
||||
assert.match(editorShellSource, /\.editor-page-footer :deep\(\.editor-actions\) \{[^}]*justify-content: center;/)
|
||||
})
|
||||
|
||||
test('exposes real list, draft, submit, and detail workflow entries without cancellation', () => {
|
||||
test('exposes real list, draft, submit, and detail workflow entries', () => {
|
||||
assert.match(source, /function openCreate\(\)/)
|
||||
assert.match(source, /async function saveDraft\(\)/)
|
||||
assert.match(source, /function submitOrder\(\)/)
|
||||
assert.match(source, /async function openDetail\(order: FirstLegOrder\)/)
|
||||
assert.match(source, /Promise\.allSettled\(\[/)
|
||||
assert.match(source, /const orderPageRequest = isCreatePage\.value \|\| isDetailPage\.value\s*\? store\.loadWarehouseType\('DOMESTIC', true\)\s*:\s*store\.load\(\{ includeDrafts: true \}\)/)
|
||||
assert.match(source, /const orderPageRequest = isCreatePage\.value \|\| isDetailPage\.value\s*\? store\.loadWarehouseType\('DOMESTIC', true\)\s*:\s*loadOrderPage\(\)/)
|
||||
assert.match(source, /Promise\.allSettled\(\[\s*orderPageRequest,\s*companyRequest/)
|
||||
assert.match(source, /tenantStore\.loadCompanyContext\(\)/)
|
||||
assert.match(source, /await store\.loadDetail\(orderId\)/)
|
||||
assert.doesNotMatch(source, /cancelOrder|取消订单/)
|
||||
})
|
||||
|
||||
test('returns edited submissions to the refreshed order list instead of opening detail', () => {
|
||||
@@ -67,7 +66,7 @@ test('copies an order into the dedicated create page without reusing order ident
|
||||
})
|
||||
|
||||
test('keeps create-page support errors scoped to create-page requests', () => {
|
||||
assert.match(source, /if \(!isCreatePage\.value && store\.draftLoadError\)/)
|
||||
assert.doesNotMatch(source, /store\.draftLoadError/)
|
||||
})
|
||||
|
||||
test('blocks order submission before company approval while preserving draft actions', () => {
|
||||
@@ -115,7 +114,7 @@ test('uses the shared query toolbar and data table without metric cards', () =>
|
||||
assert.match(source, /<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" \/>/)
|
||||
assert.match(source, /async function searchOrders\(model: QueryModel\)/)
|
||||
assert.match(source, /await store\.load\(\{/)
|
||||
assert.match(source, /<DataTable v-model:page="tablePage" v-model:page-size="tablePageSize" :data="pagedOrders" :columns="visibleOrderColumns"/)
|
||||
assert.match(source, /<DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns"/)
|
||||
assert.match(source, /\{ key: 'actions', label: '操作', width: 284, fixed: 'left', align: 'left', headerAlign: 'left', slotName: 'actions' \}/)
|
||||
assert.doesNotMatch(source, /order-metrics|订单概览/)
|
||||
})
|
||||
@@ -232,6 +231,9 @@ test('shows one unified progress line and C02 business summaries without detail
|
||||
assert.doesNotMatch(source, /<h3>报关回执<\/h3>/)
|
||||
assert.match(source, /船期摘要/)
|
||||
assert.match(source, /柜次明细/)
|
||||
assert.match(source, /pickingStatusLabel: getFirstLegPickingStatusLabel\(summary\.loadingStatus\)/)
|
||||
assert.match(source, /prop="pickingStatusLabel" label="拣货状态"/)
|
||||
assert.doesNotMatch(source, /label="当前节点"/)
|
||||
assert.match(source, /尚未分配柜次,后续柜次节点将在这里同步。/)
|
||||
assert.doesNotMatch(source, /暂无柜次分配信息/)
|
||||
assert.doesNotMatch(source, /summary\.sealNo \|\|/)
|
||||
@@ -245,9 +247,9 @@ test('uses only fields present on C02 rows before loading full detail', () => {
|
||||
assert.match(source, /displayListValue/)
|
||||
assert.doesNotMatch(source, /key: 'operator'/)
|
||||
assert.doesNotMatch(source, /key: 'transportMode', type: 'select'/)
|
||||
assert.match(source, /store\.draftLoadError/)
|
||||
assert.match(source, /mainStatus: statusValue && statusValue !== 'DRAFT' \? statusValue : undefined/)
|
||||
assert.match(source, /draftOnly: statusValue === 'DRAFT'/)
|
||||
assert.match(source, /:total="store\.total"/)
|
||||
assert.match(source, /mainStatus: text\('status'\)/)
|
||||
assert.match(source, /queue: activeOrderQueue\.value, page: requestedPage, size: tablePageSize\.value/)
|
||||
assert.match(source, /createdFrom: range\[0\] \? `\$\{range\[0\]\}T00:00:00`/)
|
||||
})
|
||||
|
||||
@@ -637,8 +639,8 @@ test('shows billing-weight confirmation only when the backend marks it pending',
|
||||
|
||||
test('submits only selected draft orders in one batch action', () => {
|
||||
assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/)
|
||||
assert.match(source, /Promise\.allSettled\(drafts\.map\(\(order\) => submitMerchantFirstLegOrder/)
|
||||
assert.match(source, /createIdempotencyKey\(`first-leg-batch-submit-\$\{order\.id\}`\)/)
|
||||
assert.match(source, /Promise\.allSettled\(ids\.map\(id => store\.submitSaved/)
|
||||
assert.doesNotMatch(source, /submitMerchantFirstLegOrder/)
|
||||
assert.match(source, /v-if="canSubmitOrder"[\s\S]*批量提交草稿/)
|
||||
})
|
||||
|
||||
@@ -684,8 +686,8 @@ test('opens the server-owned inbound-code association from the order detail', ()
|
||||
assert.doesNotMatch(source, /openInboundCodeAssociation\([^)]*\.id\)/)
|
||||
})
|
||||
|
||||
test('opens customer customs documents only for server-confirmed loaded tax-refund orders', () => {
|
||||
assert.match(source, /order\.status !== 'LOADED'/)
|
||||
test('opens customer customs documents only for server-confirmed tax-refund orders after loading', () => {
|
||||
assert.match(source, /!isCustomsOrderCandidate\(order\)/)
|
||||
assert.match(source, /item\.orderId === order\.id && item\.taxMode === 'TAX_REFUND'/)
|
||||
assert.match(source, /getMerchantCustomsForOrder\(order\.id\)/)
|
||||
assert.match(source, /if \(eligibleCustomsDetail\(order\)\) \{\s*actions\.push\(\{ key: 'customs', label: '报关资料'/)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormItemRule, type FormRules, type UploadRequestOptions } from 'element-plus'
|
||||
import { AlertTriangle, ChevronDown, ChevronUp, Download, FilePlus2, FileText, GripVertical, ImagePlus, MapPin, PackageCheck, Pencil, Plus, RotateCcw, Send, SlidersHorizontal, Trash2, Upload } from '@lucide/vue'
|
||||
@@ -12,9 +12,11 @@ import FirstLegOrderEditorShell from '@/modules/first-leg/components/FirstLegOrd
|
||||
import InboundBillingPanel from '@/modules/first-leg/components/InboundBillingPanel.vue'
|
||||
import InboundCodeAssociationDialog from '@/modules/first-leg/components/InboundCodeAssociationDialog.vue'
|
||||
import OrderProgressPanel from '@/modules/first-leg/components/OrderProgressPanel.vue'
|
||||
import TransportFactsTable from '@/modules/first-leg/components/TransportFactsTable.vue'
|
||||
import CustomsDocumentsDialog from '@/modules/first-leg/components/CustomsDocumentsDialog.vue'
|
||||
import { getMerchantInboundBilling } from '@/modules/first-leg/api/inboundBilling'
|
||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '@/modules/first-leg/api/customs'
|
||||
import { isCustomsOrderCandidate, needsCustomsUpload } from '../utils/customsEligibility'
|
||||
import {
|
||||
estimateMerchantFirstLegPrice,
|
||||
createIdempotencyKey,
|
||||
@@ -28,7 +30,6 @@ import {
|
||||
getMerchantOrderAddresses,
|
||||
getMerchantPricingChannels,
|
||||
importMerchantFirstLegOrders,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantOrderAddress,
|
||||
uploadMerchantProductImage,
|
||||
type CustomerOrderAddress,
|
||||
@@ -40,7 +41,7 @@ import {
|
||||
type MerchantPricingChannel,
|
||||
type InboundCodePolicy,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import { useFirstLegOrdersStore } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useFirstLegOrdersStore, type DraftEditSession } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useTenantAdministrationStore } from '@/modules/tenant-management/public'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
|
||||
@@ -52,6 +53,7 @@ import {
|
||||
canClientEditFirstLegOrder,
|
||||
createEmptyCargoItem,
|
||||
getFirstLegStatusLabel,
|
||||
getFirstLegPickingStatusLabel,
|
||||
getFirstLegStatusTone,
|
||||
getFirstLegTransportModeLabel,
|
||||
summarizeFirstLegCargo,
|
||||
@@ -78,6 +80,53 @@ const companyAuditLoaded = ref(false)
|
||||
const companySubmissionBlocked = computed(() => companyAuditLoaded.value && tenantStore.company.auditStatus !== 'ACTIVE')
|
||||
const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create'))
|
||||
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel'))
|
||||
const cancellingOrderId = ref('')
|
||||
const pendingCancellation = shallowRef<{ id: string; expectedVersion: number; reason: string; businessNo: string; statusLabel: string }>()
|
||||
|
||||
function canOfferCancellation(order: FirstLegOrder) {
|
||||
return canCancelOrder.value && ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE'].includes(order.status)
|
||||
}
|
||||
|
||||
async function cancelOrder(order: FirstLegOrder) {
|
||||
if (!canOfferCancellation(order) || cancellingOrderId.value) return
|
||||
cancellingOrderId.value = order.id
|
||||
try {
|
||||
let command = pendingCancellation.value
|
||||
if (command && command.id !== order.id) {
|
||||
ElMessage.warning(`请先处理订单 ${command.businessNo} 未确认的取消结果`)
|
||||
return
|
||||
}
|
||||
if (!command) {
|
||||
const target = await store.prepareCancellation(order.id)
|
||||
const { value } = await ElMessageBox.prompt(`订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
|
||||
type: 'warning', inputType: 'textarea', confirmButtonText: '确认取消订单', cancelButtonText: '返回',
|
||||
inputValidator: value => Boolean(value?.trim()) && value.trim().length <= 500 || '请填写 1–500 字取消原因',
|
||||
})
|
||||
command = { ...target, reason: value.trim() }
|
||||
pendingCancellation.value = command
|
||||
} else {
|
||||
await ElMessageBox.confirm(`订单:${command.businessNo};原状态:${command.statusLabel};原因:${command.reason}。将查询当前状态并重试原取消请求。`, '重试取消订单', {
|
||||
type: 'warning', confirmButtonText: '重试原请求', cancelButtonText: '返回',
|
||||
})
|
||||
}
|
||||
await store.cancelOrder(command.id, command.expectedVersion, command.reason)
|
||||
pendingCancellation.value = undefined
|
||||
ElMessage.success('订单已取消')
|
||||
await loadOrderPage()
|
||||
if (isDetailPage.value) await router.push({ name: 'first-leg-orders' })
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
if (error instanceof ApiError && (error.code === 'A0409' || error.status === 409)) {
|
||||
pendingCancellation.value = undefined
|
||||
ElMessage.error(`${error.message}。请刷新订单后重新确认取消。`)
|
||||
} else {
|
||||
ElMessage.error(error instanceof Error ? error.message : '取消失败,请重试原请求')
|
||||
}
|
||||
} finally {
|
||||
cancellingOrderId.value = ''
|
||||
}
|
||||
}
|
||||
const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
|
||||
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const availableWarehouses = computed(() => store.warehouses.filter((warehouse) => warehouse.warehouseType === 'DOMESTIC'))
|
||||
@@ -87,9 +136,9 @@ const appliedFilters = ref<QueryModel>({ ...filters.value })
|
||||
const queryFields = computed<QueryField[]>(() => [
|
||||
{ key: 'cargoKeyword', label: '入仓码 / SKU', type: 'input', placeholder: '请输入入仓码或 SKU', props: { 'aria-label': '入仓码或 SKU' } },
|
||||
{ key: 'receivingWarehouseId', label: '收货仓', type: 'select', placeholder: '全部', options: availableWarehouses.value.map((item) => ({ label: item.name, value: item.id })), props: { 'aria-label': '收货仓' } },
|
||||
{ key: 'channelName', label: '渠道名称', type: 'select', placeholder: '全部', options: [...new Set(store.orders.map((item) => item.channelName).filter(Boolean))].map((name) => ({ label: name, value: name })), props: { 'aria-label': '渠道名称' } },
|
||||
{ key: 'channelName', label: '渠道名称', type: 'select', placeholder: '全部', options: store.queryChannelNames.map((name) => ({ label: name, value: name })), props: { 'aria-label': '渠道名称' } },
|
||||
{ key: 'createdRange', label: '创建时间', type: 'daterange', placeholder: '请选择创建时间', props: { 'aria-label': '创建时间' } },
|
||||
{ key: 'status', label: '当前状态', type: 'select', placeholder: '全部', options: FIRST_LEG_ORDER_STATUSES.map((item) => ({ label: item.label, value: item.code })), props: { 'aria-label': '当前状态' } },
|
||||
{ key: 'status', label: '当前状态', type: 'select', placeholder: '全部', options: FIRST_LEG_ORDER_STATUSES.filter(item => item.code !== 'CANCELLED').map((item) => ({ label: item.label, value: item.code })), props: { 'aria-label': '当前状态' } },
|
||||
{ key: 'destinationType', label: '目的仓类型', type: 'select', placeholder: '全部', options: [{ label: 'FBA 仓', value: 'FBA' }, { label: '海外仓', value: 'OVERSEAS' }, { label: '私人地址', value: 'PRIVATE' }], props: { 'aria-label': '目的仓类型' } },
|
||||
{ key: 'trackingNumber', label: '快递单号', type: 'input', placeholder: '请输入快递单号', props: { 'aria-label': '快递单号' } },
|
||||
])
|
||||
@@ -189,6 +238,7 @@ const tablePageSize = ref(10)
|
||||
const downloadingMarks = ref(false)
|
||||
const exportingOrders = ref(false)
|
||||
const batchSubmitting = ref(false)
|
||||
const pendingBatchSubmissionIds = ref<string[]>([])
|
||||
const selectedOrders = ref<FirstLegOrder[]>([])
|
||||
const selectedOrderCount = computed(() => selectedOrders.value.length)
|
||||
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
|
||||
@@ -198,6 +248,7 @@ const activeOrderQueue = ref<OrderQueue>('all')
|
||||
const editorOpen = ref(false)
|
||||
const orderFormRef = ref<FormInstance>()
|
||||
const editingId = ref<string>()
|
||||
const editingSession = shallowRef<DraftEditSession>()
|
||||
const openingEditor = ref(false)
|
||||
const copyingOrderId = ref('')
|
||||
const detailId = ref<string>()
|
||||
@@ -450,61 +501,59 @@ useUnsavedWorkRegistration({
|
||||
dirty: editorDirty,
|
||||
})
|
||||
|
||||
function matchesAppliedFilters(order: FirstLegOrder) {
|
||||
const statusValue = appliedFilters.value.status
|
||||
const createdRangeValue = appliedFilters.value.createdRange
|
||||
const textValue = (key: string) => typeof appliedFilters.value[key] === 'string' ? String(appliedFilters.value[key]).trim().toLowerCase() : ''
|
||||
const receivingWarehouseId = textValue('receivingWarehouseId')
|
||||
const channelName = textValue('channelName')
|
||||
const cargoKeyword = textValue('cargoKeyword')
|
||||
const destinationType = textValue('destinationType')
|
||||
const trackingNumber = textValue('trackingNumber')
|
||||
const status = typeof statusValue === 'string' ? statusValue as FirstLegOrderStatus | '' : ''
|
||||
const createdRange = Array.isArray(createdRangeValue) ? createdRangeValue.filter((value): value is string => typeof value === 'string') : []
|
||||
const matchesWarehouse = !receivingWarehouseId || order.receivingWarehouseId.toLowerCase() === receivingWarehouseId
|
||||
const matchesChannel = !channelName || order.channelName.toLowerCase() === channelName
|
||||
const matchesCargo = !cargoKeyword || [order.businessSummary.inboundCode, ...order.skuNos, ...order.items.map((item) => item.sku)]
|
||||
.filter(Boolean).some((value) => String(value).toLowerCase().includes(cargoKeyword))
|
||||
const matchesDestinationType = !destinationType || order.destinationType.toLowerCase() === destinationType
|
||||
const matchesTrackingNumber = !trackingNumber || order.trackingNumber.toLowerCase().includes(trackingNumber)
|
||||
const matchesStatus = !status || order.status === status
|
||||
const matchesDate = createdRange.length !== 2 || (order.createdAt.slice(0, 10) >= createdRange[0] && order.createdAt.slice(0, 10) <= createdRange[1])
|
||||
return matchesWarehouse && matchesChannel && matchesCargo && matchesDestinationType && matchesTrackingNumber && matchesStatus && matchesDate
|
||||
}
|
||||
const orderQueueCounts = computed(() => store.queueCounts)
|
||||
const pagedOrders = computed(() => store.orders)
|
||||
|
||||
const queryMatchedOrders = computed(() => store.orders.filter(matchesAppliedFilters))
|
||||
const orderQueueCounts = computed(() => ({
|
||||
all: queryMatchedOrders.value.length,
|
||||
fee: queryMatchedOrders.value.filter((order) => order.businessSummary.customerFeeConfirmationRequired).length,
|
||||
customs: queryMatchedOrders.value.filter((order) => Boolean(eligibleCustomsDetail(order))).length,
|
||||
draft: queryMatchedOrders.value.filter((order) => order.status === 'DRAFT').length,
|
||||
}))
|
||||
const filteredOrders = computed(() => queryMatchedOrders.value.filter((order) => {
|
||||
if (activeOrderQueue.value === 'fee') return order.businessSummary.customerFeeConfirmationRequired
|
||||
if (activeOrderQueue.value === 'customs') return Boolean(eligibleCustomsDetail(order))
|
||||
if (activeOrderQueue.value === 'draft') return order.status === 'DRAFT'
|
||||
return true
|
||||
}))
|
||||
const pagedOrders = computed(() => {
|
||||
const start = (tablePage.value - 1) * tablePageSize.value
|
||||
return filteredOrders.value.slice(start, start + tablePageSize.value)
|
||||
})
|
||||
|
||||
function selectOrderQueue(queue: OrderQueue) {
|
||||
async function selectOrderQueue(queue: OrderQueue) {
|
||||
activeOrderQueue.value = queue
|
||||
tablePage.value = 1
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
async function changeOrderPage(page: number) {
|
||||
tablePage.value = page
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
async function changeOrderPageSize(size: number) {
|
||||
tablePageSize.value = size
|
||||
tablePage.value = 1
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
let orderPageRequestVersion = 0
|
||||
async function loadOrderPage() {
|
||||
const requestVersion = ++orderPageRequestVersion
|
||||
const text = (key: string) => typeof appliedFilters.value[key] === 'string' ? String(appliedFilters.value[key]).trim() || undefined : undefined
|
||||
const range = Array.isArray(appliedFilters.value.createdRange) ? appliedFilters.value.createdRange : []
|
||||
const requestedPage = tablePage.value
|
||||
await store.load({
|
||||
cargoKeyword: text('cargoKeyword'), receivingWarehouseId: text('receivingWarehouseId'),
|
||||
channelName: text('channelName'), destinationType: text('destinationType'),
|
||||
trackingNumber: text('trackingNumber'), mainStatus: text('status'),
|
||||
createdFrom: range[0] ? `${range[0]}T00:00:00` : undefined,
|
||||
createdTo: range[1] ? `${range[1]}T23:59:59.999` : undefined,
|
||||
queue: activeOrderQueue.value, page: requestedPage, size: tablePageSize.value,
|
||||
})
|
||||
if (requestVersion !== orderPageRequestVersion) return
|
||||
const lastPage = Math.max(1, Math.ceil(store.total / tablePageSize.value))
|
||||
if (!store.loadError && requestedPage > lastPage) {
|
||||
tablePage.value = lastPage
|
||||
await loadOrderPage()
|
||||
return
|
||||
}
|
||||
selectedOrders.value = []
|
||||
orderTableVersion.value += 1
|
||||
}
|
||||
|
||||
function eligibleCustomsDetail(order: FirstLegOrder) {
|
||||
const value = customsByOrder[order.id]
|
||||
if (order.status !== 'LOADED' || !value?.merchantStatus) return null
|
||||
if (!isCustomsOrderCandidate(order) || !value?.merchantStatus) return null
|
||||
return value.inbounds.some((item) => item.orderId === order.id && item.taxMode === 'TAX_REFUND') ? value : null
|
||||
}
|
||||
|
||||
async function loadCustomsEligibility(order: FirstLegOrder) {
|
||||
if (order.status !== 'LOADED' || customsByOrder[order.id] !== undefined || customsEligibilityPending.has(order.id)) return
|
||||
if (!isCustomsOrderCandidate(order) || customsByOrder[order.id] !== undefined || customsEligibilityPending.has(order.id)) return
|
||||
customsEligibilityPending.add(order.id)
|
||||
try {
|
||||
customsByOrder[order.id] = await getMerchantCustomsForOrder(order.id)
|
||||
@@ -536,7 +585,9 @@ function openInboundCodeAssociation(inboundCode: string) {
|
||||
}
|
||||
|
||||
function updateCustomsDetail(value: MerchantCustomsContainer) {
|
||||
const previous = customsByOrder[customsDialogOrderId.value]
|
||||
if (customsDialogOrderId.value) customsByOrder[customsDialogOrderId.value] = value
|
||||
if (!isCreatePage.value && !isDetailPage.value && previous && previous.merchantStatus !== value.merchantStatus) void loadOrderPage()
|
||||
}
|
||||
|
||||
const detailOrder = computed(() => detailId.value ? store.getById(detailId.value) : undefined)
|
||||
@@ -548,7 +599,7 @@ const pagedDetailCargoItems = computed(() => {
|
||||
})
|
||||
const progressSummaryItems = computed(() => {
|
||||
const order = detailOrder.value
|
||||
if (!order) return []
|
||||
if (!order || order.status === 'CANCELLED') return []
|
||||
const inbound = inboundBilling.value?.inbound.summary
|
||||
const summary = order.businessSummary
|
||||
const formatMetric = (value: number | null | undefined, unit = '') => value == null ? '待更新' : `${value.toLocaleString()}${unit ? ` ${unit}` : ''}`
|
||||
@@ -572,7 +623,7 @@ const progressSummaryItems = computed(() => {
|
||||
const cabinetProgressItems = computed(() => {
|
||||
const summary = detailOrder.value?.businessSummary
|
||||
if (!summary || (!summary.cabinetNo && !summary.containerNo)) return []
|
||||
return [{ cabinetId: summary.cabinetNo || summary.containerNo, cabinetNo: summary.cabinetNo || summary.containerNo, status: summary.loadingStatus || '待更新', vesselName: summary.vesselName, voyageNo: summary.voyageNo, estimatedSailingAt: summary.estimatedSailingAt }]
|
||||
return [{ cabinetId: summary.cabinetNo || summary.containerNo, cabinetNo: summary.cabinetNo || summary.containerNo, pickingStatusLabel: getFirstLegPickingStatusLabel(summary.loadingStatus), vesselName: summary.vesselName, voyageNo: summary.voyageNo, estimatedSailingAt: summary.estimatedSailingAt }]
|
||||
})
|
||||
const selectedWarehouse = computed(() => availableWarehouses.value.find((item) => item.id === form.receivingWarehouseId))
|
||||
const selectedDestinationWarehouse = computed(() => store.warehouses.find((item) => item.id === form.destinationWarehouseId && item.warehouseType === form.destinationType))
|
||||
@@ -582,7 +633,13 @@ const hasActiveFilters = computed(() => {
|
||||
const values = appliedFilters.value
|
||||
return Object.values(values).some((value) => Array.isArray(value) ? value.length > 0 : Boolean(typeof value === 'string' ? value.trim() : value))
|
||||
})
|
||||
const emptyDescription = computed(() => hasActiveFilters.value ? '没有符合筛选条件的订单' : '还没有订单')
|
||||
const emptyDescription = computed(() => {
|
||||
if (hasActiveFilters.value) return '没有符合筛选条件的订单'
|
||||
if (activeOrderQueue.value === 'customs') return '暂无需要上传报关资料的订单'
|
||||
if (activeOrderQueue.value === 'fee') return '暂无需要确认计费重的订单'
|
||||
if (activeOrderQueue.value === 'draft') return '暂无草稿订单'
|
||||
return '还没有订单'
|
||||
})
|
||||
|
||||
async function loadPageData() {
|
||||
supportingDataLoading.value = true
|
||||
@@ -596,7 +653,7 @@ async function loadPageData() {
|
||||
: Promise.resolve()
|
||||
const orderPageRequest = isCreatePage.value || isDetailPage.value
|
||||
? store.loadWarehouseType('DOMESTIC', true)
|
||||
: store.load({ includeDrafts: true })
|
||||
: loadOrderPage()
|
||||
const addressRequest = isCreatePage.value ? loadOrderAddresses() : Promise.resolve()
|
||||
const [ordersResult, companyResult, destinationResult, policyResult, addressResult] = await Promise.allSettled([
|
||||
orderPageRequest,
|
||||
@@ -617,7 +674,6 @@ async function loadPageData() {
|
||||
}
|
||||
if (!isCreatePage.value && ordersResult.status === 'rejected' && !store.loadError) supportingDataErrors.value.push(`订单加载失败:${errorMessage(ordersResult.reason)}`)
|
||||
if (store.warehouseLoadError) supportingDataErrors.value.push(`公共仓库加载失败:${store.warehouseLoadError}`)
|
||||
if (!isCreatePage.value && store.draftLoadError) supportingDataErrors.value.push(`订单草稿加载失败:${store.draftLoadError}`)
|
||||
if (destinationResult.status === 'rejected') supportingDataErrors.value.push(`目的仓加载失败:${errorMessage(destinationResult.reason)}`)
|
||||
if (addressResult.status === 'rejected') supportingDataErrors.value.push(`企业地址簿加载失败:${errorMessage(addressResult.reason)}`)
|
||||
await autofillWarehouseSelections()
|
||||
@@ -633,6 +689,7 @@ async function loadRouteDraft(id: string) {
|
||||
const draft = draftFromOrder(detailedOrder)
|
||||
if (draft.destinationType !== 'PRIVATE') await loadDestinationWarehouses(draft.destinationType)
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (form.receivingWarehouseId) await loadSelectedWarehouse(form.receivingWarehouseId)
|
||||
@@ -1299,6 +1356,9 @@ function getOrderRowActions(row: object): TableAction[] {
|
||||
if (canEditOrder.value && canClientEditFirstLegOrder(order.status)) {
|
||||
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
|
||||
}
|
||||
if (canOfferCancellation(order)) {
|
||||
actions.push({ key: 'cancel', label: pendingCancellation.value?.id === order.id ? '重试取消' : '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) })
|
||||
}
|
||||
if (eligibleCustomsDetail(order)) {
|
||||
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
|
||||
}
|
||||
@@ -1361,6 +1421,7 @@ async function openEdit(order: FirstLegOrder) {
|
||||
}
|
||||
}
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (warehouseAvailable) void loadSelectedWarehouse(detailedOrder.receivingWarehouseId)
|
||||
@@ -1385,7 +1446,8 @@ async function loadDetailPage(orderId: string) {
|
||||
detailError.value = ''
|
||||
try {
|
||||
const detailedOrder = await store.loadDetail(orderId)
|
||||
void loadInboundBilling(detailedOrder)
|
||||
if (detailedOrder.status === 'CANCELLED') resetInboundBillingState()
|
||||
else void loadInboundBilling(detailedOrder)
|
||||
// Load previews from the persisted file IDs after the store has replaced the detail row.
|
||||
await Promise.all((detailOrder.value?.items ?? detailedOrder.items).map(ensureProductImagePreview))
|
||||
} catch (error) {
|
||||
@@ -1466,6 +1528,7 @@ async function retryInboundBilling() {
|
||||
}
|
||||
|
||||
function handleInboundFeeConfirmed() {
|
||||
if (!isCreatePage.value && !isDetailPage.value) void loadOrderPage()
|
||||
if (!feeConfirmationOpen.value) void retryInboundBilling()
|
||||
}
|
||||
|
||||
@@ -1677,14 +1740,14 @@ function handleOrderSelectionChange(rows: FirstLegOrder[]) {
|
||||
}
|
||||
|
||||
async function submitSelectedDraftOrders() {
|
||||
const drafts = selectedDraftOrders.value
|
||||
if (batchSubmitting.value || !drafts.length) return
|
||||
const ids = [...new Set([...pendingBatchSubmissionIds.value, ...selectedDraftOrders.value.map(order => order.id)])]
|
||||
if (batchSubmitting.value || !ids.length) return
|
||||
if (companySubmissionBlocked.value) {
|
||||
ElMessage.warning('企业资料审核通过后才能提交订单')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认提交选中的 ${drafts.length} 条草稿订单吗?`, '批量提交订单', {
|
||||
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?${pendingBatchSubmissionIds.value.length ? '上次结果未确认的订单将使用原提交命令重试。' : ''}`, '批量提交订单', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '确认提交',
|
||||
cancelButtonText: '取消',
|
||||
@@ -1696,10 +1759,8 @@ async function submitSelectedDraftOrders() {
|
||||
|
||||
batchSubmitting.value = true
|
||||
try {
|
||||
const results = await Promise.allSettled(drafts.map((order) => submitMerchantFirstLegOrder(
|
||||
order.id,
|
||||
createIdempotencyKey(`first-leg-batch-submit-${order.id}`),
|
||||
)))
|
||||
const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined)))
|
||||
pendingBatchSubmissionIds.value = ids.filter((id, index) => results[index]?.status === 'rejected' && store.hasPendingSubmission(id))
|
||||
const successCount = results.filter((result) => result.status === 'fulfilled').length
|
||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
||||
await searchOrders(appliedFilters.value)
|
||||
@@ -1893,7 +1954,7 @@ async function submitBatchImport() {
|
||||
batchImportIdempotencyKey.value,
|
||||
)
|
||||
const result = batchImportResult.value.result
|
||||
if (result.succeeded && auth.hasPermission('order:first-leg:list')) await store.load({ includeDrafts: true })
|
||||
if (result.succeeded && auth.hasPermission('order:first-leg:list')) await loadOrderPage()
|
||||
if (result.failed) ElMessage.warning(`导入完成:成功 ${result.succeeded} 条,失败 ${result.failed} 条`)
|
||||
else ElMessage.success(`已成功导入 ${result.succeeded} 条订单草稿`)
|
||||
} catch (error) {
|
||||
@@ -1951,8 +2012,10 @@ async function saveDraft() {
|
||||
if (!await validateEditorForm()) return
|
||||
saving.value = true
|
||||
try {
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
if (!await confirmSubmissionEdit()) return
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = order.id
|
||||
editingSession.value = store.beginDraftEdit(order)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
if (isCreatePage.value) await router.push({ name: 'first-leg-orders' })
|
||||
@@ -1964,6 +2027,20 @@ async function saveDraft() {
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmSubmissionEdit() {
|
||||
if (!editingId.value || !store.hasPendingSubmission(editingId.value)) return true
|
||||
try {
|
||||
await ElMessageBox.confirm('上次提交结果尚未确认。确认重新读取订单并按当前表单重新编辑吗?只有服务端仍为草稿时才能开始新的提交决定。', '重新编辑订单', {
|
||||
type: 'warning', center: true, confirmButtonText: '确认重新编辑', cancelButtonText: '返回',
|
||||
})
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return false
|
||||
throw error
|
||||
}
|
||||
editingSession.value = await store.beginNewSubmissionEdit(editingId.value)
|
||||
return true
|
||||
}
|
||||
|
||||
async function submitOrder() {
|
||||
if (saving.value) return
|
||||
if (companySubmissionBlocked.value) {
|
||||
@@ -1982,13 +2059,16 @@ async function submitOrder() {
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!await validateEditorForm()) return
|
||||
const retry = store.isSubmissionRetry(editingId.value, cloneDraft(form))
|
||||
if (!retry && !await validateEditorForm()) return
|
||||
|
||||
try {
|
||||
saving.value = true
|
||||
if (!retry && !await confirmSubmissionEdit()) return
|
||||
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
|
||||
const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
const savedOrder = await store.saveDraftForSubmission(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = savedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(savedOrder)
|
||||
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
@@ -2008,37 +2088,13 @@ async function submitOrder() {
|
||||
}
|
||||
|
||||
async function searchOrders(model: QueryModel) {
|
||||
const createdRange = model.createdRange
|
||||
appliedFilters.value = {
|
||||
...model,
|
||||
createdRange: Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||
appliedFilters.value = { ...model,
|
||||
createdRange: Array.isArray(model.createdRange) ? model.createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||
}
|
||||
tablePage.value = 1
|
||||
try {
|
||||
const statusValue = typeof model.status === 'string' ? model.status as FirstLegOrderStatus | '' : ''
|
||||
const cargoKeyword = typeof model.cargoKeyword === 'string' ? model.cargoKeyword.trim() : ''
|
||||
const range = Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : []
|
||||
const query = {
|
||||
keyword: undefined,
|
||||
inboundCode: cargoKeyword || undefined,
|
||||
receivingWarehouseId: typeof model.receivingWarehouseId === 'string' && model.receivingWarehouseId ? model.receivingWarehouseId : undefined,
|
||||
mainStatus: statusValue && statusValue !== 'DRAFT' ? statusValue : undefined,
|
||||
draftOnly: statusValue === 'DRAFT',
|
||||
includeDrafts: !statusValue,
|
||||
createdFrom: range[0] ? `${range[0]}T00:00:00` : undefined,
|
||||
createdTo: range[1] ? `${range[1]}T23:59:59` : undefined,
|
||||
}
|
||||
await store.load(query)
|
||||
const cargoMatched = cargoKeyword && store.orders.some((order) => order.status !== 'DRAFT' && orderMatchesCargoKeyword(order, cargoKeyword))
|
||||
if (cargoKeyword && !cargoMatched && statusValue !== 'DRAFT') {
|
||||
await store.load({ ...query, keyword: undefined, inboundCode: undefined, fbaCode: cargoKeyword })
|
||||
}
|
||||
selectedOrders.value = []
|
||||
orderTableVersion.value += 1
|
||||
} catch {
|
||||
// Store keeps the recoverable error state rendered below the query toolbar.
|
||||
}
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -2047,7 +2103,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" />
|
||||
|
||||
<div class="client-card order-table-card">
|
||||
<DataTable v-model:page="tablePage" v-model:page-size="tablePageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="filteredOrders.length" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange">
|
||||
<DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="store.total" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange">
|
||||
<template #toolbar>
|
||||
<nav class="order-queue-tabs" aria-label="订单事项分类">
|
||||
<button type="button" :class="{ active: activeOrderQueue === 'all' }" @click="selectOrderQueue('all')">全部</button>
|
||||
@@ -2086,7 +2142,7 @@ async function searchOrders(model: QueryModel) {
|
||||
</el-popover>
|
||||
<el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button>
|
||||
<el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button>
|
||||
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="selectedDraftOrders.length === 0 || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />批量提交草稿</el-button>
|
||||
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="(selectedDraftOrders.length === 0 && pendingBatchSubmissionIds.length === 0) || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />{{ pendingBatchSubmissionIds.length ? '重试批量提交' : '批量提交草稿' }}</el-button>
|
||||
<el-button v-if="auth.hasPermission('order:first-leg:create')" @click="openBatchImport"><Upload :size="17" />批量导入订单</el-button>
|
||||
<el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button>
|
||||
|
||||
@@ -2349,16 +2405,16 @@ async function searchOrders(model: QueryModel) {
|
||||
<div class="order-detail-heading">
|
||||
<div class="detail-heading-main">
|
||||
<el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button>
|
||||
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div>
|
||||
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'CANCELLED' ? (detailOrder.orderNo || '—') : detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p v-if="detailOrder.status === 'CANCELLED'">订单已取消。</p><p v-else>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div>
|
||||
</div>
|
||||
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button></div>
|
||||
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button><el-button v-if="canOfferCancellation(detailOrder)" type="danger" plain :loading="cancellingOrderId === detailOrder.id" :disabled="!!cancellingOrderId" @click="cancelOrder(detailOrder)">{{ pendingCancellation?.id === detailOrder.id ? '重试取消' : '取消订单' }}</el-button></div>
|
||||
</div>
|
||||
<section class="detail-section">
|
||||
<h3>订单与运输</h3>
|
||||
<dl class="order-detail-grid">
|
||||
<div><dt>入仓码</dt><dd><button v-if="detailOrder.businessSummary.inboundCode" class="inbound-code-link table-code" type="button" @click="openInboundCodeAssociation(detailOrder.businessSummary.inboundCode)">{{ detailOrder.businessSummary.inboundCode }}</button><span v-else>{{ detailOrder.status === 'DRAFT' ? '提交后生成' : '待生成' }}</span></dd></div>
|
||||
<div><dt>入仓码</dt><dd><button v-if="detailOrder.businessSummary.inboundCode" class="inbound-code-link table-code" type="button" @click="openInboundCodeAssociation(detailOrder.businessSummary.inboundCode)">{{ detailOrder.businessSummary.inboundCode }}</button><span v-else>{{ detailOrder.status === 'CANCELLED' ? '—' : detailOrder.status === 'DRAFT' ? '提交后生成' : '待生成' }}</span></dd></div>
|
||||
<div><dt>创建时间</dt><dd>{{ formatDateTime(detailOrder.createdAt) }}</dd></div>
|
||||
<div><dt>运输方式</dt><dd>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }}</dd></div>
|
||||
<div><dt>运输方式</dt><dd>{{ detailOrder.status === 'CANCELLED' && !detailOrder.transportMode ? '—' : getFirstLegTransportModeLabel(detailOrder.transportMode) }}</dd></div>
|
||||
<div><dt>贸易条款</dt><dd>{{ displayValue(detailOrder.tradeTerm) }}</dd></div>
|
||||
<div><dt>发货方式</dt><dd>{{ pickupMethodLabels[detailOrder.pickupMethod] }}</dd></div>
|
||||
<div><dt>预约提货时间</dt><dd>{{ detailOrder.pickupMethod === 'PICKUP' && detailOrder.requestedPickupAt ? formatDateTime(detailOrder.requestedPickupAt) : '-' }}</dd></div>
|
||||
@@ -2383,7 +2439,7 @@ async function searchOrders(model: QueryModel) {
|
||||
</dl>
|
||||
<div v-if="detailOrder.customerRemark" class="customer-remark"><strong>客户备注</strong><p>{{ detailOrder.customerRemark }}</p></div>
|
||||
</section>
|
||||
<section v-if="detailOrder.status !== 'DRAFT'" class="detail-section">
|
||||
<section v-if="detailOrder.status !== 'DRAFT' && detailOrder.status !== 'CANCELLED'" class="detail-section">
|
||||
<h3>关键业务摘要</h3>
|
||||
<dl class="fulfillment-summary">
|
||||
<div v-for="item in progressSummaryItems" :key="item.label"><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>
|
||||
@@ -2397,15 +2453,16 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-table-column prop="cabinetNo" label="柜号 / 柜次" min-width="150"><template #default="{ row }"><span class="table-code">{{ row.cabinetNo || '—' }}</span></template></el-table-column>
|
||||
<el-table-column label="船名 / 航次" min-width="180"><template #default="{ row }">{{ [row.vesselName, row.voyageNo].filter(Boolean).join(' · ') || '待更新' }}</template></el-table-column>
|
||||
<el-table-column label="预计船期" width="170"><template #default="{ row }">{{ row.estimatedSailingAt ? formatDateTime(row.estimatedSailingAt) : '待更新' }}</template></el-table-column>
|
||||
<el-table-column prop="status" label="当前节点" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.status || '待更新' }}</el-tag></template></el-table-column>
|
||||
<el-table-column prop="pickingStatusLabel" label="拣货状态" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.pickingStatusLabel }}</el-tag></template></el-table-column>
|
||||
</el-table>
|
||||
<p v-else class="detail-inline-empty">尚未分配柜次,后续柜次节点将在这里同步。</p>
|
||||
<TransportFactsTable :fragments="detailOrder.businessSummary.transportFragments" />
|
||||
</div>
|
||||
</template>
|
||||
</OrderProgressPanel>
|
||||
<section class="detail-section">
|
||||
<section v-if="detailOrder.status !== 'CANCELLED' || detailOrder.expressCompanyName || detailOrder.trackingNumber" class="detail-section">
|
||||
<h3>履约快递信息</h3>
|
||||
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || '待平台补充' }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || '待平台补充' }}</dd></div></dl>
|
||||
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div></dl>
|
||||
<div v-else class="express-empty"><PackageCheck :size="20" /><div><strong>平台尚未维护快递信息</strong><span>快递公司和快递单号由平台后台维护,客户端仅只读展示。</span></div></div>
|
||||
</section>
|
||||
<section class="detail-section">
|
||||
@@ -2455,6 +2512,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-empty v-else description="暂无货物明细" :image-size="56" />
|
||||
</section>
|
||||
<InboundBillingPanel
|
||||
v-if="detailOrder.status !== 'CANCELLED'"
|
||||
:data="inboundBilling"
|
||||
:loading="inboundBillingLoading"
|
||||
:unavailable="inboundBillingUnavailable"
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { ref } from 'vue'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const names = ['loadOrderPage', 'changeOrderPage', 'changeOrderPageSize', 'selectOrderQueue', 'searchOrders']
|
||||
const functions = ast.statements.filter(n => ts.isFunctionDeclaration(n) && names.includes(n.name?.text)).map(n => n.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule('let orderPageRequestVersion = 0;\n' + functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
function harness() {
|
||||
const calls = []
|
||||
const values = {
|
||||
tablePage: ref(1), tablePageSize: ref(10), activeOrderQueue: ref('all'), appliedFilters: ref({}),
|
||||
selectedOrders: ref(['previous']), orderTableVersion: ref(0),
|
||||
store: { total: 215, loadError: '', load: async q => { calls.push(q) } },
|
||||
}
|
||||
const handlers = new Function(...Object.keys(values), code + ';return {' + names.join(',') + '}')(...Object.values(values))
|
||||
return { ...values, ...handlers, calls }
|
||||
}
|
||||
test('page events request server pages; size, queue and search reset to the first page', async () => {
|
||||
const h = harness()
|
||||
await h.changeOrderPage(21); assert.equal(h.calls.at(-1).page, 21)
|
||||
await h.changeOrderPageSize(50); assert.equal(h.calls.at(-1).page, 1); assert.equal(h.calls.at(-1).size, 50)
|
||||
await h.selectOrderQueue('customs'); assert.equal(h.calls.at(-1).queue, 'customs'); assert.equal(h.tablePage.value, 1)
|
||||
await h.searchOrders({ cargoKeyword: ' SKU ', status: 'DRAFT', createdRange: ['2026-10-01', '2026-10-03'] })
|
||||
assert.equal(h.calls.at(-1).cargoKeyword, 'SKU'); assert.equal(h.calls.at(-1).mainStatus, 'DRAFT')
|
||||
assert.equal(h.calls.at(-1).createdFrom, '2026-10-01T00:00:00')
|
||||
assert.equal(h.calls.at(-1).createdTo, '2026-10-03T23:59:59.999')
|
||||
assert.deepEqual(h.selectedOrders.value, [])
|
||||
})
|
||||
test('deletion on the last page clamps and reloads once; failed reads retain the requested page for retry', async () => {
|
||||
const h = harness(); h.store.total = 200
|
||||
await h.changeOrderPage(22)
|
||||
assert.deepEqual(h.calls.map(q => q.page), [22, 20]); assert.equal(h.tablePage.value, 20)
|
||||
h.store.total = 0; h.store.loadError = 'failed'
|
||||
await h.changeOrderPage(22)
|
||||
assert.equal(h.tablePage.value, 22); assert.equal(h.calls.length, 3)
|
||||
})
|
||||
test('old same-page response cannot clamp a newer query or clear its current selection', async () => {
|
||||
const h = harness(); let release
|
||||
h.store.load = () => new Promise(resolve => { release = resolve })
|
||||
const first = h.loadOrderPage(); const oldRelease = release
|
||||
const second = h.searchOrders({ cargoKeyword: 'new' })
|
||||
h.store.total = 215; release(); await second
|
||||
h.selectedOrders.value = ['new-selection']
|
||||
oldRelease(); await first
|
||||
assert.deepEqual(h.selectedOrders.value, ['new-selection'])
|
||||
assert.equal(h.orderTableVersion.value, 1)
|
||||
})
|
||||
@@ -49,6 +49,7 @@ export interface DeliveryRow {
|
||||
driverName: string | null
|
||||
palletCount: number
|
||||
packageCount: number
|
||||
signedPackages: number | null
|
||||
totalWeightKg: number | null
|
||||
totalVolumeCbm: number | null
|
||||
plannedDeliveryAt: string
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
function harness(t) {
|
||||
const source = readFileSync(new URL('./views/DeliveryOrdersView.vue', import.meta.url), 'utf8')
|
||||
.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const code = ts.transpileModule(source + '\nexport { filters, queryFields, tableColumns, page, pageSize, search, reset, loadOrders, records, total, loading, errorMessage }', {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
|
||||
}).outputText
|
||||
const calls = [], mounted = []
|
||||
const dependencies = {
|
||||
vue: { ...vue, onMounted: callback => mounted.push(callback) }, dayjs,
|
||||
'vue-router': { useRouter: () => ({ push() {} }) },
|
||||
'@/modules/auth/public': { useAuthStore: () => ({ hasPermission: () => true }) },
|
||||
'../api/deliveryOrders': { listDeliveryOrders: query => new Promise((resolve, reject) => calls.push({ query, resolve, reject })) },
|
||||
}
|
||||
const scope = vue.effectScope(), view = {}
|
||||
scope.run(() => new Function('require', 'exports', code)(id => {
|
||||
assert.ok(id in dependencies, id)
|
||||
return dependencies[id]
|
||||
}, view))
|
||||
t.after(() => scope.stop())
|
||||
return { view, calls, mount: () => mounted.forEach(fn => fn()) }
|
||||
}
|
||||
const result = name => ({ records: [{ deliveryNo: name }], total: 1 })
|
||||
|
||||
test('formal delivery filters submit exact values and format each known method in Chinese', async t => {
|
||||
const { view, calls } = harness(t)
|
||||
const expected = { FBA_PICKUP: 'FBA 自提', CUSTOMER_PICKUP: '客户自提', TRUCK_PALLET: '卡派打托', TRUCK_FLOOR: '卡派地板', EXPRESS: '快递', OUTSOURCED: '外配', DEDICATED_TRUCK: '专车直送', LTL: '零担派送', TRUCK: '卡车派送' }
|
||||
const options = view.queryFields.find(f => f.key === 'deliveryMethod').options
|
||||
assert.deepEqual(Object.fromEntries(options.map(o => [o.value, o.label])), expected)
|
||||
const column = view.tableColumns.find(c => c.prop === 'deliveryMethod')
|
||||
for (const [value, label] of Object.entries(expected)) {
|
||||
view.filters.deliveryMethod = value
|
||||
const pending = view.loadOrders()
|
||||
assert.equal(calls.at(-1).query.deliveryMethod, value)
|
||||
calls.at(-1).resolve(result(value)); await pending
|
||||
assert.equal(column.formatter({}, {}, value), label)
|
||||
}
|
||||
assert.equal(column.formatter({}, {}, null), '—')
|
||||
})
|
||||
|
||||
test('newest result survives older success and older failure', async t => {
|
||||
for (const oldFailure of [false, true]) {
|
||||
const { view, calls } = harness(t)
|
||||
view.filters.documentNo = 'old'; const old = view.loadOrders()
|
||||
view.filters.documentNo = 'new'; const current = view.loadOrders()
|
||||
calls[1].resolve(result('new')); await current
|
||||
if (oldFailure) calls[0].reject(new Error('old failed'))
|
||||
else calls[0].resolve(result('old'))
|
||||
await old
|
||||
assert.equal(view.records.value[0].deliveryNo, 'new')
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
assert.equal(view.total.value, 1)
|
||||
assert.equal(calls.length, 2)
|
||||
}
|
||||
})
|
||||
|
||||
test('older completion cannot clear current loading; current failure can be retried', async t => {
|
||||
const { view, calls } = harness(t)
|
||||
const old = view.loadOrders(), current = view.loadOrders()
|
||||
calls[0].resolve(result('old')); await old
|
||||
assert.equal(view.loading.value, true)
|
||||
assert.equal(view.records.value.length, 0)
|
||||
calls[1].reject(new Error('current failed')); await current
|
||||
assert.equal(view.loading.value, false)
|
||||
assert.equal(view.errorMessage.value, 'current failed')
|
||||
const retry = view.loadOrders(); calls[2].resolve(result('retry')); await retry
|
||||
assert.equal(view.records.value[0].deliveryNo, 'retry')
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('mount, search from later page, page-size change and reset each issue one request', async t => {
|
||||
const { view, calls, mount } = harness(t)
|
||||
mount(); await vue.nextTick(); assert.equal(calls.length, 1)
|
||||
view.page.value = 3; await vue.nextTick(); assert.equal(calls.length, 2)
|
||||
view.search(); await vue.nextTick(); assert.equal(calls.length, 3)
|
||||
assert.equal(calls[2].query.page, 1)
|
||||
view.page.value = 4; await vue.nextTick(); assert.equal(calls.length, 4)
|
||||
view.pageSize.value = 50; await vue.nextTick(); assert.equal(calls.length, 5)
|
||||
assert.equal(calls[4].query.page, 1); assert.equal(calls[4].query.size, 50)
|
||||
view.reset(); await vue.nextTick(); assert.equal(calls.length, 6)
|
||||
calls.forEach(call => call.resolve(result('resolved')))
|
||||
})
|
||||
@@ -18,6 +18,18 @@ async function importTypeScriptModule(source) {
|
||||
return import(`data:text/javascript;base64,${Buffer.from(compiled).toString('base64')}`)
|
||||
}
|
||||
|
||||
for (const signedPackages of [null, 0, 3]) test(`preserves actual signed quantity ${signedPackages} in merchant list and detail`, async () => {
|
||||
const api = await importTypeScriptModule(apiSource.replace(
|
||||
"import { apiBlobRequest, apiRequest } from '@/api/http'",
|
||||
`const apiBlobRequest = async () => new Blob([])
|
||||
const order = { deliveryNo: 'DL-1', packageCount: 9, signedPackages: ${JSON.stringify(signedPackages)} }
|
||||
const apiRequest = async (config) => config.url.endsWith('/DL-1')
|
||||
? { order, skus: [], fees: [] } : { records: [order], page: 1, size: 20, total: 1, pages: 1 }`,
|
||||
))
|
||||
assert.equal((await api.listDeliveryOrders({ page: 1, size: 20 })).records[0].signedPackages, signedPackages)
|
||||
assert.equal((await api.getDeliveryOrder('DL-1')).signedPackages, signedPackages)
|
||||
})
|
||||
|
||||
test('uses only authenticated merchant delivery endpoints without customer scope or mock fallback', () => {
|
||||
assert.match(apiSource, /method: 'GET'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/)
|
||||
assert.match(apiSource, /delivery-orders\/\$\{encodeURIComponent\(deliveryNo\)\}/)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { readFile, stat } from 'node:fs/promises'
|
||||
import { basename } from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
// Local-only verification. Expectations must come from this run's uploaded
|
||||
// fixture bytes, not from the downloaded file or a previous Downloads entry.
|
||||
export async function verifyReceiptFile(path, expected, startedAt) {
|
||||
const metadata = await stat(path)
|
||||
const bytes = await readFile(path)
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
||||
const checks = {
|
||||
currentRun: metadata.mtimeMs >= startedAt,
|
||||
fileName: basename(path) === expected.fileName,
|
||||
size: bytes.length === expected.sizeBytes,
|
||||
content: sha256 === expected.sha256,
|
||||
}
|
||||
return { passed: Object.values(checks).every(Boolean), checks, sizeBytes: bytes.length, sha256, savedFileName: basename(path) }
|
||||
}
|
||||
|
||||
// Run only inside the approved computer-use session, passing its existing Tab.
|
||||
// This module never connects to a browser, logs in, fetches HTTP or changes data.
|
||||
// Root supplies fresh fixture metadata and logs in through the normal page UI.
|
||||
// Example in cua_repl after reading the skill and selecting the customer tab:
|
||||
// const { acceptReceiptDownload } = await import('<absolute path to this module>')
|
||||
// const result = await acceptReceiptDownload(tab, expected)
|
||||
// expected = { deliveryNo, fileName, sizeBytes, sha256 } from the source fixture.
|
||||
// Save result with the current run ID/version; timeout is BLOCKED, not PASS.
|
||||
export async function acceptReceiptDownload(tab, expected) {
|
||||
if (!expected.deliveryNo || !expected.fileName || !Number.isSafeInteger(expected.sizeBytes)
|
||||
|| expected.sizeBytes < 0 || !/^[a-f0-9]{64}$/.test(expected.sha256)) {
|
||||
throw new Error('Fresh fixture delivery number, filename, byte length and SHA-256 are required')
|
||||
}
|
||||
const snapshot = await tab.playwright.domSnapshot()
|
||||
const heading = tab.playwright.getByRole('heading', { name: expected.deliveryNo, exact: true })
|
||||
if (!(await heading.isVisible())) throw new Error('Open the exact fixture delivery detail first')
|
||||
const row = tab.playwright.getByRole('row').filter({ hasText: expected.fileName })
|
||||
if (await row.count() !== 1) throw new Error('Expected exactly one receipt row')
|
||||
const startedAt = Date.now()
|
||||
const [download, click] = await Promise.allSettled([
|
||||
tab.playwright.waitForEvent('download', { timeoutMs: 20000 }).then(d => d.path({ timeoutMs: 10000 })),
|
||||
row.getByRole('button', { name: '下载', exact: true }).click({ timeoutMs: 15000 }),
|
||||
])
|
||||
const base = { deliveryNo: expected.deliveryNo, fileName: expected.fileName, startedAt,
|
||||
clickCompleted: click.status === 'fulfilled', receiptVisible: snapshot.includes(expected.fileName) }
|
||||
if (click.status !== 'fulfilled' || download.status !== 'fulfilled' || !download.value) {
|
||||
return { ...base, status: 'BLOCKED', reason: 'No completed browser save with a current local path', savedFileVerified: false }
|
||||
}
|
||||
const verification = await verifyReceiptFile(download.value, expected, startedAt)
|
||||
return { ...base, status: verification.passed ? 'PASS' : 'FAIL', verification }
|
||||
}
|
||||
|
||||
// Real isolation companion procedure (root-owned environment run):
|
||||
// 1. A logs in, opens fresh A delivery, runs acceptReceiptDownload; retain result.
|
||||
// 2. Log out via UI, log in as unrelated B, open the same A detail URL.
|
||||
// 3. Require denied detail/no receipt filename/no download control and record DOM.
|
||||
// 4. Root's HTTP suite must independently verify B->A binary endpoint rejection.
|
||||
// A hidden button alone is not server isolation. Do not insert tokens into DOM,
|
||||
// use raw CDP, reuse an old file, or replace missing UI save with HTTP success.
|
||||
// If tool paths have opaque basenames, filename check remains FAIL/unproven;
|
||||
// obtain browser download record plus original saved file through the user.
|
||||
@@ -0,0 +1,190 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import ts from 'typescript'
|
||||
import axios from 'axios'
|
||||
import { ref, computed } from 'vue'
|
||||
import { mkdtemp, writeFile, utimes, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { verifyReceiptFile, acceptReceiptDownload } from './receiptBrowserAcceptance.mjs'
|
||||
|
||||
// Execute production HTTP, API and SFC setup code. Only transport, browser saving
|
||||
// and UI feedback are replaced; this is not a browser/server isolation test.
|
||||
function compile(path, dependencies, globals = {}) {
|
||||
let source = readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||
if (path.endsWith('.vue')) {
|
||||
source = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
+ '\nexport { downloadReceipt, loadReceipts, receiptFiles, downloadingFileId, receiptsError, feeColumns }'
|
||||
}
|
||||
source = source.replace('import.meta.env.VITE_API_BASE_URL', "'/api'")
|
||||
const code = ts.transpileModule(source, { compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true,
|
||||
} }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', ...Object.keys(globals), code)((id) => {
|
||||
assert.ok(id in dependencies, `Unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports, ...Object.values(globals))
|
||||
return exports
|
||||
}
|
||||
|
||||
const payload = Buffer.from([0, 255, 13, 10, 128, 1, 2, 3])
|
||||
const file = { fileId: 'file/1', fileName: '签收证明 #1.bin', sizeBytes: payload.length }
|
||||
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex')
|
||||
|
||||
test('delivery detail fee column renders formal fee names without changing unknown values', () => {
|
||||
const { component } = harness()
|
||||
const column = component.feeColumns.find(item => item.prop === 'feeType')
|
||||
for (const [input, expected] of [
|
||||
['DELIVERY_FEE', '派送费'], ['LOADING_FEE', '装车费'], ['APPOINTMENT_FEE', '预约费'],
|
||||
['', '—'], [null, '—'], [undefined, '—'], ['OTHER_FEE', 'OTHER_FEE'], ['特殊服务费', '特殊服务费'],
|
||||
]) assert.equal(column.formatter({}, {}, input), expected)
|
||||
})
|
||||
|
||||
function harness({ token = 'customer-A', rejectDownload, rejectList, pending, clickError } = {}) {
|
||||
const requests = [], saved = [], errors = [], revoked = [], urls = new Map()
|
||||
const http = compile('../../api/http.ts', {
|
||||
axios: { ...axios, create: config => axios.create({ ...config, adapter: async config => {
|
||||
requests.push({ url: config.url, authorization: config.headers.get('Authorization'), responseType: config.responseType })
|
||||
const binary = config.url.endsWith('/download')
|
||||
const status = binary ? rejectDownload : rejectList
|
||||
if (status) {
|
||||
const response = { status, data: new Blob([JSON.stringify({ code: String(status), message: '无权访问签收文件' })], { type: 'application/json' }), headers: {}, config }
|
||||
throw new axios.AxiosError('denied', 'ERR_BAD_REQUEST', config, null, response)
|
||||
}
|
||||
if (binary && pending) await pending
|
||||
return { status: 200, headers: {}, config, data: binary
|
||||
? new Blob([payload], { type: 'application/octet-stream' })
|
||||
: { code: '200', message: '成功', data: { deliveryNo: 'DL/A', files: [file] } } }
|
||||
} }) },
|
||||
'@chongchong/shared': { parseApiJsonResponse: value => value },
|
||||
'@/api/session': { getAccessToken: () => token, accessTokenIdentity: value => value, getRefreshToken: () => '', persistTokenPair() {}, clearSessionTokens() {} },
|
||||
'@/api/errorDetails': compile('../../api/errorDetails.ts', {}),
|
||||
'@/api/types': compile('../../api/types.ts', {}),
|
||||
'@/api/crossTabRefresh': compile('../../api/crossTabRefresh.ts', {}),
|
||||
})
|
||||
const api = compile('./api/deliveryOrders.ts', { '@/api/http': http })
|
||||
const component = compile('./views/DeliveryOrderDetailView.vue', {
|
||||
vue: { ref, computed, onMounted() {} },
|
||||
'vue-router': { useRouter: () => ({ push() {} }) },
|
||||
'element-plus': { ElMessage: { error: message => errors.push(message) } },
|
||||
dayjs: () => {}, '../api/deliveryOrders': api,
|
||||
}, {
|
||||
defineProps: () => ({ deliveryNo: 'DL/A' }),
|
||||
URL: { createObjectURL(blob) { const url = `blob:${urls.size}`; urls.set(url, blob); return url }, revokeObjectURL(url) { revoked.push(url); urls.delete(url) } },
|
||||
document: { createElement(tag) {
|
||||
assert.equal(tag, 'a')
|
||||
return { href: '', download: '', click() {
|
||||
if (clickError) throw clickError
|
||||
assert.ok(urls.has(this.href), 'blob must still exist when saving is requested')
|
||||
saved.push({ fileName: this.download, blob: urls.get(this.href) })
|
||||
} }
|
||||
} },
|
||||
})
|
||||
return { component, requests, saved, errors, revoked, urls }
|
||||
}
|
||||
|
||||
test('C63 real handler passes exact binary bytes and Unicode filename to browser save', async () => {
|
||||
const h = harness()
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.saved.length, 1)
|
||||
assert.equal(h.saved[0].fileName, file.fileName)
|
||||
const bytes = Buffer.from(await h.saved[0].blob.arrayBuffer())
|
||||
assert.deepEqual(bytes, payload)
|
||||
assert.equal(sha256(bytes), sha256(payload))
|
||||
const changed = Buffer.from(payload); changed[0] ^= 1
|
||||
assert.equal(changed.length, bytes.length)
|
||||
assert.notEqual(sha256(bytes), sha256(changed), 'same size is not content evidence')
|
||||
assert.deepEqual(h.requests.map(r => r.url), ['/merchant/v1/last-leg/delivery-orders/DL%2FA/documents/receipt', '/merchant/v1/last-leg/delivery-orders/DL%2FA/documents/receipt/files/file%2F1/download'])
|
||||
assert.equal(h.requests[1].responseType, 'blob')
|
||||
assert.equal(h.requests[1].authorization, 'Bearer customer-A')
|
||||
assert.equal(h.component.downloadingFileId.value, '')
|
||||
assert.equal(h.revoked.length, 1)
|
||||
assert.equal(h.urls.size, 0)
|
||||
assert.deepEqual(h.errors, [])
|
||||
})
|
||||
|
||||
for (const status of [403, 404, 500]) {
|
||||
test(`C63 HTTP ${status} never saves an error body and releases busy state`, async () => {
|
||||
const h = harness({ rejectDownload: status })
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.saved.length, 0)
|
||||
assert.equal(h.urls.size, 0)
|
||||
assert.equal(h.revoked.length, 0)
|
||||
assert.equal(h.errors.length, 1)
|
||||
assert.equal(h.component.downloadingFileId.value, '')
|
||||
})
|
||||
}
|
||||
|
||||
test('C63 unknown file and duplicate in-flight clicks do not issue another download', async () => {
|
||||
let finish
|
||||
const h = harness({ pending: new Promise(resolve => { finish = resolve }) })
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt('not-in-receipt-list')
|
||||
assert.equal(h.requests.length, 1)
|
||||
const first = h.component.downloadReceipt(file.fileId)
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
finish()
|
||||
await first
|
||||
assert.equal(h.requests.length, 2)
|
||||
assert.equal(h.saved.length, 1)
|
||||
})
|
||||
|
||||
test('C63 denied customer list clears prior file choices; denied download uses current customer session', async () => {
|
||||
const h = harness({ token: 'customer-B', rejectList: 403, rejectDownload: 403 })
|
||||
h.component.receiptFiles.value = [file]
|
||||
await h.component.loadReceipts()
|
||||
assert.equal(h.component.receiptFiles.value.length, 0)
|
||||
assert.ok(h.component.receiptsError.value)
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.requests.length, 1)
|
||||
// Simulate a stale visible choice: the real API must still use B's session.
|
||||
h.component.receiptFiles.value = [file]
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.ok(h.requests.every(r => r.authorization === 'Bearer customer-B'))
|
||||
assert.equal(h.saved.length, 0)
|
||||
assert.equal(h.errors.length, 1)
|
||||
})
|
||||
|
||||
test('C63 browser save exception releases object URL and permits retry', async () => {
|
||||
const h = harness({ clickError: new Error('save failed') })
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.saved.length, 0)
|
||||
assert.deepEqual(h.errors, ['save failed'])
|
||||
assert.equal(h.revoked.length, 1)
|
||||
assert.equal(h.component.downloadingFileId.value, '')
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.requests.length, 3)
|
||||
assert.equal(h.errors.length, 2)
|
||||
})
|
||||
|
||||
test('C63 disk evidence rejects same-size corruption, stale files and wrong filenames', async t => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'c63-download-'))
|
||||
t.after(() => rm(directory, { recursive: true, force: true }))
|
||||
const path = join(directory, file.fileName)
|
||||
const expected = { fileName: file.fileName, sizeBytes: payload.length, sha256: sha256(payload) }
|
||||
const startedAt = Date.now() - 1000
|
||||
await writeFile(path, payload)
|
||||
assert.equal((await verifyReceiptFile(path, expected, startedAt)).passed, true)
|
||||
const changed = Buffer.from(payload); changed[0] ^= 1
|
||||
await writeFile(path, changed)
|
||||
const corrupted = await verifyReceiptFile(path, expected, startedAt)
|
||||
assert.equal(corrupted.checks.size, true)
|
||||
assert.equal(corrupted.checks.content, false)
|
||||
assert.equal(corrupted.passed, false)
|
||||
await writeFile(path, payload)
|
||||
await utimes(path, new Date(0), new Date(0))
|
||||
assert.equal((await verifyReceiptFile(path, expected, startedAt)).checks.currentRun, false)
|
||||
const wrongPath = join(directory, 'wrong-name.bin')
|
||||
await writeFile(wrongPath, payload)
|
||||
assert.equal((await verifyReceiptFile(wrongPath, expected, startedAt)).checks.fileName, false)
|
||||
})
|
||||
|
||||
test('C63 browser evidence refuses missing fixture hash before interacting', async () => {
|
||||
await assert.rejects(acceptReceiptDownload({}, { deliveryNo: 'DL/A', fileName: file.fileName }), /SHA-256/)
|
||||
})
|
||||
@@ -36,7 +36,7 @@ const itemColumns: DataTableColumn[] = [
|
||||
{ prop: 'volumeCbm', label: '体积(m³)', width: 120, align: 'right', headerAlign: 'right', formatter: tableValueFormatter },
|
||||
]
|
||||
const feeColumns: DataTableColumn[] = [
|
||||
{ prop: 'feeType', label: '费用类型', minWidth: 180, formatter: tableValueFormatter }, { prop: 'currency', label: '币种', width: 100, formatter: tableValueFormatter },
|
||||
{ prop: 'feeType', label: '费用类型', minWidth: 180, formatter: (_row: object, _column: unknown, value: string | null | undefined) => formatDeliveryFeeType(value) }, { prop: 'currency', label: '币种', width: 100, formatter: tableValueFormatter },
|
||||
{ prop: 'amount', label: '金额', width: 140, align: 'right', headerAlign: 'right', formatter: tableValueFormatter }, { prop: 'remark', label: '备注', minWidth: 240, formatter: tableValueFormatter },
|
||||
]
|
||||
|
||||
@@ -50,6 +50,11 @@ function display(value: string | number | null | undefined) {
|
||||
return value === null || value === undefined || value === '' ? '—' : String(value)
|
||||
}
|
||||
|
||||
function formatDeliveryFeeType(value: string | null | undefined) {
|
||||
const labels: Record<string, string> = { DELIVERY_FEE: '派送费', LOADING_FEE: '装车费', APPOINTMENT_FEE: '预约费' }
|
||||
return value ? labels[value] ?? value : '—'
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined) {
|
||||
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '—'
|
||||
}
|
||||
|
||||
@@ -19,6 +19,20 @@ const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const filters = reactive({ documentNo: '', dispatchNo: '', waybillNo: '', status: '', deliveryMethod: '', plannedRange: [] as string[] })
|
||||
const canCreate = computed(() => auth.hasPermission('merchant:warehouse:delivery:create'))
|
||||
let requestSequence = 0
|
||||
|
||||
const deliveryMethodOptions = [
|
||||
{ value: 'FBA_PICKUP', label: 'FBA 自提' },
|
||||
{ value: 'CUSTOMER_PICKUP', label: '客户自提' },
|
||||
{ value: 'TRUCK_PALLET', label: '卡派打托' },
|
||||
{ value: 'TRUCK_FLOOR', label: '卡派地板' },
|
||||
{ value: 'EXPRESS', label: '快递' },
|
||||
{ value: 'OUTSOURCED', label: '外配' },
|
||||
{ value: 'DEDICATED_TRUCK', label: '专车直送' },
|
||||
{ value: 'LTL', label: '零担派送' },
|
||||
{ value: 'TRUCK', label: '卡车派送' },
|
||||
]
|
||||
const deliveryMethodLabels: Record<string, string> = Object.fromEntries(deliveryMethodOptions.map(item => [item.value, item.label]))
|
||||
|
||||
const statusOptions = [
|
||||
{ value: 'WAIT_DELIVERY', label: '待派送' },
|
||||
@@ -37,14 +51,14 @@ const queryFields: QueryField[] = [
|
||||
{ key: 'dispatchNo', label: '排车单号', type: 'input', placeholder: '请输入排车单号' },
|
||||
{ key: 'waybillNo', label: '运单号', type: 'input', placeholder: '请输入运单号' },
|
||||
{ key: 'status', label: '派送状态', type: 'select', options: statusOptions },
|
||||
{ key: 'deliveryMethod', label: '派送方式', type: 'select', options: [{ label: '卡车派送', value: 'TRUCK' }, { label: '快递派送', value: 'COURIER' }, { label: '客户自提', value: 'SELF_PICKUP' }] },
|
||||
{ key: 'deliveryMethod', label: '派送方式', type: 'select', options: deliveryMethodOptions },
|
||||
{ key: 'plannedRange', label: '计划时间', type: 'daterange' },
|
||||
]
|
||||
const tableColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', slotName: 'actions', width: 90, fixed: 'left' }, { prop: 'deliveryNo', label: '派送单号', minWidth: 180 },
|
||||
{ prop: 'dispatchNo', label: '排车单号', minWidth: 170 }, { prop: 'outboundNo', label: '出库单号', minWidth: 170 },
|
||||
{ key: 'status', label: '状态', slotName: 'status', width: 110 }, { prop: 'overseasWarehouseName', label: '海外仓', minWidth: 160 },
|
||||
{ prop: 'deliveryMethod', label: '派送方式', width: 120 }, { prop: 'waybillNo', label: '运单号', minWidth: 150 },
|
||||
{ prop: 'deliveryMethod', label: '派送方式', width: 120, formatter: (_row: object, _column: unknown, value: string | null | undefined) => value ? deliveryMethodLabels[value] ?? value : '—' }, { prop: 'waybillNo', label: '运单号', minWidth: 150 },
|
||||
{ prop: 'carrierName', label: '承运商', minWidth: 140 }, { key: 'planned', label: '计划派送', slotName: 'planned', width: 160 },
|
||||
{ key: 'arrival', label: '预计到达', slotName: 'arrival', width: 160 }, { key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 160 },
|
||||
]
|
||||
@@ -84,18 +98,21 @@ function buildQuery(): DeliveryQuery {
|
||||
}
|
||||
|
||||
async function loadOrders() {
|
||||
const sequence = ++requestSequence
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const result = await listDeliveryOrders(buildQuery())
|
||||
if (sequence !== requestSequence) return
|
||||
records.value = result.records
|
||||
total.value = result.total
|
||||
} catch (error) {
|
||||
if (sequence !== requestSequence) return
|
||||
records.value = []
|
||||
total.value = 0
|
||||
errorMessage.value = error instanceof Error ? error.message : '派送单加载失败,请重试'
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (sequence === requestSequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user