This commit is contained in:
2026-08-06 14:55:17 +08:00
parent a813426588
commit 4ac0adac62
18 changed files with 379 additions and 352 deletions
@@ -40,19 +40,19 @@ describe('platform express company API', () => {
.mockResolvedValueOnce({ code: '200', message: 'success', data: page })
.mockResolvedValueOnce({ code: '200', message: 'success', data: { id: '19001' } })
await expect(listPlatformExpressCompanies(10001, 2, 20, ' 顺丰 ', 'ACTIVE')).resolves.toEqual({
await expect(listPlatformExpressCompanies(2, 20, ' 顺丰 ', 'ACTIVE')).resolves.toEqual({
records: [],
page: 1,
size: 20,
total: 0,
pages: 0,
})
await expect(getPlatformExpressCompany(10001, '19001')).resolves.toEqual({ id: '19001' })
await expect(getPlatformExpressCompany('19001')).resolves.toEqual({ id: '19001' })
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/express-companies', {
params: { tenantId: 10001, page: 2, size: 20, keyword: '顺丰', status: 'ACTIVE' },
params: { page: 2, size: 20, keyword: '顺丰', status: 'ACTIVE' },
})
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/express-companies/19001', {
params: { tenantId: 10001 },
params: { tenantId: 0 },
})
})
@@ -61,16 +61,16 @@ describe('platform express company API', () => {
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: null })
vi.mocked(http.patch).mockResolvedValue({ code: '200', message: 'success', data: null })
await expect(createPlatformExpressCompany(10001, payload)).resolves.toBe('19001')
await expect(updatePlatformExpressCompany(10001, '19001', payload)).resolves.toBeNull()
await expect(changePlatformExpressCompanyStatus(10001, '19001', 'INACTIVE')).resolves.toBeNull()
await expect(createPlatformExpressCompany(payload)).resolves.toBe('19001')
await expect(updatePlatformExpressCompany('19001', payload)).resolves.toBeNull()
await expect(changePlatformExpressCompanyStatus('19001', 'INACTIVE')).resolves.toBeNull()
expect(http.post).toHaveBeenCalledWith('/platform/v1/express-companies', payload, { params: { tenantId: 10001 } })
expect(http.put).toHaveBeenCalledWith('/platform/v1/express-companies/19001', payload, { params: { tenantId: 10001 } })
expect(http.post).toHaveBeenCalledWith('/platform/v1/express-companies', payload, { params: { tenantId: 0 } })
expect(http.put).toHaveBeenCalledWith('/platform/v1/express-companies/19001', payload, { params: { tenantId: 0 } })
expect(http.patch).toHaveBeenCalledWith(
'/platform/v1/express-companies/19001/status',
{ status: 'INACTIVE' },
{ params: { tenantId: 10001 } },
{ params: { tenantId: 0 } },
)
})
@@ -89,12 +89,12 @@ describe('platform express company API', () => {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
})
await expect(importPlatformExpressCompanies(10001, file)).resolves.toEqual(result)
await expect(importPlatformExpressCompanies(file)).resolves.toEqual(result)
expect(http.post).toHaveBeenCalledOnce()
const [path, body, config] = vi.mocked(http.post).mock.calls[0]!
expect(path).toBe('/platform/v1/express-companies/import')
expect(body).toBeInstanceOf(FormData)
expect((body as FormData).get('file')).toBe(file)
expect(config).toEqual({ params: { tenantId: 10001 } })
expect(config).toEqual({ params: { tenantId: 0 } })
})
})
@@ -49,9 +49,9 @@ export interface PlatformExpressCompanyImportResult {
}
const basePath = '/platform/v1/express-companies'
const platformResourceScope = 0
export async function listPlatformExpressCompanies(
tenantId: number | string | undefined,
page = 1,
size = 20,
keyword = '',
@@ -59,7 +59,6 @@ export async function listPlatformExpressCompanies(
) {
const response = await http.get<ApiEnvelope<PlatformExpressCompanyPage>, ApiEnvelope<PlatformExpressCompanyPage>>(basePath, {
params: {
tenantId,
page,
size,
keyword: keyword.trim() || undefined,
@@ -76,39 +75,37 @@ export async function listPlatformExpressCompanies(
}
}
export async function getPlatformExpressCompany(tenantId: number | string, id: number | string) {
export async function getPlatformExpressCompany(id: number | string) {
const response = await http.get<ApiEnvelope<PlatformExpressCompanyResource>, ApiEnvelope<PlatformExpressCompanyResource>>(
`${basePath}/${id}`,
{ params: { tenantId } },
{ params: { tenantId: platformResourceScope } },
)
return unwrapApiResponse(response)
}
export async function createPlatformExpressCompany(tenantId: number | string, payload: SavePlatformExpressCompanyRequest) {
export async function createPlatformExpressCompany(payload: SavePlatformExpressCompanyRequest) {
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
params: { tenantId },
params: { tenantId: platformResourceScope },
})
return unwrapApiResponse(response)
}
export async function updatePlatformExpressCompany(
tenantId: number | string,
id: number | string,
payload: SavePlatformExpressCompanyRequest,
) {
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${id}`, payload, {
params: { tenantId },
params: { tenantId: platformResourceScope },
})
return unwrapApiResponse(response)
}
export async function changePlatformExpressCompanyStatus(
tenantId: number | string,
id: number | string,
status: PlatformExpressCompanyStatus,
) {
const response = await http.patch<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${id}/status`, { status }, {
params: { tenantId },
params: { tenantId: platformResourceScope },
})
return unwrapApiResponse(response)
}
@@ -117,13 +114,13 @@ export async function downloadPlatformExpressCompanyImportTemplate() {
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
}
export async function importPlatformExpressCompanies(tenantId: number | string, file: File) {
export async function importPlatformExpressCompanies(file: File) {
const formData = new FormData()
formData.append('file', file)
const response = await http.post<ApiEnvelope<PlatformExpressCompanyImportResult>, ApiEnvelope<PlatformExpressCompanyImportResult>>(
`${basePath}/import`,
formData,
{ params: { tenantId } },
{ params: { tenantId: platformResourceScope } },
)
return unwrapApiResponse(response)
}
@@ -5,8 +5,6 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vites
import { listPlatformExpressCompanies, type PlatformExpressCompanyResource } from '@/modules/master-data/express-companies/api/platformExpressCompanies'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { useAuthStore } from '@/core/auth/auth'
import QueryToolbar from '@/shared/components/QueryToolbar.vue'
import { listPlatformTenants, type PlatformTenantResource } from '../../../iam/api/platformIam'
import ExpressCompaniesView from './ExpressCompaniesView.vue'
vi.mock('@/modules/master-data/express-companies/api/platformExpressCompanies', () => ({
@@ -16,8 +14,6 @@ vi.mock('@/modules/master-data/express-companies/api/platformExpressCompanies',
changePlatformExpressCompanyStatus: vi.fn(),
}))
vi.mock('../../../iam/api/platformIam', () => ({ listPlatformTenants: vi.fn() }))
class ResizeObserverStub implements ResizeObserver {
observe() {}
unobserve() {}
@@ -38,7 +34,7 @@ function createMemoryStorage(): Storage {
const company: PlatformExpressCompanyResource = {
id: '19001',
tenantId: 10001,
tenantId: 0,
companyCode: 'SF',
companyName: '顺丰速运',
servicePhone: '95338',
@@ -49,16 +45,6 @@ const company: PlatformExpressCompanyResource = {
updatedAt: '2026-07-31T10:20:00',
}
const tenant = (id: number | string, tenantName: string): PlatformTenantResource => ({
id, tenantCode: String(id), tenantName, status: 'ACTIVE', legalName: tenantName,
legalRepresentative: null, unifiedSocialCreditCode: null, contactName: null,
contactPhone: null, contactEmail: null, servicePackage: null, contactWechat: null,
salesOwnerName: null, paymentTermDays: null, enterpriseType: null, establishedDate: null,
registeredCapital: null, registeredCapitalCurrency: null, registeredAddress: null,
internalRemark: null, createdAt: null, approvedAt: null,
})
const snowflakeTenantId = '9223372036854775806'
async function mountView() {
vi.stubGlobal('localStorage', createMemoryStorage())
vi.stubGlobal('sessionStorage', createMemoryStorage())
@@ -83,9 +69,6 @@ describe('ExpressCompaniesView query and table migration', () => {
beforeEach(() => {
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
document.body.innerHTML = ''
vi.mocked(listPlatformTenants).mockReset().mockResolvedValue({
records: [tenant(10001, '默认企业'), tenant(snowflakeTenantId, '雪花企业')], page: 1, size: 200, total: 2, pages: 1,
})
vi.mocked(listPlatformExpressCompanies).mockReset().mockResolvedValue({
records: [company], page: 1, size: 20, total: 1, pages: 1,
})
@@ -95,12 +78,12 @@ describe('ExpressCompaniesView query and table migration', () => {
const wrapper = await mountView()
expect(wrapper.find('.query-toolbar').exists()).toBe(true)
expect(wrapper.find('input[aria-label="所属企业"]').exists()).toBe(true)
expect(wrapper.find('input[aria-label="所属企业"]').exists()).toBe(false)
expect(wrapper.find('.data-table').exists()).toBe(true)
expect(wrapper.text()).toContain('顺丰速运')
expect(wrapper.text()).toContain('全部企业 · 共 1 家快递公司')
expect(wrapper.text()).toContain('平台公共数据 · 共 1 家快递公司')
expect(wrapper.find('.metric-strip').exists()).toBe(false)
expect(listPlatformExpressCompanies).toHaveBeenCalledWith(undefined, 1, 20, '', '')
expect(listPlatformExpressCompanies).toHaveBeenCalledWith(1, 20, '', '')
})
it('does not request with edited filters until search is submitted', async () => {
@@ -113,18 +96,16 @@ describe('ExpressCompaniesView query and table migration', () => {
await searchButton?.trigger('click')
await flushPromises()
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(undefined, 1, 20, '顺丰', '')
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(1, 20, '顺丰', '')
})
it('preserves a snowflake tenant id as a string when switching enterprises', async () => {
it('opens the create form without selecting an enterprise', async () => {
const wrapper = await mountView()
const toolbar = wrapper.findComponent(QueryToolbar)
const model = { tenantId: snowflakeTenantId, keyword: '', status: '' }
toolbar.vm.$emit('update:modelValue', model)
toolbar.vm.$emit('search', model)
const createButton = wrapper.findAll('button').find((button) => button.text().trim() === '新增快递公司')
await createButton?.trigger('click')
await flushPromises()
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(snowflakeTenantId, 1, 20, '', '')
expect(document.body.textContent).toContain('新增快递公司')
expect(document.body.textContent).not.toContain('请先在筛选条件中选择所属企业')
})
})
@@ -21,7 +21,6 @@ import {
type SavePlatformExpressCompanyRequest,
} from '@/modules/master-data/express-companies/api/platformExpressCompanies'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { listPlatformTenants, type PlatformTenantResource } from '@/modules/iam'
const access = useAccessPreviewStore()
const loading = ref(false)
@@ -34,9 +33,6 @@ const rows = ref<PlatformExpressCompanyResource[]>([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const tenants = ref<PlatformTenantResource[]>([])
const tenantLoadError = ref<ApiErrorDetails | null>(null)
const editorTenantId = ref('')
const loadError = ref<ApiErrorDetails | null>(null)
const statusLoadingIds = ref(new Set<string>())
const editLoadingIds = ref(new Set<string>())
@@ -46,21 +42,12 @@ const importFile = ref<File | null>(null)
const importResult = ref<PlatformExpressCompanyImportResult | null>(null)
const importError = ref<ApiErrorDetails | null>(null)
type ExpressCompanyFilters = QueryModel & {
tenantId: string
keyword: string
status: PlatformExpressCompanyStatus | ''
}
const filters = ref<ExpressCompanyFilters>({ tenantId: '', keyword: '', status: '' })
const filters = ref<ExpressCompanyFilters>({ keyword: '', status: '' })
const appliedFilters = ref<ExpressCompanyFilters>({ ...filters.value })
const queryFields = computed<QueryField[]>(() => [
{
key: 'tenantId',
type: 'select',
width: 180,
placeholder: tenantLoadError.value ? '企业列表加载失败' : '全部企业',
props: { 'aria-label': '所属企业', filterable: true, disabled: Boolean(tenantLoadError.value) },
options: tenants.value.map((tenant) => ({ value: String(tenant.id), label: `${tenant.tenantName}(${tenant.tenantCode || tenant.id})` })),
},
{ key: 'keyword', type: 'input', placeholder: '快递公司名称或编码', props: { maxlength: 128, 'aria-label': '快递公司关键词' } },
{
key: 'status',
@@ -103,13 +90,6 @@ const { captureBaseline } = useUnsavedWorkRegistration({
requiredPermission: editorPermission,
})
const selectedEnterpriseId = computed(() => appliedFilters.value.tenantId)
const targetEnterpriseId = computed(() => filters.value.tenantId)
const selectedEnterpriseName = computed(() => {
if (!selectedEnterpriseId.value) return '全部企业'
return tenants.value.find((tenant) => String(tenant.id) === selectedEnterpriseId.value)?.tenantName || `企业 ${selectedEnterpriseId.value}`
})
watch(
() => access.can(editorPermission.value),
(canWrite) => {
@@ -142,7 +122,6 @@ function formatUpdatedAt(value?: string | null) {
const expressCompanyColumns: DataTableColumn[] = [
{ key: 'actions', label: '操作', width: 170, fixed: 'left', slotName: 'actions' },
{ key: 'company', label: '快递公司', minWidth: 210, slotName: 'company' },
{ key: 'tenant', label: '所属企业', minWidth: 190, showOverflowTooltip: true, slotName: 'tenant' },
{ prop: 'servicePhone', label: '客服电话', minWidth: 130, formatter: (row: PlatformExpressCompanyResource) => row.servicePhone || '—' },
{ key: 'website', label: '官方网站', minWidth: 210, slotName: 'website' },
{ key: 'trackingUrlTemplate', label: '轨迹查询模板', minWidth: 260, slotName: 'trackingUrlTemplate' },
@@ -151,50 +130,12 @@ const expressCompanyColumns: DataTableColumn[] = [
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
]
function apiTenantId(value: string | undefined) {
if (!value) return undefined
const numeric = Number(value)
return Number.isSafeInteger(numeric) ? numeric : value
}
function requireSelectedEnterprise(action: string) {
if (!targetEnterpriseId.value) {
ElMessage.warning(`请先在筛选条件中选择所属企业,再${action}`)
return null
}
return apiTenantId(targetEnterpriseId.value)!
}
function tenantName(tenantId: number | string) {
return tenants.value.find((tenant) => String(tenant.id) === String(tenantId))?.tenantName || `企业 ${tenantId}`
}
async function loadTenants() {
tenantLoadError.value = null
try {
const records: PlatformTenantResource[] = []
let currentPage = 1
let pages = 1
do {
const result = await listPlatformTenants({ page: currentPage, size: 200 })
records.push(...result.records)
pages = Math.max(1, result.pages)
currentPage += 1
} while (currentPage <= pages)
tenants.value = records
} catch (error) {
tenants.value = []
tenantLoadError.value = getApiErrorDetails(error, '企业列表加载失败,暂时无法按所属企业筛选')
}
}
async function loadExpressCompanies() {
const sequence = ++loadSequence
loading.value = true
loadError.value = null
try {
const result = await listPlatformExpressCompanies(
apiTenantId(appliedFilters.value.tenantId),
page.value,
pageSize.value,
appliedFilters.value.keyword,
@@ -215,7 +156,6 @@ async function loadExpressCompanies() {
function applyFilters(model: QueryModel) {
appliedFilters.value = {
tenantId: String(model.tenantId || ''),
keyword: String(model.keyword || ''),
status: (model.status || '') as PlatformExpressCompanyStatus | '',
}
@@ -227,9 +167,6 @@ function applyFilters(model: QueryModel) {
}
function openCreate() {
const tenantId = requireSelectedEnterprise('新增快递公司')
if (!tenantId) return
editorTenantId.value = String(tenantId)
Object.assign(form, emptyForm())
captureBaseline()
editorOpen.value = true
@@ -253,14 +190,12 @@ function assignEditor(row: PlatformExpressCompanyResource) {
}
async function openEdit(row: PlatformExpressCompanyResource) {
const tenantId = apiTenantId(String(row.tenantId))!
editorTenantId.value = String(row.tenantId)
const id = String(row.id)
const pending = new Set(editLoadingIds.value)
pending.add(id)
editLoadingIds.value = pending
try {
assignEditor(await getPlatformExpressCompany(tenantId, row.id))
assignEditor(await getPlatformExpressCompany(row.id))
} catch (error) {
const details = getApiErrorDetails(error, '快递公司详情加载失败,请稍后重试')
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
@@ -272,7 +207,6 @@ async function openEdit(row: PlatformExpressCompanyResource) {
}
function openImport() {
if (!requireSelectedEnterprise('批量导入')) return
importFile.value = null
importResult.value = null
importError.value = null
@@ -326,8 +260,6 @@ function selectImportFile(event: Event) {
}
async function submitImport() {
const tenantId = requireSelectedEnterprise('批量导入')
if (!tenantId) return
if (!importFile.value) {
ElMessage.warning('请先选择填写完成的 XLSX 文件')
return
@@ -336,7 +268,7 @@ async function submitImport() {
importError.value = null
importResult.value = null
try {
const result = await importPlatformExpressCompanies(tenantId, importFile.value)
const result = await importPlatformExpressCompanies(importFile.value)
importResult.value = result
if (result.success) {
ElMessage.success(`成功导入 ${result.importedRows} 家快递公司`)
@@ -374,15 +306,13 @@ function buildPayload(): SavePlatformExpressCompanyRequest {
}
async function saveExpressCompany() {
const tenantId = form.id ? apiTenantId(editorTenantId.value) : requireSelectedEnterprise('新增快递公司')
if (!tenantId) return
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
const payload = buildPayload()
if (form.id) await updatePlatformExpressCompany(tenantId, form.id, payload)
else await createPlatformExpressCompany(tenantId, payload)
if (form.id) await updatePlatformExpressCompany(form.id, payload)
else await createPlatformExpressCompany(payload)
editorOpen.value = false
ElMessage.success(form.id ? '快递公司资料已更新' : '快递公司已创建')
await loadExpressCompanies()
@@ -395,7 +325,6 @@ async function saveExpressCompany() {
}
async function toggleStatus(row: PlatformExpressCompanyResource) {
const tenantId = apiTenantId(String(row.tenantId))!
const nextStatus: PlatformExpressCompanyStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
try {
@@ -412,7 +341,7 @@ async function toggleStatus(row: PlatformExpressCompanyResource) {
pending.add(id)
statusLoadingIds.value = pending
try {
await changePlatformExpressCompanyStatus(tenantId, row.id, nextStatus)
await changePlatformExpressCompanyStatus(row.id, nextStatus)
ElMessage.success(`已${action}${row.companyName}`)
await loadExpressCompanies()
} catch (error) {
@@ -427,19 +356,12 @@ async function toggleStatus(row: PlatformExpressCompanyResource) {
watch([page, pageSize], () => { void loadExpressCompanies() })
onMounted(() => {
void loadTenants()
void loadExpressCompanies()
})
</script>
<template>
<div class="business-page express-company-page">
<el-alert v-if="tenantLoadError" type="warning" :closable="false" show-icon class="state-alert">
<template #title>所属企业列表加载失败</template>
<p>{{ tenantLoadError.message }};快递公司仍按全部企业展示。</p>
<ApiErrorMeta :details="tenantLoadError" />
<el-button size="small" @click="loadTenants">重新加载企业列表</el-button>
</el-alert>
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
<template #title>快递公司加载失败</template>
<p>{{ loadError.message }}</p>
@@ -453,7 +375,7 @@ onMounted(() => {
<div class="panel-heading">
<div>
<h2>快递公司列表</h2>
<p>{{ selectedEnterpriseName }} · 共 {{ total }} 家快递公司</p>
<p>平台公共数据 · 共 {{ total }} 家快递公司</p>
</div>
<div class="panel-actions">
<el-button v-if="access.can('platform:express:import')" :disabled="loading" @click="openImport"><Upload :size="16" />批量导入</el-button>
@@ -494,7 +416,6 @@ onMounted(() => {
<span v-else class="muted-value">仅查看</span>
</template>
<template #company="{ row }"><div class="express-company-cell"><span><Truck :size="17" /></span><div><strong>{{ (row as PlatformExpressCompanyResource).companyName }}</strong><small>{{ (row as PlatformExpressCompanyResource).companyCode }}</small></div></div></template>
<template #tenant="{ row }"><span>{{ tenantName((row as PlatformExpressCompanyResource).tenantId) }}</span></template>
<template #website="{ row }">
<a v-if="safeHttpUrl((row as PlatformExpressCompanyResource).website)" class="external-link" :href="safeHttpUrl((row as PlatformExpressCompanyResource).website)!" target="_blank" rel="noopener noreferrer">访问官网<ExternalLink :size="13" /></a>
<span v-else class="muted-value">{{ (row as PlatformExpressCompanyResource).website || '—' }}</span>