feat: complete admin API integration
This commit is contained in:
+42
-2
@@ -1,6 +1,21 @@
|
||||
import axios, { AxiosHeaders } from 'axios'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ApiResponseError, getApiErrorDetails, unwrapApiResponse } from './http'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
ApiResponseError,
|
||||
getApiErrorDetails,
|
||||
http,
|
||||
registerAuthRefreshHandler,
|
||||
registerAuthSessionExpiredHandler,
|
||||
unwrapApiResponse,
|
||||
} from './http'
|
||||
|
||||
const originalAdapter = http.defaults.adapter
|
||||
|
||||
afterEach(() => {
|
||||
http.defaults.adapter = originalAdapter
|
||||
registerAuthRefreshHandler(async () => { throw new Error('refresh handler is not configured') })
|
||||
registerAuthSessionExpiredHandler(() => undefined)
|
||||
})
|
||||
|
||||
describe('API error diagnostics', () => {
|
||||
it('keeps business request and trace identifiers when unwrapping fails', () => {
|
||||
@@ -40,4 +55,29 @@ describe('API error diagnostics', () => {
|
||||
traceId: 'trace-2',
|
||||
})
|
||||
})
|
||||
|
||||
it('notifies session expiry once when concurrent 401 requests share a failed refresh', async () => {
|
||||
const refresh = vi.fn(async () => { throw new Error('refresh token expired') })
|
||||
const expired = vi.fn()
|
||||
registerAuthRefreshHandler(refresh)
|
||||
registerAuthSessionExpiredHandler(expired)
|
||||
http.defaults.adapter = async (config) => {
|
||||
throw new axios.AxiosError('Unauthorized', 'ERR_BAD_REQUEST', config, undefined, {
|
||||
status: 401,
|
||||
statusText: 'Unauthorized',
|
||||
headers: {},
|
||||
config,
|
||||
data: { code: 'A0401', message: '登录状态已过期' },
|
||||
})
|
||||
}
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
http.get('/platform/v1/orders'),
|
||||
http.get('/platform/v1/warehouses'),
|
||||
])
|
||||
|
||||
expect(results.every((result) => result.status === 'rejected')).toBe(true)
|
||||
expect(refresh).toHaveBeenCalledTimes(1)
|
||||
expect(expired).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
+16
-1
@@ -43,14 +43,20 @@ export const http = axios.create({
|
||||
|
||||
type RetryableRequestConfig = InternalAxiosRequestConfig & { _authRetry?: boolean }
|
||||
type AuthRefreshHandler = () => Promise<string>
|
||||
type AuthSessionExpiredHandler = () => void | Promise<void>
|
||||
|
||||
let authRefreshHandler: AuthRefreshHandler | null = null
|
||||
let authSessionExpiredHandler: AuthSessionExpiredHandler | null = null
|
||||
let activeRefresh: Promise<string> | null = null
|
||||
|
||||
export function registerAuthRefreshHandler(handler: AuthRefreshHandler) {
|
||||
authRefreshHandler = handler
|
||||
}
|
||||
|
||||
export function registerAuthSessionExpiredHandler(handler: AuthSessionExpiredHandler) {
|
||||
authSessionExpiredHandler = handler
|
||||
}
|
||||
|
||||
http.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('cc-admin-token')
|
||||
if (token) {
|
||||
@@ -71,7 +77,16 @@ http.interceptors.response.use(
|
||||
config._authRetry = true
|
||||
try {
|
||||
if (!activeRefresh) {
|
||||
activeRefresh = authRefreshHandler().finally(() => { activeRefresh = null })
|
||||
activeRefresh = authRefreshHandler()
|
||||
.catch(async (refreshError) => {
|
||||
try {
|
||||
await authSessionExpiredHandler?.()
|
||||
} catch {
|
||||
// 会话已清理,跳转失败不应覆盖原始认证错误。
|
||||
}
|
||||
throw refreshError
|
||||
})
|
||||
.finally(() => { activeRefresh = null })
|
||||
}
|
||||
const nextToken = await activeRefresh
|
||||
config.headers.Authorization = `Bearer ${nextToken}`
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/api/http'
|
||||
import {
|
||||
acceptPlatformFirstLegOrder,
|
||||
addPlatformFirstLegOrderNote,
|
||||
approvePlatformFirstLegOrder,
|
||||
cancelPlatformFirstLegOrder,
|
||||
completePlatformFirstLegOrder,
|
||||
getPlatformFirstLegOrder,
|
||||
listPlatformFirstLegOrders,
|
||||
startPlatformFirstLegOrder,
|
||||
updatePlatformFirstLegOrderExpress,
|
||||
} from './platformFirstLegOrders'
|
||||
|
||||
vi.mock('@/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
describe('platform first-leg order API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
})
|
||||
|
||||
it('queries a tenant-scoped order page with server pagination and filters', async () => {
|
||||
const page = { records: [], page: 2, size: 20, total: 0, pages: 0 }
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: page })
|
||||
|
||||
await expect(listPlatformFirstLegOrders('10001', {
|
||||
keyword: 'FL2026', status: 'SUBMITTED', createdFrom: '2026-07-01T00:00:00', createdTo: '2026-07-31T23:59:59', page: 2, size: 20,
|
||||
})).resolves.toEqual(page)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/orders/first-leg', {
|
||||
params: {
|
||||
tenantId: '10001', keyword: 'FL2026', status: 'SUBMITTED', createdFrom: '2026-07-01T00:00:00', createdTo: '2026-07-31T23:59:59', page: 2, size: 20,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the platform lifecycle routes and target tenant query parameter', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: { order: {} } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '0', message: 'success', data: null })
|
||||
|
||||
await getPlatformFirstLegOrder('10001', '90001')
|
||||
await approvePlatformFirstLegOrder('10001', '90001')
|
||||
await acceptPlatformFirstLegOrder('10001', '90001')
|
||||
await startPlatformFirstLegOrder('10001', '90001')
|
||||
await completePlatformFirstLegOrder('10001', '90001')
|
||||
await cancelPlatformFirstLegOrder('10001', '90001', '客户取消')
|
||||
await addPlatformFirstLegOrderNote('10001', '90001', '已联系客户确认')
|
||||
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/orders/first-leg/90001', { params: { tenantId: '10001' } })
|
||||
expect(http.post).toHaveBeenNthCalledWith(1, '/platform/v1/orders/first-leg/90001/approve', undefined, { params: { tenantId: '10001' } })
|
||||
expect(http.post).toHaveBeenNthCalledWith(2, '/platform/v1/orders/first-leg/90001/accept', undefined, { params: { tenantId: '10001' } })
|
||||
expect(http.post).toHaveBeenNthCalledWith(3, '/platform/v1/orders/first-leg/90001/start', undefined, { params: { tenantId: '10001' } })
|
||||
expect(http.post).toHaveBeenNthCalledWith(4, '/platform/v1/orders/first-leg/90001/complete', undefined, { params: { tenantId: '10001' } })
|
||||
expect(http.post).toHaveBeenNthCalledWith(5, '/platform/v1/orders/first-leg/90001/cancel', { reason: '客户取消' }, { params: { tenantId: '10001' } })
|
||||
expect(http.post).toHaveBeenNthCalledWith(6, '/platform/v1/orders/first-leg/90001/internal-notes', { content: '已联系客户确认' }, { params: { tenantId: '10001' } })
|
||||
})
|
||||
|
||||
it('writes the backend express contract as names, not a guessed master-data ID', async () => {
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '0', message: 'success', data: null })
|
||||
|
||||
await updatePlatformFirstLegOrderExpress('10001', '90001', { expressCompany: '顺丰速运', expressTrackingNo: 'SF123456' })
|
||||
expect(http.put).toHaveBeenCalledWith(
|
||||
'/platform/v1/orders/first-leg/90001/express',
|
||||
{ expressCompany: '顺丰速运', expressTrackingNo: 'SF123456' },
|
||||
{ params: { tenantId: '10001' } },
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/api/http'
|
||||
|
||||
export type PlatformFirstLegOrderStatus =
|
||||
| 'DRAFT'
|
||||
| 'SUBMITTED'
|
||||
| 'APPROVED'
|
||||
| 'ACCEPTED'
|
||||
| 'REJECTED'
|
||||
| 'CANCELLED'
|
||||
| 'PROCESSING'
|
||||
| 'COMPLETED'
|
||||
|
||||
export interface PlatformFirstLegOrderResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
orderNo: string | null
|
||||
customerId: number | string | null
|
||||
customerName: string
|
||||
status: PlatformFirstLegOrderStatus
|
||||
transportMode: 'SEA' | 'AIR' | 'RAIL' | 'TRUCK'
|
||||
tradeTerm: string | null
|
||||
destinationCountryCode: string
|
||||
destinationWarehouseId: number | string | null
|
||||
destinationWarehouseName: string
|
||||
expectedShipDate: string | null
|
||||
customerRemark: string | null
|
||||
pickupMethod: string
|
||||
receivingWarehouseId: number | string
|
||||
receivingWarehouseName: string
|
||||
receivingWarehouseAddress: string | null
|
||||
receivingTime: string | null
|
||||
channelCode: string
|
||||
channelName: string
|
||||
taxMode: string
|
||||
containerMode: string | null
|
||||
customsInspection: boolean | null
|
||||
destinationType: string
|
||||
amazonWarehouseCode: string | null
|
||||
shipmentId: string | null
|
||||
referenceId: string | null
|
||||
expressCompany: string | null
|
||||
expressTrackingNo: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface PlatformFirstLegCargoResource {
|
||||
id: number | string
|
||||
itemNo: number
|
||||
cargoName: string
|
||||
cargoNameEn: string | null
|
||||
packageType: string
|
||||
packageCount: number
|
||||
grossWeightKg: number
|
||||
volumeCbm: number
|
||||
totalQuantity: number | null
|
||||
cargoRemark: string | null
|
||||
}
|
||||
|
||||
export interface PlatformFirstLegPartyResource {
|
||||
id: number | string
|
||||
partyType: 'SENDER' | 'RECEIVER' | string
|
||||
companyName: string
|
||||
contactName: string
|
||||
phone: string
|
||||
email: string | null
|
||||
countryCode: string
|
||||
province: string | null
|
||||
city: string
|
||||
district: string | null
|
||||
addressLine: string
|
||||
postalCode: string | null
|
||||
}
|
||||
|
||||
export interface PlatformOrderStatusHistoryResource {
|
||||
id: number | string
|
||||
fromStatus: PlatformFirstLegOrderStatus | null
|
||||
toStatus: PlatformFirstLegOrderStatus
|
||||
action: string
|
||||
reason: string | null
|
||||
operatorName: string | null
|
||||
occurredAt: string
|
||||
}
|
||||
|
||||
export interface PlatformOrderInternalNoteResource {
|
||||
id: number | string
|
||||
content: string
|
||||
createdAt: string
|
||||
createdBy: number | string | null
|
||||
}
|
||||
|
||||
export interface PlatformFirstLegOrderDetailResource {
|
||||
order: PlatformFirstLegOrderResource
|
||||
cargoes: PlatformFirstLegCargoResource[]
|
||||
parties: PlatformFirstLegPartyResource[]
|
||||
internalNotes: PlatformOrderInternalNoteResource[]
|
||||
statusHistory: PlatformOrderStatusHistoryResource[]
|
||||
}
|
||||
|
||||
export interface PlatformFirstLegOrderPageResource {
|
||||
records: PlatformFirstLegOrderResource[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
export interface PlatformFirstLegOrderQuery {
|
||||
keyword?: string
|
||||
status?: PlatformFirstLegOrderStatus
|
||||
customerId?: string
|
||||
destinationWarehouseId?: string
|
||||
createdFrom?: string
|
||||
createdTo?: string
|
||||
page: number
|
||||
size: number
|
||||
}
|
||||
|
||||
async function getData<T>(path: string, params?: Record<string, unknown>) {
|
||||
const response = await http.get<ApiEnvelope<T>, ApiEnvelope<T>>(path, { params })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function postData<T>(path: string, body?: unknown, params?: Record<string, unknown>) {
|
||||
const response = await http.post<ApiEnvelope<T>, ApiEnvelope<T>>(path, body, { params })
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export function listPlatformFirstLegOrders(tenantId: string, query: PlatformFirstLegOrderQuery) {
|
||||
return getData<PlatformFirstLegOrderPageResource>('/platform/v1/orders/first-leg', { tenantId, ...query })
|
||||
}
|
||||
|
||||
export function getPlatformFirstLegOrder(tenantId: string, orderId: string) {
|
||||
return getData<PlatformFirstLegOrderDetailResource>(`/platform/v1/orders/first-leg/${orderId}`, { tenantId })
|
||||
}
|
||||
|
||||
export function approvePlatformFirstLegOrder(tenantId: string, orderId: string) {
|
||||
return postData<void>(`/platform/v1/orders/first-leg/${orderId}/approve`, undefined, { tenantId })
|
||||
}
|
||||
|
||||
export function acceptPlatformFirstLegOrder(tenantId: string, orderId: string) {
|
||||
return postData<void>(`/platform/v1/orders/first-leg/${orderId}/accept`, undefined, { tenantId })
|
||||
}
|
||||
|
||||
export function startPlatformFirstLegOrder(tenantId: string, orderId: string) {
|
||||
return postData<void>(`/platform/v1/orders/first-leg/${orderId}/start`, undefined, { tenantId })
|
||||
}
|
||||
|
||||
export function completePlatformFirstLegOrder(tenantId: string, orderId: string) {
|
||||
return postData<void>(`/platform/v1/orders/first-leg/${orderId}/complete`, undefined, { tenantId })
|
||||
}
|
||||
|
||||
export function cancelPlatformFirstLegOrder(tenantId: string, orderId: string, reason: string) {
|
||||
return postData<void>(`/platform/v1/orders/first-leg/${orderId}/cancel`, { reason }, { tenantId })
|
||||
}
|
||||
|
||||
export function addPlatformFirstLegOrderNote(tenantId: string, orderId: string, content: string) {
|
||||
return postData<number | string>(`/platform/v1/orders/first-leg/${orderId}/internal-notes`, { content }, { tenantId })
|
||||
}
|
||||
|
||||
export function updatePlatformFirstLegOrderExpress(
|
||||
tenantId: string,
|
||||
orderId: string,
|
||||
payload: { expressCompany: string; expressTrackingNo: string },
|
||||
) {
|
||||
return http.put<ApiEnvelope<void>, ApiEnvelope<void>>(
|
||||
`/platform/v1/orders/first-leg/${orderId}/express`,
|
||||
payload,
|
||||
{ params: { tenantId } },
|
||||
).then(unwrapApiResponse)
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/api/http'
|
||||
import {
|
||||
changePlatformRoleStatus,
|
||||
createPlatformPermission,
|
||||
createPlatformRole,
|
||||
deletePlatformRole,
|
||||
downloadTenantQualification,
|
||||
listTenantQualifications,
|
||||
listCurrentPlatformPermissionCodes,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
qualificationFileName,
|
||||
replacePlatformRolePermissions,
|
||||
updatePlatformRole,
|
||||
type PlatformPermissionResource,
|
||||
type PlatformRoleResource,
|
||||
} from './platformIam'
|
||||
|
||||
vi.mock('@/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn() },
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
@@ -26,6 +31,7 @@ const role: PlatformRoleResource = {
|
||||
roleType: 'SYSTEM',
|
||||
status: 'ACTIVE',
|
||||
description: '企业资料与入驻审核',
|
||||
permissionIds: ['5100010'],
|
||||
}
|
||||
|
||||
const permission: PlatformPermissionResource = {
|
||||
@@ -46,6 +52,8 @@ describe('platform IAM roles', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(http.delete).mockReset()
|
||||
})
|
||||
|
||||
it('loads roles from the platform IAM prefix', async () => {
|
||||
@@ -67,6 +75,21 @@ describe('platform IAM roles', () => {
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/roles', payload)
|
||||
})
|
||||
|
||||
it('updates status, permissions, and deletes roles with the implemented IAM routes', async () => {
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '0', message: 'success', data: role })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '0', message: 'success', data: null })
|
||||
|
||||
await expect(updatePlatformRole(role.id, { roleName: '审核主管', description: '负责企业审核' })).resolves.toEqual(role)
|
||||
await expect(changePlatformRoleStatus(role.id, 'DISABLED')).resolves.toEqual(role)
|
||||
await expect(replacePlatformRolePermissions(role.id, ['5100010'])).resolves.toEqual(role)
|
||||
await expect(deletePlatformRole(role.id)).resolves.toBeNull()
|
||||
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/roles/${role.id}`, { roleName: '审核主管', description: '负责企业审核' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/roles/${role.id}/status`, { status: 'DISABLED' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(3, '/platform/v1/iam/roles/permissions', { roleId: role.id, permissionIds: ['5100010'] })
|
||||
expect(http.delete).toHaveBeenCalledWith(`/platform/v1/iam/roles/${role.id}`)
|
||||
})
|
||||
|
||||
it('loads and creates permission resources under the platform IAM prefix', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: [permission] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '0', message: 'success', data: permission })
|
||||
@@ -86,6 +109,13 @@ describe('platform IAM roles', () => {
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/permissions', payload)
|
||||
})
|
||||
|
||||
it('loads the current users permission snapshot without calling the role-management endpoint', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '0', message: 'success', data: ['platform:warehouse:list'] })
|
||||
|
||||
await expect(listCurrentPlatformPermissionCodes()).resolves.toEqual(['platform:warehouse:list'])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/authorization/permissions')
|
||||
})
|
||||
|
||||
it('loads qualifications for the selected tenant', async () => {
|
||||
const qualification = {
|
||||
id: 12,
|
||||
|
||||
+38
-2
@@ -44,14 +44,15 @@ export interface PlatformTenantQualification {
|
||||
}
|
||||
|
||||
export interface PlatformRoleResource {
|
||||
id: number
|
||||
tenantId: number
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
appCode: 'PLATFORM'
|
||||
roleCode: string
|
||||
roleName: string
|
||||
roleType: 'SYSTEM' | 'CUSTOM' | string
|
||||
status: 'ACTIVE' | 'INACTIVE' | string
|
||||
description: string | null
|
||||
permissionIds?: Array<number | string>
|
||||
}
|
||||
|
||||
export interface CreatePlatformRoleRequest {
|
||||
@@ -60,6 +61,11 @@ export interface CreatePlatformRoleRequest {
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface UpdatePlatformRoleRequest {
|
||||
roleName: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface CreatePlatformPermissionRequest {
|
||||
type: 'MENU' | 'BUTTON'
|
||||
code: string
|
||||
@@ -80,10 +86,24 @@ async function postData<T>(path: string, body: unknown): Promise<T> {
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function putData<T>(path: string, body: unknown): Promise<T> {
|
||||
const response = await http.put<ApiEnvelope<T>, ApiEnvelope<T>>(path, body)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function deleteData<T>(path: string): Promise<T> {
|
||||
const response = await http.delete<ApiEnvelope<T>, ApiEnvelope<T>>(path)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export function listPlatformPermissions() {
|
||||
return getData<PlatformPermissionResource[]>('/platform/v1/iam/permissions')
|
||||
}
|
||||
|
||||
export function listCurrentPlatformPermissionCodes() {
|
||||
return getData<string[]>('/platform/v1/iam/authorization/permissions')
|
||||
}
|
||||
|
||||
export function listEnterpriseReviews() {
|
||||
return getData<EnterpriseReview[]>('/platform/v1/iam/reviews')
|
||||
}
|
||||
@@ -123,6 +143,22 @@ export function createPlatformRole(payload: CreatePlatformRoleRequest) {
|
||||
return postData<PlatformRoleResource>('/platform/v1/iam/roles', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformRole(roleId: number | string, payload: UpdatePlatformRoleRequest) {
|
||||
return putData<PlatformRoleResource>(`/platform/v1/iam/roles/${roleId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformRoleStatus(roleId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformRoleResource>(`/platform/v1/iam/roles/${roleId}/status`, { status })
|
||||
}
|
||||
|
||||
export function deletePlatformRole(roleId: number | string) {
|
||||
return deleteData<void>(`/platform/v1/iam/roles/${roleId}`)
|
||||
}
|
||||
|
||||
export function replacePlatformRolePermissions(roleId: number | string, permissionIds: Array<number | string>) {
|
||||
return putData<void>('/platform/v1/iam/roles/permissions', { roleId, permissionIds })
|
||||
}
|
||||
|
||||
export function createPlatformPermission(payload: CreatePlatformPermissionRequest) {
|
||||
return postData<PlatformPermissionResource>('/platform/v1/iam/permissions', payload)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/api/http'
|
||||
import {
|
||||
changePlatformWarehouseStatus,
|
||||
createPlatformWarehouse,
|
||||
getPlatformWarehouse,
|
||||
listPlatformWarehouses,
|
||||
updatePlatformWarehouse,
|
||||
type SavePlatformWarehouseRequest,
|
||||
} from './platformWarehouses'
|
||||
|
||||
vi.mock('@/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
const payload: SavePlatformWarehouseRequest = {
|
||||
tenantId: 10001,
|
||||
warehouseCode: 'CN-YW-01',
|
||||
warehouseName: '义乌收货仓',
|
||||
warehouseType: 'DOMESTIC',
|
||||
countryCode: 'CN',
|
||||
timezone: 'Asia/Shanghai',
|
||||
contactName: '仓库客服',
|
||||
contactPhone: '0579-12345678',
|
||||
contactEmail: null,
|
||||
status: 'ACTIVE',
|
||||
remark: null,
|
||||
address: {
|
||||
addressType: 'OPERATING',
|
||||
countryCode: 'CN',
|
||||
stateProvince: '浙江省',
|
||||
city: '义乌市',
|
||||
district: null,
|
||||
postalCode: null,
|
||||
addressLine1: '北苑街道 1 号库',
|
||||
addressLine2: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
},
|
||||
capabilities: [{
|
||||
capabilityCode: 'RECEIVING',
|
||||
capabilityName: '收货服务',
|
||||
enabled: true,
|
||||
cutoffTime: null,
|
||||
description: '周一至周六 08:30-18:00',
|
||||
}],
|
||||
}
|
||||
|
||||
describe('platform warehouse API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(http.patch).mockReset()
|
||||
})
|
||||
|
||||
it('lists and loads warehouse details for the target tenant', async () => {
|
||||
const page = { records: [], page: 1, size: 200, total: 0, pages: 0 }
|
||||
const detail = { warehouse: {}, addresses: [], capabilities: [] }
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce({ code: '0', message: 'success', data: page })
|
||||
.mockResolvedValueOnce({ code: '0', message: 'success', data: detail })
|
||||
|
||||
await expect(listPlatformWarehouses(10001)).resolves.toEqual(page)
|
||||
await expect(getPlatformWarehouse(10001, '19001')).resolves.toEqual(detail)
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/warehouse-admin', {
|
||||
params: { tenantId: 10001, page: 1, size: 200 },
|
||||
})
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/warehouse-admin/19001', {
|
||||
params: { tenantId: 10001 },
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the implemented create, update, and status routes', async () => {
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '0', message: 'success', data: '19001' })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '0', message: 'success', data: null })
|
||||
vi.mocked(http.patch).mockResolvedValue({ code: '0', message: 'success', data: null })
|
||||
|
||||
await expect(createPlatformWarehouse(payload)).resolves.toBe('19001')
|
||||
await expect(updatePlatformWarehouse(10001, '19001', payload)).resolves.toBeNull()
|
||||
await expect(changePlatformWarehouseStatus(10001, '19001', 'INACTIVE')).resolves.toBeNull()
|
||||
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/warehouse-admin', payload)
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/warehouse-admin/19001', payload, {
|
||||
params: { tenantId: 10001 },
|
||||
})
|
||||
expect(http.patch).toHaveBeenCalledWith('/platform/v1/warehouse-admin/19001/status', undefined, {
|
||||
params: { tenantId: 10001, status: 'INACTIVE' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/api/http'
|
||||
|
||||
export type PlatformWarehouseStatus = 'ACTIVE' | 'INACTIVE'
|
||||
|
||||
export interface PlatformWarehouseResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
warehouseCode: string
|
||||
warehouseName: string
|
||||
warehouseType: string
|
||||
countryCode: string
|
||||
timezone: string
|
||||
contactName: string | null
|
||||
contactPhone: string | null
|
||||
contactEmail: string | null
|
||||
status: PlatformWarehouseStatus
|
||||
remark: string | null
|
||||
createdAt?: string | null
|
||||
updatedAt?: string | null
|
||||
}
|
||||
|
||||
export interface PlatformWarehouseAddressResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
warehouseId: number | string
|
||||
addressType: string
|
||||
countryCode: string
|
||||
stateProvince: string | null
|
||||
city: string
|
||||
district: string | null
|
||||
postalCode: string | null
|
||||
addressLine1: string
|
||||
addressLine2: string | null
|
||||
latitude: number | string | null
|
||||
longitude: number | string | null
|
||||
}
|
||||
|
||||
export interface PlatformWarehouseCapabilityResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
warehouseId: number | string
|
||||
capabilityCode: string
|
||||
capabilityName: string
|
||||
enabled: boolean | null
|
||||
cutoffTime: string | null
|
||||
description: string | null
|
||||
}
|
||||
|
||||
export interface PlatformWarehouseDetailResource {
|
||||
warehouse: PlatformWarehouseResource
|
||||
addresses: PlatformWarehouseAddressResource[]
|
||||
capabilities: PlatformWarehouseCapabilityResource[]
|
||||
}
|
||||
|
||||
export interface PlatformWarehousePage {
|
||||
records: PlatformWarehouseResource[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
export interface PlatformWarehouseAddressRequest {
|
||||
addressType: string
|
||||
countryCode: string
|
||||
stateProvince: string | null
|
||||
city: string
|
||||
district: string | null
|
||||
postalCode: string | null
|
||||
addressLine1: string
|
||||
addressLine2: string | null
|
||||
latitude: number | string | null
|
||||
longitude: number | string | null
|
||||
}
|
||||
|
||||
export interface PlatformWarehouseCapabilityRequest {
|
||||
capabilityCode: string
|
||||
capabilityName: string
|
||||
enabled: boolean
|
||||
cutoffTime: string | null
|
||||
description: string | null
|
||||
}
|
||||
|
||||
export interface SavePlatformWarehouseRequest {
|
||||
tenantId: number
|
||||
warehouseCode: string
|
||||
warehouseName: string
|
||||
warehouseType: string
|
||||
countryCode: string
|
||||
timezone: string
|
||||
contactName: string | null
|
||||
contactPhone: string | null
|
||||
contactEmail: string | null
|
||||
status: PlatformWarehouseStatus
|
||||
remark: string | null
|
||||
address: PlatformWarehouseAddressRequest
|
||||
capabilities: PlatformWarehouseCapabilityRequest[]
|
||||
}
|
||||
|
||||
const basePath = '/platform/v1/warehouse-admin'
|
||||
|
||||
export async function listPlatformWarehouses(tenantId: number, page = 1, size = 200) {
|
||||
const response = await http.get<ApiEnvelope<PlatformWarehousePage>, ApiEnvelope<PlatformWarehousePage>>(basePath, {
|
||||
params: { tenantId, page, size },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function getPlatformWarehouse(tenantId: number, warehouseId: number | string) {
|
||||
const response = await http.get<ApiEnvelope<PlatformWarehouseDetailResource>, ApiEnvelope<PlatformWarehouseDetailResource>>(
|
||||
`${basePath}/${warehouseId}`,
|
||||
{ params: { tenantId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function createPlatformWarehouse(payload: SavePlatformWarehouseRequest) {
|
||||
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function updatePlatformWarehouse(tenantId: number, warehouseId: number | string, payload: SavePlatformWarehouseRequest) {
|
||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${warehouseId}`, payload, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function changePlatformWarehouseStatus(
|
||||
tenantId: number,
|
||||
warehouseId: number | string,
|
||||
status: PlatformWarehouseStatus,
|
||||
) {
|
||||
const response = await http.patch<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${warehouseId}/status`, undefined, {
|
||||
params: { tenantId, status },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
Vendored
+1
@@ -46,6 +46,7 @@ declare module 'vue' {
|
||||
ElTimelineItem: typeof import('element-plus/es')['ElTimelineItem']
|
||||
ElTree: typeof import('element-plus/es')['ElTree']
|
||||
MetricStrip: typeof import('./components/MetricStrip.vue')['default']
|
||||
PlatformFirstLegOrdersPanel: typeof import('./components/PlatformFirstLegOrdersPanel.vue')['default']
|
||||
RolePreviewSwitcher: typeof import('./components/RolePreviewSwitcher.vue')['default']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Eye, FilePenLine, PackageCheck, RotateCcw, Search } from '@lucide/vue'
|
||||
import {
|
||||
acceptPlatformFirstLegOrder,
|
||||
addPlatformFirstLegOrderNote,
|
||||
approvePlatformFirstLegOrder,
|
||||
cancelPlatformFirstLegOrder,
|
||||
completePlatformFirstLegOrder,
|
||||
getPlatformFirstLegOrder,
|
||||
listPlatformFirstLegOrders,
|
||||
startPlatformFirstLegOrder,
|
||||
updatePlatformFirstLegOrderExpress,
|
||||
type PlatformFirstLegOrderDetailResource,
|
||||
type PlatformFirstLegOrderResource,
|
||||
type PlatformFirstLegOrderStatus,
|
||||
} from '@/api/platformFirstLegOrders'
|
||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/api/http'
|
||||
import ApiErrorMeta from '@/components/ApiErrorMeta.vue'
|
||||
import MetricStrip from '@/components/MetricStrip.vue'
|
||||
import StatusBadge from '@/components/StatusBadge.vue'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
|
||||
const TENANT_SESSION_KEY = 'cc-admin-first-leg-order-tenant-id'
|
||||
const access = useAccessPreviewStore()
|
||||
const tenantId = ref(sessionStorage.getItem(TENANT_SESSION_KEY) || '')
|
||||
const loadedTenantId = ref('')
|
||||
const orders = ref<PlatformFirstLegOrderResource[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = 20
|
||||
const loading = ref(false)
|
||||
const actionLoadingId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const detailOpen = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<PlatformFirstLegOrderDetailResource | null>(null)
|
||||
const noteDialogOpen = ref(false)
|
||||
const expressDialogOpen = ref(false)
|
||||
const selectedOrder = ref<PlatformFirstLegOrderResource | null>(null)
|
||||
const noteContent = ref('')
|
||||
const noteSaving = ref(false)
|
||||
const expressSaving = ref(false)
|
||||
const expressForm = reactive({ expressCompany: '', expressTrackingNo: '' })
|
||||
const filters = reactive<{ keyword: string; status: PlatformFirstLegOrderStatus | ''; dateRange: [string, string] | [] }>({
|
||||
keyword: '',
|
||||
status: '',
|
||||
dateRange: [],
|
||||
})
|
||||
|
||||
const tenantReady = computed(() => Boolean(loadedTenantId.value) && tenantId.value.trim() === loadedTenantId.value)
|
||||
const metrics = computed(() => [
|
||||
{ label: '订单总数', value: total.value, note: loadedTenantId.value ? `租户 ${loadedTenantId.value}` : '等待选择租户' },
|
||||
{ label: '待审核', value: orders.value.filter((item) => item.status === 'SUBMITTED').length, note: '当前页数据' },
|
||||
{ label: '履约处理中', value: orders.value.filter((item) => ['APPROVED', 'ACCEPTED', 'PROCESSING'].includes(item.status)).length, note: '当前页数据' },
|
||||
{ label: '已完成', value: orders.value.filter((item) => item.status === 'COMPLETED').length, note: '当前页数据' },
|
||||
])
|
||||
|
||||
const statusOptions: Array<{ value: PlatformFirstLegOrderStatus; label: string }> = [
|
||||
{ value: 'DRAFT', label: '草稿' },
|
||||
{ value: 'SUBMITTED', label: '待审核' },
|
||||
{ value: 'APPROVED', label: '已审核' },
|
||||
{ value: 'ACCEPTED', label: '已受理' },
|
||||
{ value: 'PROCESSING', label: '处理中' },
|
||||
{ value: 'COMPLETED', label: '已完成' },
|
||||
{ value: 'CANCELLED', label: '已取消' },
|
||||
{ value: 'REJECTED', label: '已驳回(旧契约)' },
|
||||
]
|
||||
|
||||
function statusLabel(status: PlatformFirstLegOrderStatus) {
|
||||
return statusOptions.find((item) => item.value === status)?.label || status
|
||||
}
|
||||
|
||||
function transportLabel(order: PlatformFirstLegOrderResource) {
|
||||
if (order.transportMode === 'SEA') return order.containerMode === 'FULL_CONTAINER' ? '海运整箱 FCL' : '海运拼箱 LCL'
|
||||
if (order.transportMode === 'AIR') return '空运'
|
||||
if (order.transportMode === 'RAIL') return '铁路运输'
|
||||
return '陆运'
|
||||
}
|
||||
|
||||
function formattedDate(value: string | null | undefined) {
|
||||
return value ? value.replace('T', ' ') : '-'
|
||||
}
|
||||
|
||||
function can(action: string) {
|
||||
return access.can(action)
|
||||
}
|
||||
|
||||
function canCancel(order: PlatformFirstLegOrderResource) {
|
||||
return can('platform:order:cancel') && ['DRAFT', 'SUBMITTED', 'APPROVED', 'ACCEPTED', 'REJECTED'].includes(order.status)
|
||||
}
|
||||
|
||||
function actionLabel(order: PlatformFirstLegOrderResource) {
|
||||
if (order.status === 'SUBMITTED' && can('platform:order:approve')) return '审核通过'
|
||||
if (order.status === 'APPROVED' && can('platform:order:accept')) return '受理订单'
|
||||
if (order.status === 'ACCEPTED' && can('platform:order:process')) return '开始处理'
|
||||
if (order.status === 'PROCESSING' && can('platform:order:complete')) return '完成订单'
|
||||
return ''
|
||||
}
|
||||
|
||||
async function loadOrders(resetPage = false) {
|
||||
const targetTenantId = tenantId.value.trim()
|
||||
loadError.value = null
|
||||
if (!/^\d+$/.test(targetTenantId) || targetTenantId === '0') {
|
||||
loadError.value = { message: '请输入有效的目标租户 ID 后查询订单' }
|
||||
return
|
||||
}
|
||||
if (resetPage) page.value = 1
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await listPlatformFirstLegOrders(targetTenantId, {
|
||||
keyword: filters.keyword.trim() || undefined,
|
||||
status: filters.status || undefined,
|
||||
createdFrom: filters.dateRange.length === 2 ? `${filters.dateRange[0]}T00:00:00` : undefined,
|
||||
createdTo: filters.dateRange.length === 2 ? `${filters.dateRange[1]}T23:59:59` : undefined,
|
||||
page: page.value,
|
||||
size: pageSize,
|
||||
})
|
||||
orders.value = result.records
|
||||
total.value = result.total
|
||||
loadedTenantId.value = targetTenantId
|
||||
sessionStorage.setItem(TENANT_SESSION_KEY, targetTenantId)
|
||||
} catch (error) {
|
||||
orders.value = []
|
||||
total.value = 0
|
||||
loadError.value = getApiErrorDetails(error, '订单列表加载失败,请检查 Gateway、租户范围和订单权限')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
filters.keyword = ''
|
||||
filters.status = ''
|
||||
filters.dateRange = []
|
||||
void loadOrders(true)
|
||||
}
|
||||
|
||||
function handlePageChange(nextPage: number) {
|
||||
page.value = nextPage
|
||||
void loadOrders()
|
||||
}
|
||||
|
||||
async function openDetail(order: PlatformFirstLegOrderResource) {
|
||||
if (!tenantReady.value) return
|
||||
selectedOrder.value = order
|
||||
detail.value = null
|
||||
detailOpen.value = true
|
||||
detailLoading.value = true
|
||||
try {
|
||||
detail.value = await getPlatformFirstLegOrder(loadedTenantId.value, String(order.id))
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '订单详情加载失败')
|
||||
ElMessage.error(details.message)
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAfterAction(orderId: string) {
|
||||
await loadOrders()
|
||||
if (detailOpen.value && selectedOrder.value?.id === orderId) {
|
||||
detail.value = await getPlatformFirstLegOrder(loadedTenantId.value, orderId)
|
||||
}
|
||||
}
|
||||
|
||||
async function runLifecycleAction(order: PlatformFirstLegOrderResource) {
|
||||
if (!tenantReady.value) return
|
||||
const label = actionLabel(order)
|
||||
if (!label) return
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${label}“${order.orderNo || order.id}”吗?该操作会写入订单状态历史。`, label, {
|
||||
confirmButtonText: `确认${label}`,
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
})
|
||||
actionLoadingId.value = String(order.id)
|
||||
if (order.status === 'SUBMITTED') await approvePlatformFirstLegOrder(loadedTenantId.value, String(order.id))
|
||||
if (order.status === 'APPROVED') await acceptPlatformFirstLegOrder(loadedTenantId.value, String(order.id))
|
||||
if (order.status === 'ACCEPTED') await startPlatformFirstLegOrder(loadedTenantId.value, String(order.id))
|
||||
if (order.status === 'PROCESSING') await completePlatformFirstLegOrder(loadedTenantId.value, String(order.id))
|
||||
await refreshAfterAction(String(order.id))
|
||||
ElMessage.success(`${label}已完成`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorDetails(error, `${label}失败,请稍后重试`).message)
|
||||
} finally {
|
||||
actionLoadingId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelOrder(order: PlatformFirstLegOrderResource) {
|
||||
if (!tenantReady.value) return
|
||||
try {
|
||||
const result = await ElMessageBox.prompt('请填写取消原因。后端要求该字段必填,并将写入订单状态历史。', '取消订单', {
|
||||
confirmButtonText: '确认取消',
|
||||
cancelButtonText: '返回',
|
||||
inputPattern: /\S+/,
|
||||
inputErrorMessage: '请填写取消原因',
|
||||
inputPlaceholder: '例如:客户取消本次运输安排',
|
||||
})
|
||||
actionLoadingId.value = String(order.id)
|
||||
await cancelPlatformFirstLegOrder(loadedTenantId.value, String(order.id), result.value.trim())
|
||||
await refreshAfterAction(String(order.id))
|
||||
ElMessage.success('订单已取消')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorDetails(error, '取消订单失败,请稍后重试').message)
|
||||
} finally {
|
||||
actionLoadingId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function openExpress(order: PlatformFirstLegOrderResource) {
|
||||
selectedOrder.value = order
|
||||
expressForm.expressCompany = order.expressCompany || ''
|
||||
expressForm.expressTrackingNo = order.expressTrackingNo || ''
|
||||
expressDialogOpen.value = true
|
||||
}
|
||||
|
||||
async function saveExpress() {
|
||||
if (!selectedOrder.value || !tenantReady.value) return
|
||||
if (!expressForm.expressCompany.trim() || !expressForm.expressTrackingNo.trim()) {
|
||||
ElMessage.warning('请填写快递公司和快递单号')
|
||||
return
|
||||
}
|
||||
expressSaving.value = true
|
||||
try {
|
||||
await updatePlatformFirstLegOrderExpress(loadedTenantId.value, String(selectedOrder.value.id), {
|
||||
expressCompany: expressForm.expressCompany.trim(),
|
||||
expressTrackingNo: expressForm.expressTrackingNo.trim(),
|
||||
})
|
||||
expressDialogOpen.value = false
|
||||
await refreshAfterAction(String(selectedOrder.value.id))
|
||||
ElMessage.success('履约快递信息已保存')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorDetails(error, '履约快递信息保存失败').message)
|
||||
} finally {
|
||||
expressSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openNote(order: PlatformFirstLegOrderResource) {
|
||||
selectedOrder.value = order
|
||||
noteContent.value = ''
|
||||
noteDialogOpen.value = true
|
||||
}
|
||||
|
||||
async function saveNote() {
|
||||
if (!selectedOrder.value || !tenantReady.value) return
|
||||
if (!noteContent.value.trim()) {
|
||||
ElMessage.warning('请填写内部备注')
|
||||
return
|
||||
}
|
||||
noteSaving.value = true
|
||||
try {
|
||||
await addPlatformFirstLegOrderNote(loadedTenantId.value, String(selectedOrder.value.id), noteContent.value.trim())
|
||||
noteDialogOpen.value = false
|
||||
await refreshAfterAction(String(selectedOrder.value.id))
|
||||
ElMessage.success('内部备注已保存')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorDetails(error, '内部备注保存失败').message)
|
||||
} finally {
|
||||
noteSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (tenantId.value) void loadOrders()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<MetricStrip :items="metrics" />
|
||||
|
||||
<section class="surface-panel filter-panel" aria-label="头程订单筛选">
|
||||
<div class="filter-fields server-order-filter-fields">
|
||||
<el-input v-model.trim="tenantId" clearable placeholder="目标租户 ID" aria-label="目标租户 ID" @keyup.enter="loadOrders(true)" />
|
||||
<el-input v-model.trim="filters.keyword" clearable placeholder="订单号或客户名称" aria-label="订单关键词" @keyup.enter="loadOrders(true)">
|
||||
<template #prefix><Search :size="16" /></template>
|
||||
</el-input>
|
||||
<el-select v-model="filters.status" clearable placeholder="全部状态" aria-label="订单状态">
|
||||
<el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
|
||||
</el-select>
|
||||
<el-date-picker v-model="filters.dateRange" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="创建开始" end-placeholder="创建结束" aria-label="订单创建日期" />
|
||||
</div>
|
||||
<div class="filter-actions">
|
||||
<el-button type="primary" plain :loading="loading" @click="loadOrders(true)"><Search :size="16" />查询租户</el-button>
|
||||
<el-button :disabled="loading" @click="resetFilters"><RotateCcw :size="16" />重置筛选</el-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon role="alert">
|
||||
<template #title><div class="api-error-alert-title"><span>{{ loadError.message }}</span><ApiErrorMeta :details="loadError" /></div></template>
|
||||
<el-button v-if="tenantId" link type="danger" @click="loadOrders(true)">重新加载</el-button>
|
||||
</el-alert>
|
||||
<el-alert v-else type="info" :closable="false" show-icon>
|
||||
当前页面已直连 Order 服务。后端尚未提供平台代客创建、平台编辑及履约任务查询接口,因此真实会话不显示这些静态操作。
|
||||
</el-alert>
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading"><div><h2>头程订单</h2><p>{{ loadedTenantId ? `当前数据范围:租户 ${loadedTenantId}` : '输入目标租户 ID 后读取 Order 服务真实数据' }}</p></div></header>
|
||||
<el-table v-if="loading || orders.length" v-loading="loading" :data="orders" row-key="id">
|
||||
<el-table-column label="操作" min-width="200" fixed="left">
|
||||
<template #default="{ row }"><div class="table-actions"><el-button link type="primary" @click="openDetail(row as PlatformFirstLegOrderResource)"><Eye :size="15" />详情</el-button><el-button v-if="actionLabel(row as PlatformFirstLegOrderResource)" link type="success" :loading="actionLoadingId === String((row as PlatformFirstLegOrderResource).id)" @click="runLifecycleAction(row as PlatformFirstLegOrderResource)">{{ actionLabel(row as PlatformFirstLegOrderResource) }}</el-button><el-button v-if="canCancel(row as PlatformFirstLegOrderResource)" link type="danger" :loading="actionLoadingId === String((row as PlatformFirstLegOrderResource).id)" @click="cancelOrder(row as PlatformFirstLegOrderResource)">取消</el-button><el-button v-if="can('platform:order:fulfillment') && !['DRAFT', 'REJECTED', 'CANCELLED'].includes((row as PlatformFirstLegOrderResource).status)" link type="primary" @click="openExpress(row as PlatformFirstLegOrderResource)"><PackageCheck :size="15" />快递</el-button><el-button v-if="can('platform:order:note')" link type="primary" @click="openNote(row as PlatformFirstLegOrderResource)"><FilePenLine :size="15" />备注</el-button></div></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="订单信息" min-width="210"><template #default="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).orderNo || '-' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).referenceId || '无客户参考号' }} · {{ formattedDate((row as PlatformFirstLegOrderResource).createdAt) }}</span></div></template></el-table-column>
|
||||
<el-table-column label="客户" min-width="190" show-overflow-tooltip><template #default="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).customerName }}</strong><span>租户 {{ (row as PlatformFirstLegOrderResource).tenantId }}</span></div></template></el-table-column>
|
||||
<el-table-column label="运输方案" min-width="180"><template #default="{ row }"><div class="primary-cell"><strong>{{ transportLabel(row as PlatformFirstLegOrderResource) }}</strong><span>{{ (row as PlatformFirstLegOrderResource).channelName || '未填写渠道' }}</span></div></template></el-table-column>
|
||||
<el-table-column label="目的地" min-width="150"><template #default="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).destinationWarehouseName || '-' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).destinationCountryCode || '-' }}</span></div></template></el-table-column>
|
||||
<el-table-column label="平台收货仓" min-width="180"><template #default="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).receivingWarehouseName || '-' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).receivingWarehouseAddress || '-' }}</span></div></template></el-table-column>
|
||||
<el-table-column label="履约快递" min-width="160"><template #default="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).expressCompany || '未维护' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).expressTrackingNo || '—' }}</span></div></template></el-table-column>
|
||||
<el-table-column label="状态" width="120"><template #default="{ row }"><StatusBadge :status="statusLabel((row as PlatformFirstLegOrderResource).status)" /></template></el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else :description="loadedTenantId ? '当前租户没有符合条件的头程订单' : '请先输入目标租户 ID 并查询'" />
|
||||
<footer class="table-footer"><span>共 {{ total }} 条</span><el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next" @current-change="handlePageChange" /></footer>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="detailOpen" title="订单详情" size="760px" class="business-drawer">
|
||||
<div v-loading="detailLoading">
|
||||
<template v-if="detail">
|
||||
<div class="order-detail-head"><div><span>{{ transportLabel(detail.order) }}</span><h2>{{ detail.order.orderNo || detail.order.id }}</h2><p>{{ detail.order.customerName }} · {{ detail.order.referenceId || '无客户参考号' }}</p></div><StatusBadge :status="statusLabel(detail.order.status)" /></div>
|
||||
<div class="detail-section"><h3>订单概要</h3><el-descriptions :column="2" border><el-descriptions-item label="目标仓 / 国家">{{ detail.order.destinationWarehouseName || '-' }} · {{ detail.order.destinationCountryCode || '-' }}</el-descriptions-item><el-descriptions-item label="平台收货仓">{{ detail.order.receivingWarehouseName || '-' }}</el-descriptions-item><el-descriptions-item label="收货地址" :span="2">{{ detail.order.receivingWarehouseAddress || '-' }}</el-descriptions-item><el-descriptions-item label="渠道">{{ detail.order.channelName || '-' }}({{ detail.order.channelCode || '-' }})</el-descriptions-item><el-descriptions-item label="预计出运">{{ detail.order.expectedShipDate || '-' }}</el-descriptions-item><el-descriptions-item label="客户备注" :span="2">{{ detail.order.customerRemark || '-' }}</el-descriptions-item></el-descriptions></div>
|
||||
<div class="detail-section"><h3>货物明细</h3><el-table :data="detail.cargoes" size="small" empty-text="暂无货物明细"><el-table-column prop="itemNo" label="#" width="52" /><el-table-column prop="cargoName" label="品名" min-width="150" /><el-table-column prop="packageType" label="包装" min-width="100" /><el-table-column prop="packageCount" label="件/箱" width="86" /><el-table-column label="毛重 / 体积" min-width="150"><template #default="{ row }">{{ row.grossWeightKg }} kg / {{ row.volumeCbm }} m³</template></el-table-column></el-table></div>
|
||||
<div class="detail-section"><h3>收发货方</h3><div class="party-grid"><div v-for="party in detail.parties" :key="party.id"><span>{{ party.partyType === 'SENDER' ? '发货方' : '收货方' }}</span><strong>{{ party.companyName }}</strong><p>{{ party.contactName }} · {{ party.phone }}</p><p>{{ [party.province, party.city, party.district, party.addressLine].filter(Boolean).join(' ') }}</p></div></div></div>
|
||||
<div class="detail-section"><h3>履约快递</h3><el-descriptions :column="2" border><el-descriptions-item label="快递公司">{{ detail.order.expressCompany || '-' }}</el-descriptions-item><el-descriptions-item label="快递单号">{{ detail.order.expressTrackingNo || '-' }}</el-descriptions-item></el-descriptions></div>
|
||||
<div class="detail-section"><h3>内部备注</h3><el-empty v-if="!detail.internalNotes.length" description="暂无内部备注" :image-size="52" /><el-timeline v-else><el-timeline-item v-for="note in detail.internalNotes" :key="note.id" :timestamp="formattedDate(note.createdAt)" placement="top"><p>{{ note.content }}</p></el-timeline-item></el-timeline></div>
|
||||
<div class="detail-section"><h3>状态历史</h3><el-timeline><el-timeline-item v-for="item in detail.statusHistory" :key="item.id" :timestamp="`${formattedDate(item.occurredAt)} · ${item.operatorName || '系统'}`" placement="top"><strong>{{ statusLabel(item.toStatus) }}</strong><p>{{ item.reason || item.action || '状态已更新。' }}</p></el-timeline-item></el-timeline></div>
|
||||
</template>
|
||||
<el-empty v-else-if="!detailLoading" description="订单详情暂不可用" />
|
||||
</div>
|
||||
<template #footer><div class="drawer-footer"><el-button @click="detailOpen = false">关闭</el-button></div></template>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog v-model="expressDialogOpen" title="维护履约快递" width="520px">
|
||||
<el-alert title="当前后端契约只接收快递公司名称和快递单号;快递主数据关联待后端补充。" type="info" :closable="false" show-icon />
|
||||
<el-form label-position="top" class="delivery-form"><el-form-item label="快递公司" required><el-input v-model.trim="expressForm.expressCompany" maxlength="64" placeholder="例如 顺丰速运" /></el-form-item><el-form-item label="快递单号" required><el-input v-model.trim="expressForm.expressTrackingNo" maxlength="128" placeholder="请输入完整快递单号" /></el-form-item></el-form>
|
||||
<template #footer><el-button :disabled="expressSaving" @click="expressDialogOpen = false">取消</el-button><el-button type="primary" :loading="expressSaving" @click="saveExpress">保存快递信息</el-button></template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="noteDialogOpen" title="添加内部备注" width="520px">
|
||||
<el-form label-position="top"><el-form-item label="内部备注" required><el-input v-model.trim="noteContent" maxlength="2000" type="textarea" :rows="4" show-word-limit placeholder="仅平台内部可见" /></el-form-item></el-form>
|
||||
<template #footer><el-button :disabled="noteSaving" @click="noteDialogOpen = false">取消</el-button><el-button type="primary" :loading="noteSaving" @click="saveNote">保存备注</el-button></template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.server-order-filter-fields { grid-template-columns: minmax(150px, .65fr) minmax(220px, 1.2fr) minmax(150px, .75fr) minmax(260px, 1.1fr); }
|
||||
.party-grid p { margin: 4px 0 0; color: var(--cc-muted); font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }
|
||||
@media (max-width: 720px) { .server-order-filter-fields { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
@@ -4,6 +4,7 @@ import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import { nextTick } from 'vue'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { ApiResponseError } from '@/api/http'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
import { useAdminDataStore } from '@/stores/adminData'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
@@ -14,7 +15,7 @@ vi.mock('element-plus', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('element-plus')>()
|
||||
return {
|
||||
...actual,
|
||||
ElMessage: { success: vi.fn(), error: vi.fn() },
|
||||
ElMessage: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },
|
||||
ElMessageBox: { confirm: vi.fn() },
|
||||
}
|
||||
})
|
||||
@@ -86,6 +87,7 @@ describe('AppLayout role preview coordination', () => {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.mocked(ElMessageBox.confirm).mockReset()
|
||||
vi.mocked(ElMessage.success).mockReset()
|
||||
vi.mocked(ElMessage.warning).mockReset()
|
||||
vi.mocked(ElMessage.error).mockReset()
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
@@ -294,7 +296,7 @@ describe('AppLayout role preview coordination', () => {
|
||||
const logout = auth.logout
|
||||
vi.spyOn(access, 'reset').mockImplementation(() => { calls.push('access'); resetAccess() })
|
||||
vi.spyOn(unsaved, 'clear').mockImplementation(() => { calls.push('unsaved'); clearUnsaved() })
|
||||
vi.spyOn(auth, 'logout').mockImplementation(() => { calls.push('auth'); logout() })
|
||||
vi.spyOn(auth, 'logout').mockImplementation(() => { calls.push('auth'); return logout() })
|
||||
const replace = vi.spyOn(router, 'replace')
|
||||
|
||||
await wrapper.get('[aria-label="退出登录"]').trigger('click')
|
||||
@@ -320,4 +322,20 @@ describe('AppLayout role preview coordination', () => {
|
||||
expect(router.currentRoute.value.path).toBe('/')
|
||||
expect(router.replace).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the local logout and reports server revocation failure with a tracking id', async () => {
|
||||
vi.mocked(ElMessageBox.confirm).mockResolvedValueOnce({} as never)
|
||||
const { wrapper, router, auth } = await mountLayout('/')
|
||||
vi.spyOn(auth, 'logout').mockImplementation(async () => {
|
||||
auth.token = ''
|
||||
auth.refreshToken = ''
|
||||
throw new ApiResponseError('服务不可用', 'S0503', 503, undefined, 'request-logout')
|
||||
})
|
||||
|
||||
await wrapper.get('[aria-label="退出登录"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
expect(ElMessage.warning).toHaveBeenCalledWith('本地已退出,但服务器会话撤销失败(追踪标识:request-logout)')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Menu,
|
||||
} from '@lucide/vue'
|
||||
import { PRODUCT_NAME } from '@chongchong/shared'
|
||||
import { getApiErrorDetails } from '@/api/http'
|
||||
import AdminSidebarMenu from '@/components/AdminSidebarMenu.vue'
|
||||
import RolePreviewSwitcher from '@/components/RolePreviewSwitcher.vue'
|
||||
import { resolvePreviewTarget } from '@/router/accessDecision'
|
||||
@@ -169,7 +170,13 @@ async function handleLogout() {
|
||||
loggingOut.value = true
|
||||
access.reset()
|
||||
unsaved.clear()
|
||||
auth.logout()
|
||||
try {
|
||||
await auth.logout()
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '服务器会话撤销失败')
|
||||
const trackingId = details.requestId || details.traceId
|
||||
ElMessage.warning(`本地已退出,但服务器会话撤销失败${trackingId ? `(追踪标识:${trackingId})` : ''}`)
|
||||
}
|
||||
try {
|
||||
await router.replace('/login')
|
||||
} catch {
|
||||
|
||||
+25
-1
@@ -1,11 +1,35 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import 'element-plus/es/components/message/style/css'
|
||||
import 'element-plus/es/components/message-box/style/css'
|
||||
import App from './App.vue'
|
||||
import { registerAuthSessionExpiredHandler } from '@/api/http'
|
||||
import router from './router'
|
||||
import { sanitizeInternalPath } from '@/router/accessDecision'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useUnsavedWorkStore } from '@/stores/unsavedWork'
|
||||
import './styles/index.css'
|
||||
|
||||
createApp(App).use(createPinia()).use(router).mount('#app')
|
||||
const pinia = createPinia()
|
||||
const auth = useAuthStore(pinia)
|
||||
|
||||
await auth.restoreSession()
|
||||
|
||||
registerAuthSessionExpiredHandler(async () => {
|
||||
const currentRoute = router.currentRoute.value
|
||||
if (currentRoute.name === 'login') return
|
||||
|
||||
useAccessPreviewStore(pinia).reset()
|
||||
useUnsavedWorkStore(pinia).clear()
|
||||
const redirect = sanitizeInternalPath(currentRoute.fullPath)
|
||||
ElMessage.warning('登录状态已过期,请重新登录')
|
||||
await router.replace({
|
||||
name: 'login',
|
||||
query: redirect === '/' ? undefined : { redirect },
|
||||
})
|
||||
})
|
||||
|
||||
createApp(App).use(pinia).use(router).mount('#app')
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
listCurrentPlatformPermissionCodes: vi.fn(),
|
||||
refreshHandler: null as null | (() => Promise<string>),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/http', () => ({
|
||||
http: { post: mocks.post },
|
||||
registerAuthRefreshHandler: (handler: () => Promise<string>) => { mocks.refreshHandler = handler },
|
||||
unwrapApiResponse: <T>(response: { code: string; message: string; data: T }) => {
|
||||
if (response.code !== '0') throw new Error(response.message)
|
||||
return response.data
|
||||
},
|
||||
getApiErrorDetails: (error: { code?: string; message?: string }) => ({
|
||||
message: error.message || '接口请求失败',
|
||||
code: error.code,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/platformIam', () => ({
|
||||
listCurrentPlatformPermissionCodes: mocks.listCurrentPlatformPermissionCodes,
|
||||
}))
|
||||
|
||||
import { useAuthStore } from './auth'
|
||||
|
||||
function createMemoryStorage(): Storage {
|
||||
const values = new Map<string, string>()
|
||||
return {
|
||||
get length() { return values.size },
|
||||
clear: () => values.clear(),
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
key: (index) => [...values.keys()][index] ?? null,
|
||||
removeItem: (key) => values.delete(key),
|
||||
setItem: (key, value) => values.set(key, value),
|
||||
}
|
||||
}
|
||||
|
||||
function token(overrides: Record<string, unknown> = {}) {
|
||||
const claims = {
|
||||
user_id: '1000001',
|
||||
username: 'platform_admin',
|
||||
app_code: 'PLATFORM',
|
||||
roles: ['PLATFORM_ADMIN'],
|
||||
permissions: ['platform:warehouse:list', 'platform:order:list'],
|
||||
exp: Math.floor(Date.now() / 1000) + 1800,
|
||||
...overrides,
|
||||
}
|
||||
const payload = Buffer.from(JSON.stringify(claims)).toString('base64url')
|
||||
return `header.${payload}.signature`
|
||||
}
|
||||
|
||||
function loginResponse(accessToken = token(), refreshToken = 'refresh-next') {
|
||||
return {
|
||||
code: '0',
|
||||
message: 'success',
|
||||
data: {
|
||||
tokenType: 'Bearer',
|
||||
accessToken,
|
||||
expiresIn: 1800,
|
||||
refreshToken,
|
||||
refreshExpiresIn: 604800,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('admin auth session', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
setActivePinia(createPinia())
|
||||
mocks.post.mockReset()
|
||||
mocks.listCurrentPlatformPermissionCodes.mockReset()
|
||||
mocks.refreshHandler = null
|
||||
})
|
||||
|
||||
it('intersects JWT permissions with the current authenticated permission snapshot', async () => {
|
||||
mocks.post.mockResolvedValue(loginResponse())
|
||||
mocks.listCurrentPlatformPermissionCodes.mockResolvedValue(['platform:warehouse:list'])
|
||||
const auth = useAuthStore()
|
||||
|
||||
await auth.login('warehouse_operator', 'password')
|
||||
|
||||
expect(auth.isAuthenticated).toBe(true)
|
||||
expect([...auth.permissionCodes]).toEqual(['platform:warehouse:list'])
|
||||
expect(auth.permissionResources).toEqual([])
|
||||
expect(localStorage.getItem('cc-admin-permission-codes'))
|
||||
.toBe('["platform:warehouse:list"]')
|
||||
})
|
||||
|
||||
it('rejects login and clears the session when the current permission snapshot is unavailable', async () => {
|
||||
mocks.post.mockResolvedValue(loginResponse())
|
||||
mocks.listCurrentPlatformPermissionCodes.mockRejectedValue({ code: 'S0503', message: 'IAM 服务不可用' })
|
||||
const auth = useAuthStore()
|
||||
|
||||
await expect(auth.login('platform_admin', 'password')).rejects.toMatchObject({ code: 'S0503' })
|
||||
expect(auth.isAuthenticated).toBe(false)
|
||||
expect(localStorage.getItem('cc-admin-token')).toBeNull()
|
||||
expect(localStorage.getItem('cc-admin-refresh-token')).toBeNull()
|
||||
})
|
||||
|
||||
it('revokes an issued token pair when the permission snapshot prevents login completion', async () => {
|
||||
mocks.post
|
||||
.mockResolvedValueOnce(loginResponse())
|
||||
.mockResolvedValueOnce({ code: '0', message: 'success', data: null })
|
||||
mocks.listCurrentPlatformPermissionCodes.mockRejectedValue({ code: 'S0503', message: 'IAM 服务不可用' })
|
||||
const auth = useAuthStore()
|
||||
|
||||
await expect(auth.login('platform_admin', 'password')).rejects.toMatchObject({ code: 'S0503' })
|
||||
await Promise.resolve()
|
||||
|
||||
expect(mocks.post).toHaveBeenNthCalledWith(2, '/auth/logout', { refreshToken: 'refresh-next' }, {
|
||||
headers: { Authorization: expect.stringContaining('Bearer header.') },
|
||||
})
|
||||
})
|
||||
|
||||
it('restores an expired access session with the persisted refresh token', async () => {
|
||||
localStorage.setItem('cc-admin-token', token({ exp: Math.floor(Date.now() / 1000) - 30 }))
|
||||
localStorage.setItem('cc-admin-refresh-token', 'refresh-old')
|
||||
mocks.post.mockResolvedValue(loginResponse(token(), 'refresh-rotated'))
|
||||
mocks.listCurrentPlatformPermissionCodes.mockResolvedValue(['platform:warehouse:list'])
|
||||
const auth = useAuthStore()
|
||||
|
||||
await expect(auth.restoreSession()).resolves.toBe(true)
|
||||
|
||||
expect(mocks.post).toHaveBeenCalledWith('/auth/refresh', { refreshToken: 'refresh-old' })
|
||||
expect(auth.refreshToken).toBe('refresh-rotated')
|
||||
expect(auth.isAuthenticated).toBe(true)
|
||||
})
|
||||
|
||||
it('does not let an in-flight refresh restore a session after logout', async () => {
|
||||
localStorage.setItem('cc-admin-token', token())
|
||||
localStorage.setItem('cc-admin-refresh-token', 'refresh-old')
|
||||
let resolveRefresh: ((value: ReturnType<typeof loginResponse>) => void) | undefined
|
||||
mocks.post.mockImplementation((url: string) => {
|
||||
if (url === '/auth/refresh') {
|
||||
return new Promise((resolve) => { resolveRefresh = resolve })
|
||||
}
|
||||
return Promise.resolve({ code: '0', message: 'success', data: null })
|
||||
})
|
||||
const auth = useAuthStore()
|
||||
|
||||
const refreshing = auth.refreshSession()
|
||||
await Promise.resolve()
|
||||
await auth.logout()
|
||||
resolveRefresh?.(loginResponse(token(), 'refresh-rotated'))
|
||||
|
||||
await expect(refreshing).rejects.toThrow('登录会话已被后续操作替代')
|
||||
expect(auth.isAuthenticated).toBe(false)
|
||||
expect(auth.refreshToken).toBe('')
|
||||
expect(localStorage.getItem('cc-admin-token')).toBeNull()
|
||||
})
|
||||
})
|
||||
+79
-26
@@ -1,8 +1,13 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import type { CurrentUser } from '@chongchong/shared'
|
||||
import { http, registerAuthRefreshHandler, unwrapApiResponse, type ApiEnvelope } from '@/api/http'
|
||||
import { listPlatformPermissions, type PlatformPermissionResource } from '@/api/platformIam'
|
||||
import {
|
||||
http,
|
||||
registerAuthRefreshHandler,
|
||||
unwrapApiResponse,
|
||||
type ApiEnvelope,
|
||||
} from '@/api/http'
|
||||
import { listCurrentPlatformPermissionCodes, type PlatformPermissionResource } from '@/api/platformIam'
|
||||
import { decodeJwtClaims } from '@/utils/jwt'
|
||||
|
||||
const TOKEN_KEY = 'cc-admin-token'
|
||||
@@ -17,10 +22,13 @@ interface LoginResponse {
|
||||
refreshExpiresIn: number
|
||||
}
|
||||
|
||||
class ExpiredAccessTokenError extends Error {}
|
||||
class SupersededSessionError extends Error {}
|
||||
|
||||
function sessionFromToken(token: string) {
|
||||
const claims = decodeJwtClaims(token)
|
||||
if (claims.app_code !== 'PLATFORM') throw new Error('账号不属于当前应用端')
|
||||
if (claims.exp && claims.exp * 1000 <= Date.now()) throw new Error('登录状态已过期,请重新登录')
|
||||
if (claims.exp && claims.exp * 1000 <= Date.now()) throw new ExpiredAccessTokenError('登录状态已过期')
|
||||
return {
|
||||
user: {
|
||||
id: String(claims.user_id ?? ''),
|
||||
@@ -39,6 +47,7 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
const permissions = ref<string[]>([])
|
||||
const permissionResources = ref<PlatformPermissionResource[]>([])
|
||||
const isServerSession = ref(false)
|
||||
let sessionGeneration = 0
|
||||
|
||||
if (token.value) {
|
||||
try {
|
||||
@@ -48,20 +57,34 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
user.value = session.user
|
||||
permissions.value = session.permissions.filter((code) => cachedPermissions.includes(code))
|
||||
isServerSession.value = true
|
||||
} catch {
|
||||
} catch (error) {
|
||||
token.value = ''
|
||||
refreshToken.value = ''
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
localStorage.removeItem(PERMISSION_CODES_KEY)
|
||||
if (!(error instanceof ExpiredAccessTokenError) || !refreshToken.value) {
|
||||
refreshToken.value = ''
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isAuthenticated = computed(() => Boolean(token.value))
|
||||
const permissionCodes = computed<ReadonlySet<string>>(() => new Set(permissions.value))
|
||||
|
||||
async function applySession(result: LoginResponse) {
|
||||
function ensureCurrentGeneration(expectedGeneration: number) {
|
||||
if (expectedGeneration !== sessionGeneration) {
|
||||
throw new SupersededSessionError('登录会话已被后续操作替代')
|
||||
}
|
||||
}
|
||||
|
||||
function applyPermissionCodes(codes: string[]) {
|
||||
permissions.value = codes
|
||||
localStorage.setItem(PERMISSION_CODES_KEY, JSON.stringify(codes))
|
||||
}
|
||||
|
||||
async function applySession(result: LoginResponse, expectedGeneration: number) {
|
||||
const session = sessionFromToken(result.accessToken)
|
||||
ensureCurrentGeneration(expectedGeneration)
|
||||
token.value = result.accessToken
|
||||
refreshToken.value = result.refreshToken
|
||||
user.value = session.user
|
||||
@@ -69,19 +92,19 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
localStorage.setItem(TOKEN_KEY, token.value)
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken.value)
|
||||
try {
|
||||
permissionResources.value = await listPlatformPermissions()
|
||||
const activeResourceCodes = new Set(permissionResources.value
|
||||
.filter((resource) => resource.status === 'ACTIVE')
|
||||
.map((resource) => resource.permissionCode))
|
||||
permissions.value = session.permissions.filter((code) => activeResourceCodes.has(code))
|
||||
localStorage.setItem(PERMISSION_CODES_KEY, JSON.stringify(permissions.value))
|
||||
const activePermissionCodes = await listCurrentPlatformPermissionCodes()
|
||||
ensureCurrentGeneration(expectedGeneration)
|
||||
permissionResources.value = []
|
||||
const activePermissionCodeSet = new Set(activePermissionCodes)
|
||||
applyPermissionCodes(session.permissions.filter((code) => activePermissionCodeSet.has(code)))
|
||||
} catch (error) {
|
||||
clearSession()
|
||||
ensureCurrentGeneration(expectedGeneration)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
sessionGeneration += 1
|
||||
token.value = ''
|
||||
refreshToken.value = ''
|
||||
user.value = null
|
||||
@@ -93,44 +116,73 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
localStorage.removeItem(PERMISSION_CODES_KEY)
|
||||
}
|
||||
|
||||
async function revokeTokenPair(accessToken: string, refreshTokenToRevoke: string) {
|
||||
await http.post('/auth/logout', { refreshToken: refreshTokenToRevoke }, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
})
|
||||
}
|
||||
|
||||
async function login(account: string, password: string) {
|
||||
const response = await http.post<ApiEnvelope<LoginResponse>, ApiEnvelope<LoginResponse>>(
|
||||
'/auth/login',
|
||||
{ username: account, password },
|
||||
)
|
||||
const result = unwrapApiResponse<LoginResponse>(response)
|
||||
await applySession(result)
|
||||
const expectedGeneration = ++sessionGeneration
|
||||
try {
|
||||
const response = await http.post<ApiEnvelope<LoginResponse>, ApiEnvelope<LoginResponse>>(
|
||||
'/auth/login',
|
||||
{ username: account, password },
|
||||
)
|
||||
const result = unwrapApiResponse<LoginResponse>(response)
|
||||
await applySession(result, expectedGeneration)
|
||||
} catch (error) {
|
||||
if (expectedGeneration === sessionGeneration) {
|
||||
const issuedAccessToken = token.value
|
||||
const issuedRefreshToken = refreshToken.value
|
||||
clearSession()
|
||||
if (issuedAccessToken && issuedRefreshToken) {
|
||||
void revokeTokenPair(issuedAccessToken, issuedRefreshToken).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshSession() {
|
||||
if (!refreshToken.value) throw new Error('刷新令牌不存在,请重新登录')
|
||||
const expectedGeneration = sessionGeneration
|
||||
try {
|
||||
const response = await http.post<ApiEnvelope<LoginResponse>, ApiEnvelope<LoginResponse>>(
|
||||
'/auth/refresh',
|
||||
{ refreshToken: refreshToken.value },
|
||||
)
|
||||
const result = unwrapApiResponse<LoginResponse>(response)
|
||||
await applySession(result)
|
||||
await applySession(result, expectedGeneration)
|
||||
} catch (error) {
|
||||
clearSession()
|
||||
if (expectedGeneration === sessionGeneration) clearSession()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreSession() {
|
||||
if (isAuthenticated.value) return true
|
||||
if (!refreshToken.value) return false
|
||||
try {
|
||||
await refreshSession()
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
registerAuthRefreshHandler(async () => {
|
||||
await refreshSession()
|
||||
if (!token.value) throw new Error('登录状态刷新失败')
|
||||
return token.value
|
||||
})
|
||||
|
||||
function logout() {
|
||||
async function logout() {
|
||||
const accessToken = token.value
|
||||
const tokenToRevoke = refreshToken.value
|
||||
clearSession()
|
||||
if (accessToken && tokenToRevoke) {
|
||||
void http.post('/auth/logout', { refreshToken: tokenToRevoke }, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
}).catch(() => undefined)
|
||||
await revokeTokenPair(accessToken, tokenToRevoke)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +197,7 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
isAuthenticated,
|
||||
login,
|
||||
refreshSession,
|
||||
restoreSession,
|
||||
logout,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -13,6 +13,15 @@ import RolesView from './RolesView.vue'
|
||||
import WarehousesView from './WarehousesView.vue'
|
||||
import { useAdminDataStore } from '@/stores/adminData'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { getPlatformWarehouse, listPlatformWarehouses } from '@/api/platformWarehouses'
|
||||
|
||||
vi.mock('@/api/platformWarehouses', () => ({
|
||||
listPlatformWarehouses: vi.fn(),
|
||||
getPlatformWarehouse: vi.fn(),
|
||||
createPlatformWarehouse: vi.fn(),
|
||||
updatePlatformWarehouse: vi.fn(),
|
||||
changePlatformWarehouseStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
@@ -74,8 +83,28 @@ afterAll(() => vi.unstubAllGlobals())
|
||||
describe('business action permissions', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||
sessionStorage.setItem('cc-admin-warehouse-tenant-id', '10001')
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
document.body.innerHTML = ''
|
||||
const warehouse = {
|
||||
id: '19001', tenantId: 10001, warehouseCode: 'CN-TEST-01', warehouseName: '测试收货仓',
|
||||
warehouseType: 'DOMESTIC', countryCode: 'CN', timezone: 'Asia/Shanghai', contactName: '仓库客服',
|
||||
contactPhone: '0579-12345678', contactEmail: null, status: 'ACTIVE' as const, remark: null,
|
||||
}
|
||||
vi.mocked(listPlatformWarehouses).mockResolvedValue({ records: [warehouse], page: 1, size: 200, total: 1, pages: 1 })
|
||||
vi.mocked(getPlatformWarehouse).mockResolvedValue({
|
||||
warehouse,
|
||||
addresses: [{
|
||||
id: '19002', tenantId: 10001, warehouseId: '19001', addressType: 'OPERATING', countryCode: 'CN',
|
||||
stateProvince: '浙江省', city: '义乌市', district: null, postalCode: null, addressLine1: '测试地址',
|
||||
addressLine2: null, latitude: null, longitude: null,
|
||||
}],
|
||||
capabilities: [{
|
||||
id: '19003', tenantId: 10001, warehouseId: '19001', capabilityCode: 'RECEIVING', capabilityName: '收货服务',
|
||||
enabled: true, cutoffTime: null, description: '周一至周六 08:30-18:00',
|
||||
}],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps review actions out of customer records now that reviews use a dedicated route', async () => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ElMessage } from 'element-plus'
|
||||
import { ClipboardCheck, Download, Eye, PackageCheck, Pencil, Plus, RotateCcw, Search, Ship, UserRoundCheck } from '@lucide/vue'
|
||||
import { FIRST_LEG_ORDER_STATUSES } from '@chongchong/shared'
|
||||
import MetricStrip from '@/components/MetricStrip.vue'
|
||||
import PlatformFirstLegOrdersPanel from '@/components/PlatformFirstLegOrdersPanel.vue'
|
||||
import StatusBadge from '@/components/StatusBadge.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/composables/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
@@ -172,7 +173,8 @@ function exportOrders() { ElMessage.success(`已生成 ${filteredRows.value.leng
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<PlatformFirstLegOrdersPanel v-if="access.usesServerPermissions" />
|
||||
<div v-else class="business-page">
|
||||
<MetricStrip :items="metrics" />
|
||||
<section class="surface-panel filter-panel order-filter" aria-label="头程订单筛选">
|
||||
<div class="filter-fields">
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { flushPromises, shallowMount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPlatformRole, listPlatformRoles, type PlatformRoleResource } from '@/api/platformIam'
|
||||
import { createPlatformRole, listPlatformPermissions, listPlatformRoles, type PlatformRoleResource } from '@/api/platformIam'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import RolesView from './RolesView.vue'
|
||||
|
||||
vi.mock('@/api/platformIam', () => ({
|
||||
createPlatformRole: vi.fn(),
|
||||
listPlatformPermissions: vi.fn(),
|
||||
listPlatformRoles: vi.fn(),
|
||||
updatePlatformRole: vi.fn(),
|
||||
changePlatformRoleStatus: vi.fn(),
|
||||
deletePlatformRole: vi.fn(),
|
||||
replacePlatformRolePermissions: vi.fn(),
|
||||
}))
|
||||
|
||||
const platformRole: PlatformRoleResource = {
|
||||
@@ -57,6 +62,8 @@ describe('RolesView', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(listPlatformRoles).mockReset()
|
||||
vi.mocked(listPlatformPermissions).mockReset()
|
||||
vi.mocked(listPlatformPermissions).mockResolvedValue([])
|
||||
vi.mocked(createPlatformRole).mockReset()
|
||||
})
|
||||
|
||||
@@ -78,7 +85,7 @@ describe('RolesView', () => {
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformRoles).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.text()).toContain('角色列表和新增角色已接入 IAM')
|
||||
expect(wrapper.text()).toContain('角色查询、新增、编辑、启停、删除及权限分配均使用 IAM 真实接口')
|
||||
expect(wrapper.find('[data-testid="permission-tree"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
|
||||
+72
-29
@@ -2,7 +2,16 @@
|
||||
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Pencil, Plus, RotateCcw, Search, ShieldCheck, Trash2 } from '@lucide/vue'
|
||||
import { createPlatformRole, listPlatformRoles, type PlatformRoleResource } from '@/api/platformIam'
|
||||
import {
|
||||
changePlatformRoleStatus,
|
||||
createPlatformRole,
|
||||
deletePlatformRole,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
replacePlatformRolePermissions,
|
||||
updatePlatformRole,
|
||||
type PlatformRoleResource,
|
||||
} from '@/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/api/http'
|
||||
import ApiErrorMeta from '@/components/ApiErrorMeta.vue'
|
||||
import MetricStrip from '@/components/MetricStrip.vue'
|
||||
@@ -10,8 +19,9 @@ import StatusBadge from '@/components/StatusBadge.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/composables/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
import { useAdminDataStore } from '@/stores/adminData'
|
||||
import type { DataScope, Role } from '@/types/admin'
|
||||
import type { DataScope, Permission, Role } from '@/types/admin'
|
||||
import { buildPermissionTree, summarizePermissionSelection } from '@/utils/permissionTree'
|
||||
import { mapPlatformPermission } from '@/utils/platformPermission'
|
||||
|
||||
interface TreeController {
|
||||
getCheckedKeys: (leafOnly?: boolean) => Array<string | number>
|
||||
@@ -24,14 +34,20 @@ const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const treeRef = ref<TreeController | null>(null)
|
||||
const serverRoles = ref<Role[]>([])
|
||||
const serverPermissions = ref<Permission[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const rowActionId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const filters = reactive({ keyword: '', status: '', dataScope: '' })
|
||||
const emptyForm = (): Omit<Role, 'userCount'> => ({ id: '', name: '', code: '', description: '', dataScope: '本部门数据', status: '启用', permissionIds: [], builtIn: false })
|
||||
const form = reactive(emptyForm())
|
||||
const editorLabel = computed(() => form.id ? '配置角色' : '新增角色')
|
||||
const requiredPermission = computed(() => access.usesServerPermissions ? 'platform:role:create' : 'system:role:grant')
|
||||
const canEdit = computed(() => access.can('platform:role:edit'))
|
||||
const canGrant = computed(() => access.can('platform:role:grant'))
|
||||
const requiredPermission = computed(() => access.usesServerPermissions
|
||||
? (form.id && canEdit.value ? 'platform:role:edit' : form.id ? 'platform:role:grant' : 'platform:role:create')
|
||||
: 'system:role:grant')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'role-editor',
|
||||
label: editorLabel,
|
||||
@@ -51,9 +67,10 @@ const metrics = computed(() => [
|
||||
{ label: '角色总数', value: roles.value.length, note: access.usesServerPermissions ? 'IAM 返回的角色' : '平台角色模型' },
|
||||
{ label: '启用角色', value: roles.value.filter((item) => item.status === '启用').length, note: '当前可分配' },
|
||||
{ label: '授权用户', value: access.usesServerPermissions ? '—' : store.users.length, note: access.usesServerPermissions ? '成员关系待接口回显' : '已分配平台角色' },
|
||||
{ label: '权限资源', value: access.usesServerPermissions ? '—' : store.permissions.length, note: access.usesServerPermissions ? '角色授权待接口回显' : '菜单、按钮与接口' },
|
||||
{ label: '权限资源', value: access.usesServerPermissions ? serverPermissions.value.length : store.permissions.length, note: '菜单、按钮与接口' },
|
||||
])
|
||||
const permissionTree = computed(() => buildPermissionTree(store.permissions))
|
||||
const availablePermissions = computed(() => access.usesServerPermissions ? serverPermissions.value : store.permissions)
|
||||
const permissionTree = computed(() => buildPermissionTree(availablePermissions.value))
|
||||
|
||||
watch(() => form.dataScope, () => undefined)
|
||||
|
||||
@@ -68,7 +85,7 @@ function mapPlatformRole(role: PlatformRoleResource): Role {
|
||||
userCount: 0,
|
||||
dataScope: '全部数据',
|
||||
status: role.status === 'ACTIVE' ? '启用' : '停用',
|
||||
permissionIds: [],
|
||||
permissionIds: (role.permissionIds ?? []).map(String),
|
||||
builtIn: role.roleType === 'SYSTEM',
|
||||
}
|
||||
}
|
||||
@@ -78,8 +95,11 @@ async function loadRoles() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
serverRoles.value = []
|
||||
serverPermissions.value = []
|
||||
try {
|
||||
serverRoles.value = (await listPlatformRoles()).map(mapPlatformRole)
|
||||
const [roleRecords, permissionRecords] = await Promise.all([listPlatformRoles(), listPlatformPermissions()])
|
||||
serverPermissions.value = permissionRecords.map(mapPlatformPermission)
|
||||
serverRoles.value = roleRecords.map(mapPlatformRole)
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '平台角色列表加载失败,请稍后重试')
|
||||
} finally {
|
||||
@@ -94,7 +114,7 @@ function openCreate() {
|
||||
nextTick(() => treeRef.value?.setCheckedKeys([]))
|
||||
}
|
||||
function openEdit(row: Role) {
|
||||
if (access.usesServerPermissions) return
|
||||
if (access.usesServerPermissions && !canEdit.value && !canGrant.value) return
|
||||
Object.assign(form, { ...row, permissionIds: [...row.permissionIds] })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
@@ -119,14 +139,23 @@ async function saveRole() {
|
||||
if (access.usesServerPermissions) {
|
||||
saving.value = true
|
||||
try {
|
||||
const created = await createPlatformRole({
|
||||
roleCode: normalizedCode,
|
||||
roleName: form.name.trim(),
|
||||
description: form.description.trim(),
|
||||
})
|
||||
serverRoles.value.unshift(mapPlatformRole(created))
|
||||
const permissionIds = selectedPermissionIds()
|
||||
if (form.id) {
|
||||
if (canEdit.value) {
|
||||
await updatePlatformRole(form.id, { roleName: form.name.trim(), description: form.description.trim() })
|
||||
}
|
||||
if (canGrant.value) await replacePlatformRolePermissions(form.id, permissionIds)
|
||||
} else {
|
||||
const created = await createPlatformRole({
|
||||
roleCode: normalizedCode,
|
||||
roleName: form.name.trim(),
|
||||
description: form.description.trim(),
|
||||
})
|
||||
if (canGrant.value && permissionIds.length > 0) await replacePlatformRolePermissions(created.id, permissionIds)
|
||||
}
|
||||
await loadRoles()
|
||||
editorOpen.value = false
|
||||
ElMessage.success('角色已创建')
|
||||
ElMessage.success(form.id ? '角色已更新' : '角色已创建')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '角色创建失败,请稍后重试'))
|
||||
} finally {
|
||||
@@ -146,9 +175,17 @@ async function removeRole(row: Role) {
|
||||
if (row.userCount > 0) { ElMessage.warning('请先移除该角色下的用户'); return }
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除角色“${row.name}”吗?`, '删除角色', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
|
||||
if (store.removeRole(row.id)) ElMessage.success('角色已删除')
|
||||
} catch {
|
||||
// 用户取消,不需要反馈。
|
||||
if (access.usesServerPermissions) {
|
||||
rowActionId.value = row.id
|
||||
await deletePlatformRole(row.id)
|
||||
serverRoles.value = serverRoles.value.filter((item) => item.id !== row.id)
|
||||
ElMessage.success('角色已删除')
|
||||
} else if (store.removeRole(row.id)) ElMessage.success('角色已删除')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '角色删除失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,16 +194,22 @@ async function toggleStatus(row: Role) {
|
||||
const target = row.status === '启用' ? '停用' : '启用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${target}角色“${row.name}”吗?`, '角色状态', { confirmButtonText: '确认', cancelButtonText: '取消' })
|
||||
store.saveRole({ ...row, status: target })
|
||||
if (access.usesServerPermissions) {
|
||||
rowActionId.value = row.id
|
||||
const updated = await changePlatformRoleStatus(row.id, target === '启用' ? 'ACTIVE' : 'DISABLED')
|
||||
Object.assign(row, mapPlatformRole(updated))
|
||||
} else store.saveRole({ ...row, status: target })
|
||||
ElMessage.success(`角色已${target}`)
|
||||
} catch {
|
||||
// 用户取消,不需要反馈。
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '角色状态更新失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function permissionSummary(row: Role) {
|
||||
if (access.usesServerPermissions) return '待授权回显接口'
|
||||
const { menuCount, actionCount } = summarizePermissionSelection(store.permissions, row.permissionIds)
|
||||
const { menuCount, actionCount } = summarizePermissionSelection(availablePermissions.value, row.permissionIds)
|
||||
return `${menuCount} 菜单 · ${actionCount} 操作`
|
||||
}
|
||||
|
||||
@@ -176,7 +219,7 @@ onMounted(loadRoles)
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<MetricStrip :items="metrics" />
|
||||
<el-alert v-if="access.usesServerPermissions" type="warning" :closable="false" show-icon title="角色列表和新增角色已接入 IAM;编辑、启停、删除及已有权限回显接口尚未提供,相关操作暂不开放。" />
|
||||
<el-alert v-if="access.usesServerPermissions" type="success" :closable="false" show-icon title="角色查询、新增、编辑、启停、删除及权限分配均使用 IAM 真实接口;系统内置角色继续由服务端保护。" />
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon role="alert"><template #title><div class="api-error-alert-title"><span>{{ loadError.message }}</span><ApiErrorMeta :details="loadError" /></div><el-button link type="danger" @click="loadRoles">重新加载</el-button></template></el-alert>
|
||||
<section class="surface-panel filter-panel" aria-label="角色筛选">
|
||||
<div class="filter-fields"><el-input v-model="filters.keyword" clearable placeholder="角色名称、编码或描述" aria-label="角色关键词"><template #prefix><Search :size="16" /></template></el-input><el-select v-if="!access.usesServerPermissions" v-model="filters.dataScope" clearable placeholder="全部数据范围" aria-label="数据范围"><el-option v-for="item in ['全部数据','本部门数据','本人数据','自定义']" :key="item" :label="item" :value="item" /></el-select><el-select v-model="filters.status" clearable placeholder="全部状态" aria-label="角色状态"><el-option label="启用" value="启用" /><el-option label="停用" value="停用" /></el-select></div>
|
||||
@@ -186,10 +229,10 @@ onMounted(loadRoles)
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading"><div><h2>角色与授权</h2><p>角色负责聚合菜单、操作和数据范围,内部用户可分配多个角色。</p></div></header>
|
||||
<el-table v-loading="loading" :data="filteredRows" row-key="id" empty-text="没有符合条件的角色">
|
||||
<el-table-column label="操作" width="235" fixed="left"><template #default="{ row }"><span v-if="access.usesServerPermissions" class="secondary-text">接口待补齐</span><div v-else-if="access.can('system:role:grant')" class="table-actions"><el-button link type="primary" @click="openEdit(row as Role)"><Pencil :size="15" />配置</el-button><el-button link :type="row.status === '启用' ? 'danger' : 'success'" :disabled="row.builtIn" @click="toggleStatus(row as Role)">{{ row.status === '启用' ? '停用' : '启用' }}</el-button><el-button link type="danger" :disabled="row.builtIn || row.userCount > 0" @click="removeRole(row as Role)"><Trash2 :size="15" />删除</el-button></div></template></el-table-column>
|
||||
<el-table-column label="操作" width="235" fixed="left"><template #default="{ row }"><div v-if="access.usesServerPermissions && (canEdit || canGrant || access.can('platform:role:status') || access.can('platform:role:delete'))" class="table-actions"><el-button v-if="canEdit || canGrant" link type="primary" :disabled="rowActionId === row.id || row.builtIn" @click="openEdit(row as Role)"><Pencil :size="15" />配置</el-button><el-button v-if="access.can('platform:role:status')" link :type="row.status === '启用' ? 'danger' : 'success'" :loading="rowActionId === row.id" :disabled="row.builtIn" @click="toggleStatus(row as Role)">{{ row.status === '启用' ? '停用' : '启用' }}</el-button><el-button v-if="access.can('platform:role:delete')" link type="danger" :disabled="row.builtIn || row.userCount > 0 || rowActionId === row.id" @click="removeRole(row as Role)"><Trash2 :size="15" />删除</el-button></div><span v-else-if="access.usesServerPermissions" class="secondary-text">仅查看</span><div v-else-if="access.can('system:role:grant')" class="table-actions"><el-button link type="primary" @click="openEdit(row as Role)"><Pencil :size="15" />配置</el-button><el-button link :type="row.status === '启用' ? 'danger' : 'success'" :disabled="row.builtIn" @click="toggleStatus(row as Role)">{{ row.status === '启用' ? '停用' : '启用' }}</el-button><el-button link type="danger" :disabled="row.builtIn || row.userCount > 0" @click="removeRole(row as Role)"><Trash2 :size="15" />删除</el-button></div></template></el-table-column>
|
||||
<el-table-column label="角色" min-width="210"><template #default="{ row }"><div class="role-cell"><span><ShieldCheck :size="18" /></span><div><strong>{{ row.name }}</strong><small>{{ row.code }}</small></div></div></template></el-table-column>
|
||||
<el-table-column prop="description" label="说明" min-width="240" show-overflow-tooltip />
|
||||
<el-table-column label="授权范围" min-width="170"><template #default="{ row }"><div class="primary-cell"><strong>{{ permissionSummary(row as Role) }}</strong><span>{{ access.usesServerPermissions ? '数据范围待接口提供' : row.dataScope }}</span></div></template></el-table-column>
|
||||
<el-table-column label="授权范围" min-width="170"><template #default="{ row }"><div class="primary-cell"><strong>{{ permissionSummary(row as Role) }}</strong><span>{{ access.usesServerPermissions ? '平台 IAM 权限' : row.dataScope }}</span></div></template></el-table-column>
|
||||
<el-table-column label="用户数" width="86" align="right"><template #default="{ row }">{{ access.usesServerPermissions ? '—' : row.userCount }}</template></el-table-column>
|
||||
<el-table-column label="类型" width="95"><template #default="{ row }"><el-tag :type="row.builtIn ? 'warning' : 'info'" effect="plain" size="small">{{ row.builtIn ? '系统内置' : '自定义' }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="状态" width="88"><template #default="{ row }"><StatusBadge :status="row.status" /></template></el-table-column>
|
||||
@@ -198,10 +241,10 @@ onMounted(loadRoles)
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="form.id ? '配置角色' : '新增角色'" size="760px" class="business-drawer editor-drawer" :modal="false" :close-on-click-modal="false">
|
||||
<el-form label-position="top" class="drawer-form">
|
||||
<div class="form-section"><h3>基本信息</h3><div class="form-grid two-cols"><el-form-item label="角色名称" required><el-input v-model="form.name" maxlength="64" /></el-form-item><el-form-item label="角色编码" required><el-input v-model="form.code" :disabled="Boolean(form.builtIn)" placeholder="如 OPS_MANAGER" maxlength="64" /></el-form-item><el-form-item v-if="!access.usesServerPermissions" label="数据范围"><el-select v-model="form.dataScope"><el-option v-for="item in dataScopes" :key="item" :label="item" :value="item" /></el-select></el-form-item><el-form-item v-if="!access.usesServerPermissions" label="状态"><el-radio-group v-model="form.status" :disabled="Boolean(form.builtIn)"><el-radio-button label="启用" value="启用" /><el-radio-button label="停用" value="停用" /></el-radio-group></el-form-item></div><el-form-item label="角色说明"><el-input v-model="form.description" type="textarea" :rows="2" maxlength="200" show-word-limit /></el-form-item></div>
|
||||
<div v-if="!access.usesServerPermissions" class="form-section permission-section"><div class="section-heading-row"><div><h3>菜单与操作权限</h3><p>目录仅用于组织结构且独立授权;停用目录不会级联停用已启用的菜单和操作。</p></div><span>{{ form.permissionIds.length }} 项原有授权</span></div><el-tree ref="treeRef" class="permission-tree" :data="permissionTree" node-key="id" show-checkbox check-strictly default-expand-all :props="{ label: 'name', children: 'children' }" @check="syncPermissionIds"><template #default="{ data }"><div class="permission-node"><span>{{ data.name }}</span><code>{{ data.code }}</code></div></template></el-tree></div>
|
||||
<div class="form-section"><h3>基本信息</h3><div class="form-grid two-cols"><el-form-item label="角色名称" required><el-input v-model="form.name" :disabled="access.usesServerPermissions && Boolean(form.id) && !canEdit" maxlength="64" /></el-form-item><el-form-item label="角色编码" required><el-input v-model="form.code" :disabled="Boolean(form.builtIn) || (access.usesServerPermissions && Boolean(form.id))" placeholder="如 OPS_MANAGER" maxlength="64" /></el-form-item><el-form-item v-if="!access.usesServerPermissions" label="数据范围"><el-select v-model="form.dataScope"><el-option v-for="item in dataScopes" :key="item" :label="item" :value="item" /></el-select></el-form-item><el-form-item v-if="!access.usesServerPermissions" label="状态"><el-radio-group v-model="form.status" :disabled="Boolean(form.builtIn)"><el-radio-button label="启用" value="启用" /><el-radio-button label="停用" value="停用" /></el-radio-group></el-form-item></div><el-form-item label="角色说明"><el-input v-model="form.description" :disabled="access.usesServerPermissions && Boolean(form.id) && !canEdit" type="textarea" :rows="2" maxlength="200" show-word-limit /></el-form-item></div>
|
||||
<div v-if="!access.usesServerPermissions || canGrant" class="form-section permission-section"><div class="section-heading-row"><div><h3>菜单与操作权限</h3><p>保存时按后端契约全量替换当前角色权限;未勾选表示清空授权。</p></div><span>{{ form.permissionIds.length }} 项原有授权</span></div><el-tree ref="treeRef" class="permission-tree" :data="permissionTree" node-key="id" show-checkbox check-strictly default-expand-all :props="{ label: 'name', children: 'children' }" @check="syncPermissionIds"><template #default="{ data }"><div class="permission-node"><span>{{ data.name }}</span><code>{{ data.code }}</code></div></template></el-tree></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button @click="editorOpen = false">取消</el-button><el-button v-if="access.usesServerPermissions ? canCreate : access.can('system:role:grant')" type="primary" :loading="saving" @click="saveRole">保存角色</el-button></div></template>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button v-if="access.usesServerPermissions ? (form.id ? canEdit || canGrant : canCreate) : access.can('system:role:grant')" type="primary" :loading="saving" @click="saveRole">保存角色</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createPlatformWarehouse,
|
||||
getPlatformWarehouse,
|
||||
listPlatformWarehouses,
|
||||
updatePlatformWarehouse,
|
||||
type PlatformWarehouseDetailResource,
|
||||
type PlatformWarehouseResource,
|
||||
} from '@/api/platformWarehouses'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
import WarehousesView from './WarehousesView.vue'
|
||||
|
||||
vi.mock('@/api/platformWarehouses', () => ({
|
||||
listPlatformWarehouses: vi.fn(),
|
||||
getPlatformWarehouse: vi.fn(),
|
||||
createPlatformWarehouse: vi.fn(),
|
||||
updatePlatformWarehouse: vi.fn(),
|
||||
changePlatformWarehouseStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
function createMemoryStorage(initial: Record<string, string> = {}): Storage {
|
||||
const values = new Map(Object.entries(initial))
|
||||
return {
|
||||
get length() { return values.size },
|
||||
clear: () => values.clear(),
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
key: (index) => [...values.keys()][index] ?? null,
|
||||
removeItem: (key) => values.delete(key),
|
||||
setItem: (key, value) => values.set(key, value),
|
||||
}
|
||||
}
|
||||
|
||||
const warehouse: PlatformWarehouseResource = {
|
||||
id: '19001',
|
||||
tenantId: 10001,
|
||||
warehouseCode: 'CN-TEST-01',
|
||||
warehouseName: '测试环境收货仓',
|
||||
warehouseType: 'DOMESTIC',
|
||||
countryCode: 'CN',
|
||||
timezone: 'Asia/Shanghai',
|
||||
contactName: '真实联系人',
|
||||
contactPhone: '0579-12345678',
|
||||
contactEmail: 'warehouse@example.com',
|
||||
status: 'ACTIVE',
|
||||
remark: '测试环境数据',
|
||||
updatedAt: '2026-07-31T10:20:00',
|
||||
}
|
||||
|
||||
const detail: PlatformWarehouseDetailResource = {
|
||||
warehouse,
|
||||
addresses: [{
|
||||
id: '19002', tenantId: 10001, warehouseId: '19001', addressType: 'OPERATING', countryCode: 'CN',
|
||||
stateProvince: '浙江省', city: '义乌市', district: '北苑街道', postalCode: '322000',
|
||||
addressLine1: '真实物流园 1 号库', addressLine2: 'A 栋', latitude: '29.3', longitude: '120.0',
|
||||
}],
|
||||
capabilities: [
|
||||
{ id: '19003', tenantId: 10001, warehouseId: '19001', capabilityCode: 'RECEIVING', capabilityName: '收货服务', enabled: true, cutoffTime: '17:00:00', description: '周一至周六 08:30-18:00' },
|
||||
{ id: '19004', tenantId: 10001, warehouseId: '19001', capabilityCode: 'STORAGE', capabilityName: '仓储', enabled: true, cutoffTime: null, description: '托盘仓储' },
|
||||
],
|
||||
}
|
||||
|
||||
async function mountView(withTenant = true) {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage(withTenant ? { 'cc-admin-warehouse-tenant-id': '10001' } : {}))
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const access = useAccessPreviewStore()
|
||||
access.initializeAfterLogin()
|
||||
expect(access.commitRole('R002')).toBe(true)
|
||||
const wrapper = mount(WarehousesView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia, ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
afterAll(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('WarehousesView real API integration', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
document.body.innerHTML = ''
|
||||
vi.mocked(listPlatformWarehouses).mockReset().mockResolvedValue({ records: [warehouse], page: 1, size: 200, total: 1, pages: 1 })
|
||||
vi.mocked(getPlatformWarehouse).mockReset().mockResolvedValue(detail)
|
||||
vi.mocked(createPlatformWarehouse).mockReset().mockResolvedValue('19005')
|
||||
vi.mocked(updatePlatformWarehouse).mockReset().mockResolvedValue(null)
|
||||
})
|
||||
|
||||
it('loads the selected tenant and renders address and receiving capability from details', async () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(listPlatformWarehouses).toHaveBeenCalledWith(10001, 1, 200)
|
||||
expect(getPlatformWarehouse).toHaveBeenCalledWith(10001, '19001')
|
||||
expect(wrapper.text()).toContain('测试环境收货仓')
|
||||
expect(wrapper.text()).toContain('北苑街道 真实物流园 1 号库 A 栋')
|
||||
expect(wrapper.text()).toContain('周一至周六 08:30-18:00')
|
||||
})
|
||||
|
||||
it('does not query or show demo data until a valid tenant is selected', async () => {
|
||||
const wrapper = await mountView(false)
|
||||
|
||||
expect(listPlatformWarehouses).not.toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain('请输入租户 ID 并查询真实仓库数据')
|
||||
expect(wrapper.text()).not.toContain('演示物流园')
|
||||
})
|
||||
|
||||
it('shows a recoverable real API error without falling back to demo warehouses', async () => {
|
||||
vi.mocked(listPlatformWarehouses).mockRejectedValueOnce(new Error('Gateway unavailable'))
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.text()).toContain('仓库数据加载失败')
|
||||
expect(wrapper.text()).toContain('Gateway unavailable')
|
||||
expect(wrapper.text()).toContain('重新查询')
|
||||
expect(wrapper.text()).not.toContain('演示物流园')
|
||||
})
|
||||
|
||||
it('preserves backend-only address, email, capability and cutoff fields when updating', async () => {
|
||||
const wrapper = await mountView()
|
||||
const editButton = wrapper.findAll('button').find((button) => button.text().trim() === '编辑')
|
||||
expect(editButton).toBeDefined()
|
||||
await editButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const saveButton = wrapper.findAll('button').find((button) => button.text().trim() === '保存仓库')
|
||||
expect(saveButton).toBeDefined()
|
||||
await saveButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(updatePlatformWarehouse).toHaveBeenCalledOnce()
|
||||
const [, , payload] = vi.mocked(updatePlatformWarehouse).mock.calls[0]
|
||||
expect(payload.contactEmail).toBe('warehouse@example.com')
|
||||
expect(payload.address).toMatchObject({
|
||||
district: '北苑街道', postalCode: '322000', addressLine1: '真实物流园 1 号库', addressLine2: 'A 栋',
|
||||
latitude: '29.3', longitude: '120.0',
|
||||
})
|
||||
expect(payload.capabilities).toContainEqual(expect.objectContaining({
|
||||
capabilityCode: 'RECEIVING', cutoffTime: '17:00:00', description: '周一至周六 08:30-18:00',
|
||||
}))
|
||||
expect(payload.capabilities).toContainEqual(expect.objectContaining({ capabilityCode: 'STORAGE', description: '托盘仓储' }))
|
||||
})
|
||||
})
|
||||
+318
-40
@@ -1,19 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { MapPin, Pencil, Plus, Power, RotateCcw, Search, Warehouse as WarehouseIcon } from '@lucide/vue'
|
||||
import MetricStrip from '@/components/MetricStrip.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/composables/useUnsavedWorkRegistration'
|
||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/api/http'
|
||||
import {
|
||||
changePlatformWarehouseStatus,
|
||||
createPlatformWarehouse,
|
||||
getPlatformWarehouse,
|
||||
listPlatformWarehouses,
|
||||
updatePlatformWarehouse,
|
||||
type PlatformWarehouseDetailResource,
|
||||
type PlatformWarehouseResource,
|
||||
type SavePlatformWarehouseRequest,
|
||||
} from '@/api/platformWarehouses'
|
||||
import { useAccessPreviewStore } from '@/stores/accessPreview'
|
||||
import { useAdminDataStore } from '@/stores/adminData'
|
||||
import type { Warehouse } from '@/types/admin'
|
||||
|
||||
const store = useAdminDataStore()
|
||||
const tenantStorageKey = 'cc-admin-warehouse-tenant-id'
|
||||
const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const saving = ref(false)
|
||||
const loading = ref(false)
|
||||
const page = ref(1)
|
||||
const pageSize = 10
|
||||
const tenantInput = ref(sessionStorage.getItem(tenantStorageKey) || '')
|
||||
const loadedTenantId = ref<number | null>(null)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const detailWarningCount = ref(0)
|
||||
const statusLoadingIds = ref(new Set<string>())
|
||||
const filters = reactive({ keyword: '', status: '' as Warehouse['status'] | '' })
|
||||
let loadSequence = 0
|
||||
|
||||
interface WarehouseRow extends Warehouse {
|
||||
detail: PlatformWarehouseDetailResource | null
|
||||
}
|
||||
|
||||
const rows = ref<WarehouseRow[]>([])
|
||||
|
||||
const emptyForm = (): Omit<Warehouse, 'updatedAt'> => ({
|
||||
id: '', code: '', name: '', province: '', city: '', address: '', contactName: '', contactPhone: '',
|
||||
@@ -30,7 +54,15 @@ const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
requiredPermission: editorPermission,
|
||||
})
|
||||
|
||||
const filteredRows = computed(() => store.warehouses.filter((warehouse) => {
|
||||
function parseTenantId(value = tenantInput.value) {
|
||||
const normalized = value.trim()
|
||||
if (!/^[1-9]\d*$/.test(normalized)) return null
|
||||
const tenantId = Number(normalized)
|
||||
return Number.isSafeInteger(tenantId) ? tenantId : null
|
||||
}
|
||||
|
||||
const tenantMatchesLoaded = computed(() => parseTenantId() === loadedTenantId.value)
|
||||
const filteredRows = computed(() => rows.value.filter((warehouse) => {
|
||||
const keyword = filters.keyword.trim().toLowerCase()
|
||||
const matchesKeyword = !keyword || [warehouse.code, warehouse.name, warehouse.province, warehouse.city, warehouse.address]
|
||||
.some((value) => value.toLowerCase().includes(keyword))
|
||||
@@ -38,11 +70,21 @@ const filteredRows = computed(() => store.warehouses.filter((warehouse) => {
|
||||
}))
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize, page.value * pageSize))
|
||||
const metrics = computed(() => [
|
||||
{ label: '全部收货仓', value: store.warehouses.length, note: '平台仓库档案' },
|
||||
{ label: '启用仓库', value: store.activeWarehouses, note: '客户当前可选择' },
|
||||
{ label: '暂停接单', value: store.warehouses.filter((item) => item.status === 'INACTIVE').length, note: '不出现在客户下单选项' },
|
||||
{ label: '覆盖城市', value: new Set(store.warehouses.map((item) => item.city)).size, note: '国内收货区域' },
|
||||
{ label: '全部收货仓', value: rows.value.length, note: loadedTenantId.value ? `租户 ${loadedTenantId.value}` : '等待查询租户' },
|
||||
{ label: '启用仓库', value: rows.value.filter((item) => item.status === 'ACTIVE').length, note: '客户当前可选择' },
|
||||
{ label: '暂停接单', value: rows.value.filter((item) => item.status === 'INACTIVE').length, note: '不出现在客户下单选项' },
|
||||
{ label: '覆盖城市', value: new Set(rows.value.map((item) => item.city).filter(Boolean)).size, note: '国内收货区域' },
|
||||
])
|
||||
const loadErrorDescription = computed(() => {
|
||||
if (!loadError.value) return ''
|
||||
const references = [
|
||||
loadError.value.code ? `错误码 ${loadError.value.code}` : '',
|
||||
loadError.value.requestId ? `requestId ${loadError.value.requestId}` : '',
|
||||
loadError.value.traceId ? `traceId ${loadError.value.traceId}` : '',
|
||||
].filter(Boolean)
|
||||
const retained = loadedTenantId.value ? `当前仍显示租户 ${loadedTenantId.value} 最近一次成功加载的数据。` : ''
|
||||
return [loadError.value.message, references.join(' · '), retained].filter(Boolean).join(' ')
|
||||
})
|
||||
|
||||
watch(filters, () => { page.value = 1 })
|
||||
watch(
|
||||
@@ -55,38 +97,189 @@ watch(
|
||||
{ flush: 'sync' },
|
||||
)
|
||||
|
||||
function toRow(warehouse: PlatformWarehouseResource, detail: PlatformWarehouseDetailResource | null): WarehouseRow {
|
||||
const address = detail?.addresses[0]
|
||||
const receiving = detail?.capabilities.find((item) => item.capabilityCode === 'RECEIVING')
|
||||
return {
|
||||
id: String(warehouse.id),
|
||||
code: warehouse.warehouseCode,
|
||||
name: warehouse.warehouseName,
|
||||
province: address?.stateProvince || '',
|
||||
city: address?.city || '',
|
||||
address: [address?.district, address?.addressLine1, address?.addressLine2].filter(Boolean).join(' '),
|
||||
contactName: warehouse.contactName || '',
|
||||
contactPhone: warehouse.contactPhone || '',
|
||||
businessHours: receiving?.description || (receiving?.cutoffTime ? `每日截单 ${receiving.cutoffTime}` : ''),
|
||||
status: warehouse.status,
|
||||
remark: warehouse.remark || '',
|
||||
updatedAt: warehouse.updatedAt?.replace('T', ' ').slice(0, 16) || '',
|
||||
detail,
|
||||
}
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
filters.keyword = ''
|
||||
filters.status = ''
|
||||
}
|
||||
|
||||
async function loadWarehouses(requestedTenantId = parseTenantId()) {
|
||||
if (!requestedTenantId) {
|
||||
ElMessage.warning('请输入有效的正整数租户 ID')
|
||||
return
|
||||
}
|
||||
const sequence = ++loadSequence
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const result = await listPlatformWarehouses(requestedTenantId, 1, 200)
|
||||
const details = await Promise.allSettled(
|
||||
result.records.map((warehouse) => getPlatformWarehouse(requestedTenantId, warehouse.id)),
|
||||
)
|
||||
if (sequence !== loadSequence) return
|
||||
rows.value = result.records.map((warehouse, index) => {
|
||||
const detailResult = details[index]
|
||||
return toRow(warehouse, detailResult?.status === 'fulfilled' ? detailResult.value : null)
|
||||
})
|
||||
detailWarningCount.value = details.filter((item) => item.status === 'rejected').length
|
||||
loadedTenantId.value = requestedTenantId
|
||||
tenantInput.value = String(requestedTenantId)
|
||||
sessionStorage.setItem(tenantStorageKey, tenantInput.value)
|
||||
page.value = 1
|
||||
} catch (error) {
|
||||
if (sequence !== loadSequence) return
|
||||
loadError.value = getApiErrorDetails(error, '仓库数据加载失败,请稍后重试')
|
||||
} finally {
|
||||
if (sequence === loadSequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function requireCurrentTenant() {
|
||||
if (!loadedTenantId.value) {
|
||||
ElMessage.warning('请先查询目标租户的仓库数据')
|
||||
return null
|
||||
}
|
||||
if (!tenantMatchesLoaded.value) {
|
||||
ElMessage.warning('租户 ID 已变更,请先重新查询后再维护仓库')
|
||||
return null
|
||||
}
|
||||
return loadedTenantId.value
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
if (!requireCurrentTenant()) return
|
||||
Object.assign(form, emptyForm())
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function openEdit(warehouse: Warehouse) {
|
||||
Object.assign(form, warehouse)
|
||||
async function ensureDetail(warehouse: WarehouseRow) {
|
||||
if (warehouse.detail) return warehouse.detail
|
||||
const tenantId = requireCurrentTenant()
|
||||
if (!tenantId) return null
|
||||
try {
|
||||
const detail = await getPlatformWarehouse(tenantId, warehouse.id)
|
||||
Object.assign(warehouse, toRow(detail.warehouse, detail))
|
||||
detailWarningCount.value = rows.value.filter((item) => !item.detail).length
|
||||
return detail
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '仓库详情加载失败,请重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function openEdit(warehouse: WarehouseRow) {
|
||||
const detail = await ensureDetail(warehouse)
|
||||
if (!detail) return
|
||||
const address = detail.addresses[0]
|
||||
Object.assign(form, warehouse, {
|
||||
province: address?.stateProvince || '',
|
||||
city: address?.city || '',
|
||||
address: address?.addressLine1 || '',
|
||||
})
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function saveWarehouse() {
|
||||
function nullable(value: string) {
|
||||
return value.trim() || null
|
||||
}
|
||||
|
||||
function buildSaveRequest(tenantId: number): SavePlatformWarehouseRequest {
|
||||
const existing = form.id ? rows.value.find((item) => item.id === form.id)?.detail : null
|
||||
const warehouse = existing?.warehouse
|
||||
const currentAddress = existing?.addresses[0]
|
||||
const capabilities = (existing?.capabilities || []).map((capability) => ({
|
||||
capabilityCode: capability.capabilityCode,
|
||||
capabilityName: capability.capabilityName,
|
||||
enabled: capability.enabled ?? true,
|
||||
cutoffTime: capability.cutoffTime,
|
||||
description: capability.capabilityCode === 'RECEIVING' ? nullable(form.businessHours) : capability.description,
|
||||
}))
|
||||
if (!capabilities.some((item) => item.capabilityCode === 'RECEIVING')) {
|
||||
capabilities.push({
|
||||
capabilityCode: 'RECEIVING',
|
||||
capabilityName: '收货服务',
|
||||
enabled: true,
|
||||
cutoffTime: null,
|
||||
description: nullable(form.businessHours),
|
||||
})
|
||||
}
|
||||
return {
|
||||
tenantId,
|
||||
warehouseCode: form.code.trim().toUpperCase(),
|
||||
warehouseName: form.name.trim(),
|
||||
warehouseType: warehouse?.warehouseType || 'DOMESTIC',
|
||||
countryCode: warehouse?.countryCode || 'CN',
|
||||
timezone: warehouse?.timezone || 'Asia/Shanghai',
|
||||
contactName: nullable(form.contactName),
|
||||
contactPhone: nullable(form.contactPhone),
|
||||
contactEmail: warehouse?.contactEmail || null,
|
||||
status: form.status,
|
||||
remark: nullable(form.remark),
|
||||
address: {
|
||||
addressType: currentAddress?.addressType || 'OPERATING',
|
||||
countryCode: currentAddress?.countryCode || warehouse?.countryCode || 'CN',
|
||||
stateProvince: nullable(form.province),
|
||||
city: form.city.trim(),
|
||||
district: currentAddress?.district || null,
|
||||
postalCode: currentAddress?.postalCode || null,
|
||||
addressLine1: form.address.trim(),
|
||||
addressLine2: currentAddress?.addressLine2 || null,
|
||||
latitude: currentAddress?.latitude || null,
|
||||
longitude: currentAddress?.longitude || null,
|
||||
},
|
||||
capabilities,
|
||||
}
|
||||
}
|
||||
|
||||
async function saveWarehouse() {
|
||||
const tenantId = requireCurrentTenant()
|
||||
if (!tenantId) return
|
||||
if (!form.code.trim() || !form.name.trim() || !form.city.trim() || !form.address.trim()) {
|
||||
ElMessage.warning('请填写仓库编码、名称、城市和详细地址')
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
store.saveWarehouse({ ...form, id: form.id || undefined })
|
||||
const payload = buildSaveRequest(tenantId)
|
||||
if (form.id) await updatePlatformWarehouse(tenantId, form.id, payload)
|
||||
else await createPlatformWarehouse(payload)
|
||||
const successMessage = form.id ? '仓库资料已更新' : '收货仓已创建'
|
||||
editorOpen.value = false
|
||||
ElMessage.success(form.id ? '仓库资料已更新' : '收货仓已创建')
|
||||
ElMessage.success(successMessage)
|
||||
await loadWarehouses(tenantId)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '仓库保存失败')
|
||||
const details = getApiErrorDetails(error, '仓库保存失败,请检查后重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(warehouse: Warehouse) {
|
||||
async function toggleStatus(warehouse: WarehouseRow) {
|
||||
const tenantId = requireCurrentTenant()
|
||||
if (!tenantId) return
|
||||
const target = warehouse.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
||||
const targetText = target === 'ACTIVE' ? '启用' : '停用'
|
||||
try {
|
||||
@@ -97,17 +290,58 @@ async function toggleStatus(warehouse: Warehouse) {
|
||||
`${targetText}收货仓`,
|
||||
{ confirmButtonText: `确认${targetText}`, cancelButtonText: '取消', type: target === 'INACTIVE' ? 'warning' : 'info' },
|
||||
)
|
||||
store.setWarehouseStatus(warehouse.id, target)
|
||||
statusLoadingIds.value = new Set(statusLoadingIds.value).add(warehouse.id)
|
||||
await changePlatformWarehouseStatus(tenantId, warehouse.id, target)
|
||||
warehouse.status = target
|
||||
if (warehouse.detail) warehouse.detail.warehouse.status = target
|
||||
ElMessage.success(`仓库已${targetText}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
throw error
|
||||
const details = getApiErrorDetails(error, `仓库${targetText}失败,请重试`)
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
const next = new Set(statusLoadingIds.value)
|
||||
next.delete(warehouse.id)
|
||||
statusLoadingIds.value = next
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const tenantId = parseTenantId()
|
||||
if (tenantId) void loadWarehouses(tenantId)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<section class="surface-panel tenant-panel" aria-label="目标租户">
|
||||
<div class="tenant-copy">
|
||||
<h2>目标租户</h2>
|
||||
<p>仓库数据按租户隔离,请输入企业租户 ID 后查询。</p>
|
||||
</div>
|
||||
<div class="tenant-query">
|
||||
<el-input
|
||||
v-model="tenantInput"
|
||||
inputmode="numeric"
|
||||
maxlength="19"
|
||||
placeholder="请输入租户 ID"
|
||||
aria-label="目标租户 ID"
|
||||
@keyup.enter="loadWarehouses()"
|
||||
/>
|
||||
<el-button type="primary" :loading="loading" @click="loadWarehouses()">查询仓库</el-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
|
||||
<template #title>仓库数据加载失败</template>
|
||||
<p>{{ loadErrorDescription }}</p>
|
||||
<el-button size="small" @click="loadWarehouses()">重新查询</el-button>
|
||||
</el-alert>
|
||||
<el-alert v-else-if="detailWarningCount" type="warning" :closable="false" show-icon class="state-alert">
|
||||
<template #title>部分仓库详情暂未加载</template>
|
||||
<p>{{ detailWarningCount }} 个仓库缺少地址或服务能力详情;编辑时会再次尝试加载,不会用模拟数据补齐。</p>
|
||||
</el-alert>
|
||||
|
||||
<MetricStrip :items="metrics" />
|
||||
|
||||
<section class="surface-panel filter-panel" aria-label="仓库筛选">
|
||||
@@ -121,45 +355,89 @@ async function toggleStatus(warehouse: Warehouse) {
|
||||
</div>
|
||||
<div class="filter-actions">
|
||||
<el-button @click="resetFilters"><RotateCcw :size="16" />重置</el-button>
|
||||
<el-button v-if="access.can('warehouse:write')" type="primary" @click="openCreate"><Plus :size="16" />新增仓库</el-button>
|
||||
<el-button
|
||||
v-if="access.can('warehouse:write')"
|
||||
type="primary"
|
||||
:disabled="!tenantMatchesLoaded || loading"
|
||||
@click="openCreate"
|
||||
><Plus :size="16" />新增仓库</el-button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<div class="panel-heading"><div><h2>平台收货仓</h2><p>仅启用仓库会进入客户头程下单选项</p></div></div>
|
||||
<el-table v-if="pagedRows.length" :data="pagedRows" row-key="id">
|
||||
<el-table-column label="操作" width="180" fixed="left">
|
||||
<template #default="{ row }"><div v-if="access.can('warehouse:write')" class="table-actions"><el-button link type="primary" @click="openEdit(row as Warehouse)"><Pencil :size="15" />编辑</el-button><el-button link :type="(row as Warehouse).status === 'ACTIVE' ? 'danger' : 'success'" @click="toggleStatus(row as Warehouse)"><Power :size="15" />{{ (row as Warehouse).status === 'ACTIVE' ? '停用' : '启用' }}</el-button></div><span v-else class="warehouse-subline">仅查看</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="仓库" min-width="200">
|
||||
<template #default="{ row }"><div class="warehouse-cell"><span><WarehouseIcon :size="18" /></span><div><strong>{{ (row as Warehouse).name }}</strong><small>{{ (row as Warehouse).code }}</small></div></div></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="所在城市" min-width="130"><template #default="{ row }">{{ (row as Warehouse).province }} · {{ (row as Warehouse).city }}</template></el-table-column>
|
||||
<el-table-column label="收货地址" min-width="260"><template #default="{ row }"><div class="warehouse-address"><MapPin :size="15" />{{ (row as Warehouse).address }}</div></template></el-table-column>
|
||||
<el-table-column label="联系人" min-width="150"><template #default="{ row }"><strong>{{ (row as Warehouse).contactName || '-' }}</strong><span class="warehouse-subline">{{ (row as Warehouse).contactPhone || '-' }}</span></template></el-table-column>
|
||||
<el-table-column label="收货时间" prop="businessHours" min-width="190" />
|
||||
<el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="(row as Warehouse).status === 'ACTIVE' ? 'success' : 'info'" effect="light">{{ (row as Warehouse).status === 'ACTIVE' ? '启用' : '停用' }}</el-tag></template></el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else description="没有符合条件的仓库" />
|
||||
<div class="table-footer"><span>共 {{ filteredRows.length }} 个收货仓</span><el-pagination v-model:current-page="page" :page-size="pageSize" :total="filteredRows.length" layout="prev, pager, next" /></div>
|
||||
<section class="surface-panel table-panel" aria-live="polite">
|
||||
<div class="panel-heading">
|
||||
<div>
|
||||
<h2>平台收货仓</h2>
|
||||
<p v-if="loadedTenantId">当前数据:租户 {{ loadedTenantId }} · 仅启用仓库会进入客户头程下单选项</p>
|
||||
<p v-else>查询租户后显示服务端仓库数据</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-loading="loading" class="warehouse-table-state">
|
||||
<el-table v-if="pagedRows.length" :data="pagedRows" row-key="id">
|
||||
<el-table-column label="操作" width="180" fixed="left">
|
||||
<template #default="{ row }">
|
||||
<div v-if="access.can('warehouse:write')" class="table-actions">
|
||||
<el-button link type="primary" :disabled="!tenantMatchesLoaded" @click="openEdit(row as WarehouseRow)"><Pencil :size="15" />编辑</el-button>
|
||||
<el-button
|
||||
link
|
||||
:type="(row as WarehouseRow).status === 'ACTIVE' ? 'danger' : 'success'"
|
||||
:disabled="!tenantMatchesLoaded"
|
||||
:loading="statusLoadingIds.has((row as WarehouseRow).id)"
|
||||
@click="toggleStatus(row as WarehouseRow)"
|
||||
><Power :size="15" />{{ (row as WarehouseRow).status === 'ACTIVE' ? '停用' : '启用' }}</el-button>
|
||||
</div>
|
||||
<span v-else class="warehouse-subline">仅查看</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="仓库" min-width="200">
|
||||
<template #default="{ row }"><div class="warehouse-cell"><span><WarehouseIcon :size="18" /></span><div><strong>{{ (row as WarehouseRow).name }}</strong><small>{{ (row as WarehouseRow).code }}</small></div></div></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="所在城市" min-width="130"><template #default="{ row }">{{ [(row as WarehouseRow).province, (row as WarehouseRow).city].filter(Boolean).join(' · ') || '-' }}</template></el-table-column>
|
||||
<el-table-column label="收货地址" min-width="260"><template #default="{ row }"><div class="warehouse-address"><MapPin :size="15" />{{ (row as WarehouseRow).address || '详情暂未加载' }}</div></template></el-table-column>
|
||||
<el-table-column label="联系人" min-width="150"><template #default="{ row }"><strong>{{ (row as WarehouseRow).contactName || '-' }}</strong><span class="warehouse-subline">{{ (row as WarehouseRow).contactPhone || '-' }}</span></template></el-table-column>
|
||||
<el-table-column label="收货时间" min-width="190"><template #default="{ row }">{{ (row as WarehouseRow).businessHours || '-' }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="(row as WarehouseRow).status === 'ACTIVE' ? 'success' : 'info'" effect="light">{{ (row as WarehouseRow).status === 'ACTIVE' ? '启用' : '停用' }}</el-tag></template></el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else-if="!loading" :description="loadedTenantId ? '该租户暂无符合条件的仓库' : '请输入租户 ID 并查询真实仓库数据'" />
|
||||
</div>
|
||||
<div v-if="loadedTenantId" class="table-footer"><span>共 {{ filteredRows.length }} 个收货仓</span><el-pagination v-model:current-page="page" :page-size="pageSize" :total="filteredRows.length" layout="prev, pager, next" /></div>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="editorLabel" size="620px" class="business-drawer editor-drawer" :close-on-click-modal="false">
|
||||
<el-form label-position="top" class="drawer-form">
|
||||
<div class="form-section"><h3>仓库标识</h3><div class="form-grid two-cols"><el-form-item label="仓库编码" required><el-input v-model="form.code" maxlength="32" placeholder="例如 CN-NB-01" /></el-form-item><el-form-item label="仓库名称" required><el-input v-model="form.name" maxlength="100" placeholder="客户下单时显示的名称" /></el-form-item><el-form-item label="状态"><el-radio-group v-model="form.status"><el-radio-button value="ACTIVE">启用</el-radio-button><el-radio-button value="INACTIVE">停用</el-radio-button></el-radio-group></el-form-item></div></div>
|
||||
<div class="form-section"><h3>地址与收货</h3><div class="form-grid two-cols"><el-form-item label="省份"><el-input v-model="form.province" maxlength="40" /></el-form-item><el-form-item label="城市" required><el-input v-model="form.city" maxlength="40" /></el-form-item><el-form-item label="联系人"><el-input v-model="form.contactName" maxlength="50" /></el-form-item><el-form-item label="联系电话"><el-input v-model="form.contactPhone" maxlength="30" /></el-form-item><el-form-item label="收货时间"><el-input v-model="form.businessHours" maxlength="100" /></el-form-item></div><el-form-item label="详细地址" required><el-input v-model="form.address" maxlength="300" type="textarea" :rows="3" /></el-form-item></div>
|
||||
<el-form label-position="top" class="drawer-form" :disabled="saving">
|
||||
<div class="form-section"><h3>仓库标识</h3><div class="form-grid two-cols"><el-form-item label="仓库编码" required><el-input v-model="form.code" maxlength="50" placeholder="例如 CN-NB-01" /></el-form-item><el-form-item label="仓库名称" required><el-input v-model="form.name" maxlength="120" placeholder="客户下单时显示的名称" /></el-form-item><el-form-item label="状态"><el-radio-group v-model="form.status"><el-radio-button value="ACTIVE">启用</el-radio-button><el-radio-button value="INACTIVE">停用</el-radio-button></el-radio-group></el-form-item></div></div>
|
||||
<div class="form-section"><h3>地址与收货</h3><div class="form-grid two-cols"><el-form-item label="省份"><el-input v-model="form.province" maxlength="100" /></el-form-item><el-form-item label="城市" required><el-input v-model="form.city" maxlength="100" /></el-form-item><el-form-item label="联系人"><el-input v-model="form.contactName" maxlength="64" /></el-form-item><el-form-item label="联系电话"><el-input v-model="form.contactPhone" maxlength="32" /></el-form-item><el-form-item label="收货时间"><el-input v-model="form.businessHours" maxlength="500" /></el-form-item></div><el-form-item label="详细地址" required><el-input v-model="form.address" maxlength="255" type="textarea" :rows="3" /></el-form-item></div>
|
||||
<div class="form-section"><h3>备注</h3><el-form-item label="客户可理解的收货说明"><el-input v-model="form.remark" maxlength="500" type="textarea" :rows="3" show-word-limit /></el-form-item></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button @click="editorOpen = false">取消</el-button><el-button type="primary" @click="saveWarehouse">保存仓库</el-button></div></template>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button type="primary" :loading="saving" @click="saveWarehouse">保存仓库</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tenant-panel { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px; }
|
||||
.tenant-copy h2 { margin: 0; font-size: 16px; }
|
||||
.tenant-copy p { margin: 6px 0 0; color: var(--cc-muted); font-size: 13px; }
|
||||
.tenant-query { display: flex; width: min(100%, 390px); gap: 10px; }
|
||||
.tenant-query .el-input { flex: 1; }
|
||||
.state-alert p { margin: 6px 0 10px; line-height: 1.55; }
|
||||
.warehouse-table-state { min-height: 180px; }
|
||||
.warehouse-cell { display: flex; align-items: center; gap: 10px; }
|
||||
.warehouse-cell > span { display: grid; width: 34px; height: 34px; flex: 0 0 34px; place-items: center; border-radius: 7px; background: #eef3fa; color: var(--cc-primary); }
|
||||
.warehouse-cell > div { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
|
||||
.warehouse-cell strong { overflow-wrap: anywhere; }
|
||||
.warehouse-cell small, .warehouse-subline { display: block; color: var(--cc-muted); font-size: 11px; }
|
||||
.warehouse-address { display: flex; align-items: flex-start; gap: 7px; line-height: 1.55; }
|
||||
.warehouse-address { display: flex; align-items: flex-start; gap: 7px; line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.warehouse-address svg { flex: 0 0 15px; margin-top: 2px; color: var(--cc-muted); }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.tenant-panel { align-items: stretch; flex-direction: column; gap: 16px; }
|
||||
.tenant-query { width: 100%; }
|
||||
.tenant-query .el-button { flex: 0 0 auto; }
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.tenant-query { flex-direction: column; }
|
||||
.tenant-query .el-button { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user