优化构架
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import LoginView from './LoginView.vue'
|
||||
|
||||
const loginSource = readFileSync(resolve(process.cwd(), 'src/modules/auth/pages/LoginView.vue'), 'utf8')
|
||||
const formStub = {
|
||||
template: '<form><slot /></form>',
|
||||
setup(_: unknown, { expose }: { expose: (exposed: { validate: () => Promise<boolean> }) => void }) {
|
||||
expose({ validate: async () => true })
|
||||
},
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
describe('LoginView authentication lifecycle', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
})
|
||||
|
||||
it('always renders a blank login form without demo credentials or hints', () => {
|
||||
expect(loginSource).toContain("account: ''")
|
||||
expect(loginSource).toContain("password: ''")
|
||||
expect(loginSource).not.toContain('import.meta.env.DEV')
|
||||
expect(loginSource).not.toContain('platform_admin')
|
||||
expect(loginSource).not.toContain('ChangeMe123!')
|
||||
expect(loginSource).not.toContain('demo-tip')
|
||||
})
|
||||
|
||||
it('initializes preview access after login and before redirecting', async () => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
const access = useAccessPreviewStore()
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: LoginView },
|
||||
{ path: '/', component: { template: '<p>home</p>' } },
|
||||
],
|
||||
})
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
|
||||
const calls: string[] = []
|
||||
vi.spyOn(auth, 'login').mockImplementation(async () => { calls.push('login') })
|
||||
vi.spyOn(access, 'initializeAfterLogin').mockImplementation(() => { calls.push('access') })
|
||||
vi.spyOn(router, 'replace').mockImplementation(async () => { calls.push('replace') })
|
||||
const wrapper = mount(LoginView, {
|
||||
global: {
|
||||
plugins: [pinia, router],
|
||||
stubs: {
|
||||
'el-form': formStub,
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
||||
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const inputs = wrapper.findAll('input')
|
||||
await inputs[0]!.setValue('test_admin')
|
||||
await inputs[1]!.setValue('password')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(calls).toEqual(['login', 'access', 'replace'])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['/customers?page=2', '/customers?page=2'],
|
||||
['/customers/reviews', '/customers/reviews'],
|
||||
['//example.com', '/403'],
|
||||
['https://example.com', '/403'],
|
||||
[['/customers', '/orders/first-leg'], '/403'],
|
||||
[null, '/403'],
|
||||
])('sanitizes the post-login redirect %j to %s', async (redirect, expected) => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: LoginView },
|
||||
{ path: '/', component: { template: '<p>home</p>' } },
|
||||
],
|
||||
})
|
||||
await router.push({ path: '/login', query: { redirect } })
|
||||
await router.isReady()
|
||||
vi.spyOn(auth, 'login').mockResolvedValue()
|
||||
const replace = vi.spyOn(router, 'replace').mockResolvedValue()
|
||||
const wrapper = mount(LoginView, {
|
||||
global: {
|
||||
plugins: [pinia, router],
|
||||
stubs: {
|
||||
'el-form': formStub,
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
||||
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const inputs = wrapper.findAll('input')
|
||||
await inputs[0]!.setValue('test_admin')
|
||||
await inputs[1]!.setValue('password')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(replace).toHaveBeenCalledWith(expected)
|
||||
})
|
||||
|
||||
it('preserves the form and reports a recoverable error when login fails', async () => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
const access = useAccessPreviewStore()
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/login', component: LoginView },
|
||||
{ path: '/customers', component: { template: '<p>customers</p>' } },
|
||||
],
|
||||
})
|
||||
await router.push('/login')
|
||||
await router.isReady()
|
||||
vi.spyOn(auth, 'login').mockRejectedValue(new Error('network unavailable'))
|
||||
const initialize = vi.spyOn(access, 'initializeAfterLogin')
|
||||
const replace = vi.spyOn(router, 'replace')
|
||||
const wrapper = mount(LoginView, {
|
||||
global: {
|
||||
plugins: [pinia, router],
|
||||
stubs: {
|
||||
'el-form': formStub,
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
||||
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const inputs = wrapper.findAll('input')
|
||||
await inputs[0]!.setValue('test_admin')
|
||||
await inputs[1]!.setValue('password')
|
||||
await wrapper.get('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('[role="alert"]').text()).toBe('network unavailable')
|
||||
expect(initialize).not.toHaveBeenCalled()
|
||||
expect(replace).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { ArrowRight, LockKeyhole, ShieldCheck, UserRound } from '@lucide/vue'
|
||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import baiyueLogoWhite from '@/assets/brand/baiyue-logo-white.png'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import { sanitizeInternalPath } from '@/core/routing/accessDecision'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
const access = useAccessPreviewStore()
|
||||
const loading = ref(false)
|
||||
const loginError = ref<ApiErrorDetails | null>(null)
|
||||
const formRef = ref<FormInstance>()
|
||||
const form = reactive({
|
||||
account: '',
|
||||
password: '',
|
||||
})
|
||||
const rules: FormRules<typeof form> = {
|
||||
account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
loginError.value = null
|
||||
const isValid = await formRef.value?.validate().catch(() => false)
|
||||
if (!isValid) return
|
||||
loading.value = true
|
||||
try {
|
||||
await auth.login(form.account, form.password)
|
||||
access.initializeAfterLogin()
|
||||
ElMessage.success('登录成功')
|
||||
const requestedPath = sanitizeInternalPath(route.query.redirect)
|
||||
const targetPath = requestedPath === '/'
|
||||
? access.firstAccessiblePath ?? '/403'
|
||||
: requestedPath
|
||||
await router.replace(targetPath)
|
||||
} catch (error) {
|
||||
loginError.value = getApiErrorDetails(error, '登录失败,请检查账号和密码后重试')
|
||||
ElMessage.error(loginError.value.message)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<section class="login-intro">
|
||||
<div class="login-brand"><img class="login-brand-logo" :src="baiyueLogoWhite" alt="柏悦物流" /></div>
|
||||
<div>
|
||||
<h1>让跨境物流管理<br />清晰、可靠、可追踪</h1>
|
||||
<p class="intro-copy">统一管理企业入驻、内部权限和头程订单,让每一次操作都有边界、有记录。</p>
|
||||
</div>
|
||||
<div class="security-note">
|
||||
<ShieldCheck :size="22" />
|
||||
<span>平台内部系统,请使用授权账号登录</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="login-panel">
|
||||
<div class="login-card">
|
||||
<div class="login-card-icon"><LockKeyhole :size="24" /></div>
|
||||
<h2>登录管理后台</h2>
|
||||
<p>使用平台内部员工账号登录</p>
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" size="large" @submit.prevent="submit">
|
||||
<el-form-item label="账号" prop="account" required>
|
||||
<el-input v-model.trim="form.account" placeholder="请输入账号" :prefix-icon="UserRound" autocomplete="username" maxlength="100" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码" prop="password" required>
|
||||
<el-input v-model="form.password" type="password" show-password placeholder="请输入密码" :prefix-icon="LockKeyhole" autocomplete="current-password" maxlength="128" />
|
||||
</el-form-item>
|
||||
<el-button class="login-submit" native-type="submit" type="primary" :loading="loading">
|
||||
登录 <ArrowRight :size="17" />
|
||||
</el-button>
|
||||
</el-form>
|
||||
<div v-if="loginError" class="login-error" role="alert"><p>{{ loginError.message }}</p><ApiErrorMeta :details="loginError" /></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,184 @@
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
downloadTenantQualification,
|
||||
getPlatformTenant,
|
||||
listPlatformTenants,
|
||||
listTenantQualifications,
|
||||
updatePlatformTenant,
|
||||
uploadPlatformTenantQualification,
|
||||
type PlatformTenantResource,
|
||||
} from '@/modules/iam'
|
||||
import { createPlatformExportTask } from '@/modules/downloads'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import CustomersView from './CustomersView.vue'
|
||||
|
||||
vi.mock('@/modules/iam', () => ({
|
||||
changePlatformTenantStatus: vi.fn(),
|
||||
createPlatformTenant: vi.fn(),
|
||||
downloadTenantQualification: vi.fn(),
|
||||
getPlatformTenant: vi.fn(),
|
||||
listPlatformTenantOrderCounts: vi.fn(),
|
||||
listPlatformTenants: vi.fn(),
|
||||
listTenantQualifications: vi.fn(),
|
||||
qualificationFileName: vi.fn((documentUrl: string) => documentUrl.split('/').at(-1) || '资质文件'),
|
||||
submitPlatformTenantReview: vi.fn(),
|
||||
updatePlatformTenant: vi.fn(),
|
||||
uploadPlatformTenantQualification: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/modules/downloads', () => ({ createPlatformExportTask: vi.fn() }))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
const fullTenant: PlatformTenantResource = {
|
||||
id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'PROFILE_REQUIRED',
|
||||
legalName: '柏悦物流有限公司', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
||||
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com',
|
||||
servicePackage: '基础版', contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30,
|
||||
enterpriseType: '有限责任公司', establishedDate: '2020-01-01', registeredCapital: 1000,
|
||||
registeredCapitalCurrency: 'CNY', registeredAddress: '深圳市宝安区', internalRemark: '重点客户',
|
||||
createdAt: '2026-08-01T10:00:00', approvedAt: null,
|
||||
}
|
||||
|
||||
function tableButtonByText(text: string) {
|
||||
return [...document.querySelectorAll<HTMLButtonElement>('.el-table__body button')]
|
||||
.find((button) => button.textContent?.trim() === text)
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
|
||||
describe('CustomersView', () => {
|
||||
let pinia: ReturnType<typeof createPinia>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:qualification-preview') })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
|
||||
document.body.innerHTML = ''
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:customer:list', 'platform:customer:view', 'platform:customer:edit', 'platform:customer:export']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
vi.mocked(listPlatformTenants).mockResolvedValue({
|
||||
records: [{ ...fullTenant, contactPhone: '138****8000', contactEmail: 'o***@example.com' }],
|
||||
page: 1, size: 10, total: 1, pages: 1,
|
||||
})
|
||||
vi.mocked(getPlatformTenant).mockResolvedValue(fullTenant)
|
||||
vi.mocked(listTenantQualifications).mockResolvedValue([])
|
||||
vi.mocked(updatePlatformTenant).mockResolvedValue(fullTenant)
|
||||
vi.mocked(uploadPlatformTenantQualification).mockResolvedValue({
|
||||
qualificationId: 'qualification-1', reviewId: null, tenantStatus: 'PROFILE_REQUIRED', documentUrl: '/files/license.png',
|
||||
})
|
||||
vi.mocked(createPlatformExportTask).mockResolvedValue({ id: 'export-1', status: 'PENDING' } as never)
|
||||
})
|
||||
|
||||
it('loads the complete customer detail before editing masked list fields', async () => {
|
||||
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
|
||||
tableButtonByText('编辑')?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(getPlatformTenant).toHaveBeenCalledWith(fullTenant.id)
|
||||
const phone = document.querySelector<HTMLInputElement>('input[placeholder="请输入手机号或固定电话"]')
|
||||
const email = document.querySelector<HTMLInputElement>('input[placeholder="如:contact@example.com"]')
|
||||
expect(phone?.value).toBe(fullTenant.contactPhone)
|
||||
expect(email?.value).toBe(fullTenant.contactEmail)
|
||||
})
|
||||
|
||||
it('shows an authenticated image preview for an uploaded qualification', async () => {
|
||||
vi.mocked(listTenantQualifications).mockResolvedValue([{
|
||||
id: 'qualification-1', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: fullTenant.unifiedSocialCreditCode, documentUrl: '/files/license.png',
|
||||
status: 'PENDING', reviewComment: null, validTo: null,
|
||||
}])
|
||||
vi.mocked(downloadTenantQualification).mockResolvedValue(new Blob(['image'], { type: 'image/png' }))
|
||||
|
||||
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
tableButtonByText('编辑')?.click()
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(downloadTenantQualification).toHaveBeenCalledWith(fullTenant.id, '/files/license.png')
|
||||
const preview = document.querySelector<HTMLImageElement>('img[alt="营业执照预览"]')
|
||||
expect(preview?.src).toBe('blob:qualification-preview')
|
||||
})
|
||||
|
||||
it('shows uploaded qualifications in customer detail and opens the full preview', async () => {
|
||||
vi.mocked(listTenantQualifications).mockResolvedValue([{
|
||||
id: 'qualification-1', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: fullTenant.unifiedSocialCreditCode, documentUrl: '/files/license.png',
|
||||
status: 'PENDING', reviewComment: null, validTo: null,
|
||||
}])
|
||||
vi.mocked(downloadTenantQualification).mockResolvedValue(new Blob(['image'], { type: 'image/png' }))
|
||||
|
||||
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
tableButtonByText('详情')?.click()
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
const detailPreview = document.querySelector<HTMLButtonElement>('button[aria-label="查看营业执照:license.png"]')
|
||||
expect(detailPreview?.querySelector('img[alt="营业执照缩略图"]')).not.toBeNull()
|
||||
detailPreview?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(document.querySelector('.qualification-preview img[alt="license.png预览"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('saves customer data and selected qualifications with one action', async () => {
|
||||
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
tableButtonByText('编辑')?.click()
|
||||
await flushPromises()
|
||||
|
||||
const licenseFile = new File(['license'], 'license.png', { type: 'image/png' })
|
||||
const licenseInput = document.querySelector<HTMLInputElement>('.qualification-file input[type="file"]')
|
||||
Object.defineProperty(licenseInput, 'files', { configurable: true, value: [licenseFile] })
|
||||
licenseInput?.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
await flushPromises()
|
||||
|
||||
const buttons = [...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||
expect(buttons.some((button) => button.textContent?.trim() === '上传已选资质')).toBe(false)
|
||||
buttons.find((button) => button.textContent?.trim() === '保存资料和资质')?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(updatePlatformTenant).toHaveBeenCalledWith(fullTenant.id, expect.objectContaining({ tenantName: fullTenant.tenantName }))
|
||||
expect(uploadPlatformTenantQualification).toHaveBeenCalledWith(
|
||||
fullTenant.id,
|
||||
'BUSINESS_LICENSE',
|
||||
licenseFile,
|
||||
undefined,
|
||||
fullTenant.unifiedSocialCreditCode,
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
it('submits the current filters to the backend export service without loading every customer page', async () => {
|
||||
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
|
||||
const exportButton = [...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||
.find((button) => button.textContent?.trim() === '导出Excel')
|
||||
exportButton?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(createPlatformExportTask).toHaveBeenCalledWith({
|
||||
exportType: 'CUSTOMER_LIST', format: 'XLSX', taskName: '客户列表',
|
||||
parameters: { keyword: undefined, status: undefined },
|
||||
})
|
||||
expect(listPlatformTenants).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,669 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Building2, CheckCircle2, Download, Eye, FileCheck2, FileText, FileUp, Pencil, Plus, Power } from '@lucide/vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import { createPlatformExportTask } from '@/modules/downloads'
|
||||
import {
|
||||
changePlatformTenantStatus,
|
||||
createPlatformTenant,
|
||||
downloadTenantQualification,
|
||||
getPlatformTenant,
|
||||
listPlatformTenantOrderCounts,
|
||||
listPlatformTenants,
|
||||
listTenantQualifications,
|
||||
qualificationFileName,
|
||||
submitPlatformTenantReview,
|
||||
updatePlatformTenant,
|
||||
uploadPlatformTenantQualification,
|
||||
type CreatePlatformTenantRequest,
|
||||
type PlatformQualificationType,
|
||||
type PlatformTenantQualification,
|
||||
type PlatformTenantResource,
|
||||
type PlatformTenantStatus,
|
||||
} from '@/modules/iam'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
|
||||
type CustomerFilters = QueryModel & { keyword: string; status: PlatformTenantStatus | '' }
|
||||
type QualificationDraft = {
|
||||
type: PlatformQualificationType
|
||||
label: string
|
||||
required: boolean
|
||||
file: File | null
|
||||
validTo: string
|
||||
uploaded: boolean
|
||||
uploadedName: string
|
||||
documentUrl: string
|
||||
previewUrl: string
|
||||
previewKind: 'image' | 'pdf' | ''
|
||||
previewLoading: boolean
|
||||
previewFailed: boolean
|
||||
uploading: boolean
|
||||
error: string
|
||||
}
|
||||
type DetailQualificationPreview = {
|
||||
url: string
|
||||
kind: 'image' | 'pdf'
|
||||
loading: boolean
|
||||
failed: boolean
|
||||
}
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const loading = ref(false)
|
||||
const exportSubmitting = ref(false)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const result = ref({ records: [] as PlatformTenantResource[], total: 0, pages: 0 })
|
||||
const orderCounts = ref<Record<string, number>>({})
|
||||
const rowActionId = ref('')
|
||||
const editorOpen = ref(false)
|
||||
const editorLoading = ref(false)
|
||||
const saving = ref(false)
|
||||
const submitting = ref(false)
|
||||
const savedFormSnapshot = ref('')
|
||||
const editingId = ref<string | null>(null)
|
||||
const editorStatus = ref<PlatformTenantStatus | null>(null)
|
||||
const formRef = ref<FormInstance>()
|
||||
const detailOpen = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<PlatformTenantResource | null>(null)
|
||||
const detailQualifications = ref<PlatformTenantQualification[]>([])
|
||||
const detailQualificationPreviews = ref<Record<string, DetailQualificationPreview>>({})
|
||||
const qualificationLoadError = ref('')
|
||||
const qualificationPreviewOpen = ref(false)
|
||||
const qualificationPreviewName = ref('')
|
||||
const qualificationPreviewUrl = ref('')
|
||||
const qualificationPreviewKind = ref<'image' | 'pdf' | ''>('')
|
||||
|
||||
const filters = ref<CustomerFilters>({ keyword: '', status: '' })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '公司名称、客户ID或联系人' },
|
||||
{ key: 'status', type: 'select', placeholder: '全部状态', options: [
|
||||
{ label: '待完善', value: 'PROFILE_REQUIRED' }, { label: '待审核', value: 'PENDING' },
|
||||
{ label: '启用', value: 'ACTIVE' }, { label: '已驳回', value: 'REJECTED' },
|
||||
{ label: '已停用', value: 'DISABLED' },
|
||||
] },
|
||||
]
|
||||
|
||||
const emptyForm = (): CreatePlatformTenantRequest => ({
|
||||
tenantName: '', legalName: '', unifiedSocialCreditCode: '', contactName: '', contactPhone: '',
|
||||
contactEmail: '', contactWechat: '', servicePackage: '基础版', salesOwnerName: '', paymentTermDays: 0,
|
||||
enterpriseType: '', establishedDate: null, registeredCapital: null, registeredCapitalCurrency: 'CNY',
|
||||
registeredAddress: '', internalRemark: '',
|
||||
})
|
||||
const form = ref(emptyForm())
|
||||
const rules: FormRules = {
|
||||
tenantName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
|
||||
legalName: [{ required: true, message: '请输入营业执照上的企业名称', trigger: 'blur' }],
|
||||
unifiedSocialCreditCode: [
|
||||
{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
|
||||
{ pattern: /^[0-9A-Z]{18}$/, message: '请输入 18 位大写字母或数字', trigger: 'blur' },
|
||||
],
|
||||
contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
|
||||
contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
|
||||
contactEmail: [{ type: 'email', message: '请输入有效邮箱地址', trigger: 'blur' }],
|
||||
servicePackage: [{ required: true, message: '请选择客户套餐', trigger: 'change' }],
|
||||
paymentTermDays: [{ required: true, message: '请输入账期天数', trigger: 'change' }],
|
||||
}
|
||||
|
||||
function newQualificationDrafts(): QualificationDraft[] {
|
||||
const definitions: Array<Pick<QualificationDraft, 'type' | 'label' | 'required'>> = [
|
||||
{ type: 'BUSINESS_LICENSE', label: '营业执照', required: true },
|
||||
{ type: 'LEGAL_PERSON_ID', label: '法人身份证', required: true },
|
||||
{ type: 'FREIGHT_FORWARDER_CERTIFICATE', label: '货代资质证书', required: false },
|
||||
{ type: 'BANK_ACCOUNT_LICENSE', label: '银行开户许可证', required: false },
|
||||
]
|
||||
return definitions.map((item) => ({
|
||||
...item,
|
||||
file: null,
|
||||
validTo: '',
|
||||
uploaded: false,
|
||||
uploadedName: '',
|
||||
documentUrl: '',
|
||||
previewUrl: '',
|
||||
previewKind: '',
|
||||
previewLoading: false,
|
||||
previewFailed: false,
|
||||
uploading: false,
|
||||
error: '',
|
||||
}))
|
||||
}
|
||||
const qualifications = ref<QualificationDraft[]>(newQualificationDrafts())
|
||||
|
||||
const customerColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 245, fixed: 'left', slotName: 'actions' },
|
||||
{ prop: 'tenantCode', label: '客户ID', minWidth: 170 },
|
||||
{ key: 'company', label: '公司名称', minWidth: 230, slotName: 'company' },
|
||||
{ prop: 'unifiedSocialCreditCode', label: '统一社会信用代码', minWidth: 205, formatter: (row: PlatformTenantResource) => displayText(row.unifiedSocialCreditCode) },
|
||||
{ prop: 'contactName', label: '联系人', minWidth: 120, formatter: (row: PlatformTenantResource) => displayText(row.contactName) },
|
||||
{ prop: 'contactPhone', label: '电话', minWidth: 150, formatter: (row: PlatformTenantResource) => displayText(row.contactPhone) },
|
||||
{ prop: 'salesOwnerName', label: '销售人员', minWidth: 120, formatter: (row: PlatformTenantResource) => displayText(row.salesOwnerName) },
|
||||
{ prop: 'paymentTermDays', label: '账期(天)', width: 105, formatter: (row: PlatformTenantResource) => row.paymentTermDays ?? 0 },
|
||||
{ key: 'status', label: '状态', width: 110, slotName: 'status' },
|
||||
{ key: 'orderCount', label: '运单数', width: 100, slotName: 'orderCount' },
|
||||
{ prop: 'createdAt', label: '入驻时间', minWidth: 165, formatter: (row: PlatformTenantResource) => formatDate(row.createdAt) },
|
||||
]
|
||||
|
||||
let loadSequence = 0
|
||||
const editorTitle = computed(() => editingId.value ? '编辑客户' : '新增客户')
|
||||
const canUploadQualifications = computed(() => !editorStatus.value || ['PROFILE_REQUIRED', 'REJECTED'].includes(editorStatus.value))
|
||||
const canSubmitReview = computed(() => Boolean(editingId.value) && ['PROFILE_REQUIRED', 'REJECTED'].includes(editorStatus.value || ''))
|
||||
const uploadingQualifications = computed(() => qualifications.value.some((item) => item.uploading))
|
||||
const hasSelectedQualifications = computed(() => qualifications.value.some((item) => item.file))
|
||||
const hasUnsavedChanges = computed(() => Boolean(editingId.value) && JSON.stringify(form.value) !== savedFormSnapshot.value)
|
||||
function displayText(value?: string | null) { return value?.trim() || '—' }
|
||||
function formatDate(value?: string | null) { return value ? value.replace('T', ' ').slice(0, 16) : '—' }
|
||||
function statusMeta(status: PlatformTenantStatus) {
|
||||
if (status === 'ACTIVE') return { label: '启用', type: 'success' as const }
|
||||
if (status === 'PROFILE_REQUIRED') return { label: '待完善', type: 'info' as const }
|
||||
if (status === 'PENDING') return { label: '待审核', type: 'warning' as const }
|
||||
if (status === 'REJECTED') return { label: '已驳回', type: 'danger' as const }
|
||||
return { label: '已停用', type: 'info' as const }
|
||||
}
|
||||
|
||||
async function loadCustomers() {
|
||||
const sequence = ++loadSequence
|
||||
loading.value = true; loadError.value = null
|
||||
try {
|
||||
const pageResult = await listPlatformTenants({ page: page.value, size: pageSize.value, keyword: filters.value.keyword.trim() || undefined, status: filters.value.status || undefined })
|
||||
if (sequence !== loadSequence) return
|
||||
result.value = pageResult; orderCounts.value = {}
|
||||
if (access.can('platform:order:list') && pageResult.records.length) {
|
||||
try {
|
||||
const counts = await listPlatformTenantOrderCounts(pageResult.records.map((item) => item.id))
|
||||
if (sequence === loadSequence) orderCounts.value = Object.fromEntries(counts.map((item) => [String(item.tenantId), Number(item.orderCount)]))
|
||||
} catch { /* 主档可继续使用,运单服务失败时不显示模拟数量。 */ }
|
||||
}
|
||||
} catch (error) {
|
||||
if (sequence === loadSequence) loadError.value = getApiErrorDetails(error, '客户列表加载失败,请稍后重试')
|
||||
} finally { if (sequence === loadSequence) loading.value = false }
|
||||
}
|
||||
|
||||
function applyFilters() { if (page.value === 1) void loadCustomers(); else page.value = 1 }
|
||||
function clearDraftPreview(draft: QualificationDraft) {
|
||||
if (draft.previewUrl) URL.revokeObjectURL(draft.previewUrl)
|
||||
draft.previewUrl = ''
|
||||
draft.previewKind = ''
|
||||
draft.previewLoading = false
|
||||
draft.previewFailed = false
|
||||
}
|
||||
function clearQualificationPreviews() {
|
||||
for (const draft of qualifications.value) clearDraftPreview(draft)
|
||||
qualificationPreviewOpen.value = false
|
||||
qualificationPreviewName.value = ''
|
||||
qualificationPreviewUrl.value = ''
|
||||
qualificationPreviewKind.value = ''
|
||||
}
|
||||
function resetEditor() {
|
||||
clearQualificationPreviews()
|
||||
form.value = emptyForm(); qualifications.value = newQualificationDrafts(); qualificationLoadError.value = ''; savedFormSnapshot.value = ''
|
||||
}
|
||||
function openCreate() {
|
||||
editingId.value = null; editorStatus.value = null; resetEditor(); editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
function mapTenantToForm(row: PlatformTenantResource): CreatePlatformTenantRequest {
|
||||
return {
|
||||
tenantName: row.tenantName, legalName: row.legalName || '', unifiedSocialCreditCode: row.unifiedSocialCreditCode || '',
|
||||
contactName: row.contactName || '', contactPhone: row.contactPhone || '', contactEmail: row.contactEmail || '',
|
||||
contactWechat: row.contactWechat || '', servicePackage: row.servicePackage || '基础版', salesOwnerName: row.salesOwnerName || '',
|
||||
paymentTermDays: Number(row.paymentTermDays ?? 0), enterpriseType: row.enterpriseType || '', establishedDate: row.establishedDate || null,
|
||||
registeredCapital: row.registeredCapital === null ? null : Number(row.registeredCapital),
|
||||
registeredCapitalCurrency: row.registeredCapitalCurrency || 'CNY', registeredAddress: row.registeredAddress || '',
|
||||
internalRemark: row.internalRemark || '',
|
||||
}
|
||||
}
|
||||
async function loadEditorQualifications(tenantId: number | string) {
|
||||
qualificationLoadError.value = ''
|
||||
try {
|
||||
const records = await listTenantQualifications(tenantId)
|
||||
for (const draft of qualifications.value) {
|
||||
const item = [...records].reverse().find((record) => record.qualificationType === draft.type && record.status !== 'REJECTED')
|
||||
if (item) {
|
||||
draft.uploaded = true
|
||||
draft.validTo = item.validTo || ''
|
||||
draft.documentUrl = item.documentUrl
|
||||
try { draft.uploadedName = qualificationFileName(item.documentUrl) }
|
||||
catch { draft.uploadedName = '已登记文件' }
|
||||
draft.previewKind = draft.uploadedName.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||
if (draft.previewKind === 'image') void loadQualificationPreview(draft, tenantId, false)
|
||||
}
|
||||
}
|
||||
} catch (error) { qualificationLoadError.value = getApiErrorMessage(error, '资质信息加载失败,可稍后重试') }
|
||||
}
|
||||
async function openEdit(row: PlatformTenantResource) {
|
||||
editingId.value = String(row.id); editorStatus.value = row.status; resetEditor(); form.value = mapTenantToForm(row)
|
||||
editorOpen.value = true; editorLoading.value = true
|
||||
try {
|
||||
const tenant = await getPlatformTenant(row.id)
|
||||
if (editingId.value !== String(row.id)) return
|
||||
editorStatus.value = tenant.status
|
||||
form.value = mapTenantToForm(tenant)
|
||||
savedFormSnapshot.value = JSON.stringify(form.value)
|
||||
await loadEditorQualifications(row.id)
|
||||
await nextTick(() => formRef.value?.clearValidate())
|
||||
} catch (error) {
|
||||
if (editingId.value === String(row.id)) editorOpen.value = false
|
||||
ElMessage.error(getApiErrorMessage(error, '客户完整资料加载失败,请稍后重试'))
|
||||
} finally {
|
||||
if (editingId.value === String(row.id)) editorLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function selectQualificationFile(event: Event, draft: QualificationDraft) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0] || null
|
||||
draft.error = ''; draft.file = null; clearDraftPreview(draft)
|
||||
if (!file) return
|
||||
const extensionValid = /\.(pdf|jpe?g|png)$/i.test(file.name)
|
||||
const mimeValid = ['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)
|
||||
if (!extensionValid || !mimeValid) { draft.error = '仅支持 PDF、JPG、PNG 文件'; input.value = ''; return }
|
||||
if (file.size > 10 * 1024 * 1024) { draft.error = '单个文件不能超过 10MB'; input.value = ''; return }
|
||||
draft.file = file
|
||||
draft.previewKind = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||
draft.previewUrl = URL.createObjectURL(file)
|
||||
}
|
||||
|
||||
async function loadQualificationPreview(draft: QualificationDraft, tenantId: number | string, showError = true) {
|
||||
if (!draft.documentUrl || draft.previewLoading) return false
|
||||
draft.previewLoading = true
|
||||
try {
|
||||
const blob = await downloadTenantQualification(tenantId, draft.documentUrl)
|
||||
if (!blob.size) throw new Error('资质文件内容为空')
|
||||
if (!editorOpen.value || !qualifications.value.includes(draft)) return false
|
||||
clearDraftPreview(draft)
|
||||
draft.previewKind = blob.type === 'application/pdf' || draft.uploadedName.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||
draft.previewUrl = URL.createObjectURL(blob)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (showError) ElMessage.error(getApiErrorMessage(error, '资质文件预览加载失败,请稍后重试'))
|
||||
return false
|
||||
} finally { draft.previewLoading = false }
|
||||
}
|
||||
|
||||
async function openQualificationPreview(draft: QualificationDraft) {
|
||||
if (draft.previewFailed) {
|
||||
if (!draft.uploaded || !editingId.value) {
|
||||
ElMessage.warning('该文件无法预览,请重新选择有效文件')
|
||||
return
|
||||
}
|
||||
clearDraftPreview(draft)
|
||||
draft.previewKind = draft.uploadedName.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||
}
|
||||
if (!draft.previewUrl && draft.uploaded && editingId.value) {
|
||||
await loadQualificationPreview(draft, editingId.value)
|
||||
}
|
||||
if (!draft.previewUrl || !draft.previewKind) return
|
||||
qualificationPreviewName.value = draft.file?.name || draft.uploadedName || draft.label
|
||||
qualificationPreviewUrl.value = draft.previewUrl
|
||||
qualificationPreviewKind.value = draft.previewKind
|
||||
qualificationPreviewOpen.value = true
|
||||
}
|
||||
|
||||
function handleQualificationPreviewError(draft: QualificationDraft) {
|
||||
draft.previewFailed = true
|
||||
if (qualificationPreviewUrl.value === draft.previewUrl) qualificationPreviewOpen.value = false
|
||||
}
|
||||
|
||||
function detailQualificationName(item: PlatformTenantQualification) {
|
||||
try { return qualificationFileName(item.documentUrl) }
|
||||
catch { return `${qualifications.value.find((draft) => draft.type === item.qualificationType)?.label || '资质'}文件` }
|
||||
}
|
||||
|
||||
function clearDetailQualificationPreviews() {
|
||||
for (const preview of Object.values(detailQualificationPreviews.value)) {
|
||||
if (preview.url) URL.revokeObjectURL(preview.url)
|
||||
}
|
||||
detailQualificationPreviews.value = {}
|
||||
qualificationPreviewOpen.value = false
|
||||
}
|
||||
|
||||
async function loadDetailQualificationPreview(item: PlatformTenantQualification, showError = true) {
|
||||
const key = String(item.id)
|
||||
const preview = detailQualificationPreviews.value[key]
|
||||
const tenantId = detail.value?.id
|
||||
if (!preview || !tenantId || !item.documentUrl || preview.loading) return false
|
||||
preview.loading = true
|
||||
try {
|
||||
const blob = await downloadTenantQualification(tenantId, item.documentUrl)
|
||||
if (!blob.size) throw new Error('资质文件内容为空')
|
||||
if (!detailOpen.value || detailQualificationPreviews.value[key] !== preview) return false
|
||||
if (preview.url) URL.revokeObjectURL(preview.url)
|
||||
preview.url = URL.createObjectURL(blob)
|
||||
preview.kind = blob.type === 'application/pdf' || detailQualificationName(item).toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||
preview.failed = false
|
||||
return true
|
||||
} catch (error) {
|
||||
preview.failed = true
|
||||
if (showError) ElMessage.error(getApiErrorMessage(error, '资质文件预览加载失败,请稍后重试'))
|
||||
return false
|
||||
} finally {
|
||||
if (detailQualificationPreviews.value[key] === preview) preview.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openDetailQualificationPreview(item: PlatformTenantQualification) {
|
||||
const preview = detailQualificationPreviews.value[String(item.id)]
|
||||
if (!preview) return
|
||||
if (preview.failed) {
|
||||
if (preview.url) URL.revokeObjectURL(preview.url)
|
||||
preview.url = ''
|
||||
preview.failed = false
|
||||
}
|
||||
if (!preview.url) await loadDetailQualificationPreview(item)
|
||||
if (!preview.url) return
|
||||
qualificationPreviewName.value = detailQualificationName(item)
|
||||
qualificationPreviewUrl.value = preview.url
|
||||
qualificationPreviewKind.value = preview.kind
|
||||
qualificationPreviewOpen.value = true
|
||||
}
|
||||
|
||||
function handleDetailQualificationPreviewError(item: PlatformTenantQualification) {
|
||||
const preview = detailQualificationPreviews.value[String(item.id)]
|
||||
if (!preview) return
|
||||
preview.failed = true
|
||||
if (qualificationPreviewUrl.value === preview.url) qualificationPreviewOpen.value = false
|
||||
}
|
||||
|
||||
async function uploadSelectedQualifications(tenantId: string) {
|
||||
const failures: string[] = []
|
||||
for (const draft of qualifications.value.filter((item) => item.file)) {
|
||||
draft.uploading = true; draft.error = ''
|
||||
try {
|
||||
const uploaded = await uploadPlatformTenantQualification(
|
||||
tenantId, draft.type, draft.file as File, draft.validTo || undefined,
|
||||
draft.type === 'BUSINESS_LICENSE' ? form.value.unifiedSocialCreditCode : undefined,
|
||||
draft.uploaded,
|
||||
)
|
||||
draft.uploaded = true
|
||||
draft.uploadedName = draft.file?.name || '已登记文件'
|
||||
draft.documentUrl = uploaded.documentUrl
|
||||
draft.file = null
|
||||
} catch (error) {
|
||||
draft.error = getApiErrorMessage(error, '上传失败,请重试'); failures.push(draft.label)
|
||||
} finally { draft.uploading = false }
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
async function saveCustomer() {
|
||||
if (!formRef.value || !(await formRef.value.validate().catch(() => false))) return
|
||||
saving.value = true
|
||||
try {
|
||||
const hadSelectedQualifications = hasSelectedQualifications.value
|
||||
let saved: PlatformTenantResource
|
||||
if (editingId.value) {
|
||||
const { unifiedSocialCreditCode: _immutable, ...payload } = form.value
|
||||
saved = await updatePlatformTenant(editingId.value, payload)
|
||||
} else {
|
||||
saved = await createPlatformTenant(form.value)
|
||||
editingId.value = String(saved.id)
|
||||
}
|
||||
editorStatus.value = saved.status
|
||||
savedFormSnapshot.value = JSON.stringify(form.value)
|
||||
const failures = hadSelectedQualifications ? await uploadSelectedQualifications(String(saved.id)) : []
|
||||
if (failures.length) {
|
||||
ElMessage.warning(`客户资料已保存,但${failures.join('、')}上传失败;失败文件已保留,请修正后再次保存`)
|
||||
} else if (hadSelectedQualifications) {
|
||||
ElMessage.success('客户资料和已选资质已保存,尚未提交审核')
|
||||
} else {
|
||||
ElMessage.success('客户资料已保存,尚未提交审核')
|
||||
}
|
||||
await loadCustomers()
|
||||
} catch (error) { ElMessage.error(getApiErrorMessage(error, '客户资料保存失败,请稍后重试')) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function submitReview() {
|
||||
if (!editingId.value) { ElMessage.warning('请先保存客户资料和资质文件'); return }
|
||||
if (!formRef.value || !(await formRef.value.validate().catch(() => false))) return
|
||||
if (hasUnsavedChanges.value) { ElMessage.warning('客户资料有未保存的修改,请先保存资料'); return }
|
||||
if (uploadingQualifications.value) { ElMessage.warning('资质文件正在上传,请稍候再提交审核'); return }
|
||||
if (hasSelectedQualifications.value) { ElMessage.warning('存在尚未保存的已选文件,请先点击“保存资料和资质”'); return }
|
||||
const missing = qualifications.value.filter((item) => item.required && !item.uploaded)
|
||||
for (const item of missing) item.error = `${item.label}为提交审核必填文件`
|
||||
if (missing.length) { ElMessage.warning('请先上传营业执照和法人身份证'); return }
|
||||
try {
|
||||
await ElMessageBox.confirm('提交后客户资料与资质将进入企业审核,审核完成前不能继续替换文件。确认提交吗?', '提交企业审核', { type: 'warning', confirmButtonText: '确认提交', cancelButtonText: '继续完善' })
|
||||
submitting.value = true
|
||||
const saved = await submitPlatformTenantReview(editingId.value)
|
||||
editorStatus.value = saved.status; ElMessage.success('审核单已提交')
|
||||
editorOpen.value = false; await loadCustomers()
|
||||
} catch (error) {
|
||||
if (error !== 'cancel' && error !== 'close') ElMessage.error(getApiErrorMessage(error, '提交审核失败,请稍后重试'))
|
||||
} finally { submitting.value = false }
|
||||
}
|
||||
|
||||
async function showDetail(row: PlatformTenantResource) {
|
||||
clearDetailQualificationPreviews()
|
||||
detail.value = row; detailQualifications.value = []; detailOpen.value = true; detailLoading.value = true
|
||||
try {
|
||||
const [tenant, records] = await Promise.all([getPlatformTenant(row.id), listTenantQualifications(row.id)])
|
||||
detail.value = tenant
|
||||
detailQualifications.value = records
|
||||
detailQualificationPreviews.value = Object.fromEntries(records.map((item) => {
|
||||
const kind = detailQualificationName(item).toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||
return [String(item.id), { url: '', kind, loading: false, failed: false } satisfies DetailQualificationPreview]
|
||||
}))
|
||||
for (const item of records) {
|
||||
if (detailQualificationPreviews.value[String(item.id)]?.kind === 'image') void loadDetailQualificationPreview(item, false)
|
||||
}
|
||||
} catch (error) { ElMessage.error(getApiErrorMessage(error, '客户详情加载失败')) }
|
||||
finally { detailLoading.value = false }
|
||||
}
|
||||
async function toggleStatus(row: PlatformTenantResource) {
|
||||
const next = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'; const verb = next === 'ACTIVE' ? '启用' : '停用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${verb}客户“${row.tenantName}”吗?`, `${verb}客户`, { type: 'warning', confirmButtonText: `确认${verb}`, cancelButtonText: '取消' })
|
||||
rowActionId.value = String(row.id); await changePlatformTenantStatus(row.id, next)
|
||||
ElMessage.success(`客户已${verb}`); await loadCustomers()
|
||||
} catch (error) {
|
||||
if (error !== 'cancel' && error !== 'close') ElMessage.error(getApiErrorMessage(error, `客户${verb}失败`))
|
||||
} finally { rowActionId.value = '' }
|
||||
}
|
||||
|
||||
async function exportCustomers() {
|
||||
exportSubmitting.value = true
|
||||
try {
|
||||
await createPlatformExportTask({
|
||||
exportType: 'CUSTOMER_LIST',
|
||||
format: 'XLSX',
|
||||
taskName: '客户列表',
|
||||
parameters: {
|
||||
keyword: filters.value.keyword.trim() || undefined,
|
||||
status: filters.value.status || undefined,
|
||||
},
|
||||
})
|
||||
ElMessage.success('导出任务已创建,可前往下载中心查看')
|
||||
} catch (error) { ElMessage.error(getApiErrorMessage(error, '客户导出任务创建失败')) }
|
||||
finally { exportSubmitting.value = false }
|
||||
}
|
||||
|
||||
watch([page, pageSize], () => { void loadCustomers() })
|
||||
watch(editorOpen, (open) => { if (!open) clearQualificationPreviews() })
|
||||
watch(detailOpen, (open) => { if (!open) clearDetailQualificationPreviews() })
|
||||
onBeforeUnmount(clearQualificationPreviews)
|
||||
onBeforeUnmount(clearDetailQualificationPreviews)
|
||||
onMounted(loadCustomers)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page customers-page">
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="客户筛选" :fields="queryFields" @search="applyFilters" />
|
||||
<section v-if="loadError" class="surface-panel customers-error" role="alert"><div><strong>客户列表暂时无法加载</strong><p>{{ loadError.message }}</p><ApiErrorMeta :details="loadError" /></div><el-button type="primary" :loading="loading" @click="loadCustomers">重新加载</el-button></section>
|
||||
<section v-else class="surface-panel table-panel" :aria-busy="loading">
|
||||
<div class="customers-table-header"><div class="customers-table-heading"><h2>客户列表</h2><span>共 {{ result.total }} 个客户</span></div><div class="customers-table-actions"><el-button v-if="access.can('platform:customer:export')" :loading="exportSubmitting" :disabled="loading" @click="exportCustomers"><Download :size="16" />导出Excel</el-button><el-button v-if="access.can('platform:customer:create')" type="primary" :disabled="loading" @click="openCreate"><Plus :size="16" />新增客户</el-button></div></div>
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="result.records" :columns="customerColumns" :loading="loading" :total="result.total" aria-label="客户列表" row-key="id" empty-text="暂无符合筛选条件的客户">
|
||||
<template #actions="{ row }"><div class="table-actions"><el-button v-if="access.can('platform:customer:view')" link type="primary" @click="showDetail(row as PlatformTenantResource)"><Eye :size="15" />详情</el-button><el-button v-if="access.can('platform:customer:view') && access.can('platform:customer:edit')" link type="primary" @click="openEdit(row as PlatformTenantResource)"><Pencil :size="15" />编辑</el-button><el-button v-if="access.can('platform:customer:status') && ['ACTIVE','DISABLED'].includes((row as PlatformTenantResource).status)" link :type="(row as PlatformTenantResource).status === 'ACTIVE' ? 'danger' : 'success'" :loading="rowActionId === String((row as PlatformTenantResource).id)" @click="toggleStatus(row as PlatformTenantResource)"><Power :size="15" />{{ (row as PlatformTenantResource).status === 'ACTIVE' ? '停用' : '启用' }}</el-button></div></template>
|
||||
<template #company="{ row }"><div class="customer-company-cell"><span><Building2 :size="18" /></span><strong>{{ (row as PlatformTenantResource).tenantName }}</strong></div></template>
|
||||
<template #status="{ row }"><el-tag :type="statusMeta((row as PlatformTenantResource).status).type" effect="light">{{ statusMeta((row as PlatformTenantResource).status).label }}</el-tag></template>
|
||||
<template #orderCount="{ row }">{{ access.can('platform:order:list') ? (orderCounts[String((row as PlatformTenantResource).id)] ?? '—') : '—' }}</template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="editorTitle" size="760px" class="business-drawer customer-editor" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" v-loading="editorLoading" :model="form" :rules="rules" label-position="top" class="drawer-form" :disabled="editorLoading || saving || submitting || uploadingQualifications">
|
||||
<div class="form-section"><h3>基础资料</h3><div class="form-grid two-cols">
|
||||
<el-form-item label="公司名称" prop="tenantName" required><el-input v-model="form.tenantName" placeholder="请输入工商登记公司名称" maxlength="128" /></el-form-item>
|
||||
<el-form-item label="营业执照企业名称" prop="legalName" required><el-input v-model="form.legalName" placeholder="请输入营业执照上的企业名称" maxlength="128" /></el-form-item>
|
||||
<el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode" required><el-input v-model="form.unifiedSocialCreditCode" :disabled="Boolean(editingId)" placeholder="请输入18位大写字母或数字" maxlength="18" @input="form.unifiedSocialCreditCode = String($event).toUpperCase()" /></el-form-item>
|
||||
<el-form-item label="企业类型" prop="enterpriseType"><el-input v-model="form.enterpriseType" placeholder="如:有限责任公司" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="成立日期" prop="establishedDate"><el-date-picker v-model="form.establishedDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择成立日期" :disabled-date="(date: Date) => date.getTime() > Date.now()" /></el-form-item>
|
||||
<el-form-item label="注册资本" prop="registeredCapital"><div class="capital-input"><el-input-number v-model="form.registeredCapital" :min="0" :precision="2" controls-position="right" /><el-select v-model="form.registeredCapitalCurrency" aria-label="注册资本币种"><el-option label="人民币 CNY" value="CNY" /><el-option label="美元 USD" value="USD" /><el-option label="港币 HKD" value="HKD" /></el-select></div></el-form-item>
|
||||
</div><el-form-item label="注册地址" prop="registeredAddress"><el-input v-model="form.registeredAddress" placeholder="请输入省市区、街道及门牌信息" maxlength="500" /></el-form-item></div>
|
||||
|
||||
<div class="form-section"><h3>联系与商务</h3><div class="form-grid two-cols">
|
||||
<el-form-item label="联系人" prop="contactName" required><el-input v-model="form.contactName" placeholder="请输入主要联系人姓名" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="联系电话" prop="contactPhone" required><el-input v-model="form.contactPhone" placeholder="请输入手机号或固定电话" maxlength="32" /></el-form-item>
|
||||
<el-form-item label="联系邮箱" prop="contactEmail"><el-input v-model="form.contactEmail" placeholder="如:contact@example.com" maxlength="128" /></el-form-item>
|
||||
<el-form-item label="联系微信" prop="contactWechat"><el-input v-model="form.contactWechat" placeholder="请输入联系人微信号" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="客户套餐" prop="servicePackage" required><el-select v-model="form.servicePackage"><el-option label="基础版" value="基础版" /><el-option label="专业版" value="专业版" /><el-option label="企业版" value="企业版" /></el-select></el-form-item>
|
||||
<el-form-item label="销售人员" prop="salesOwnerName"><el-input v-model="form.salesOwnerName" placeholder="请输入负责销售人员" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="账期(天)" prop="paymentTermDays" required><el-input-number v-model="form.paymentTermDays" :min="0" :max="365" controls-position="right" /></el-form-item>
|
||||
</div><el-form-item label="内部备注" prop="internalRemark"><el-input v-model="form.internalRemark" type="textarea" :rows="3" placeholder="请输入仅平台人员可见的客户备注" maxlength="1000" show-word-limit /></el-form-item></div>
|
||||
|
||||
<div class="form-section qualification-section"><div class="qualification-heading"><div><h3>资质文件</h3><p>先选择并上传文件;上传成功不会创建审核单,点击“提交审核”并确认后才会进入审核。</p></div><el-tag v-if="editorStatus" :type="statusMeta(editorStatus).type" effect="light">{{ statusMeta(editorStatus).label }}</el-tag></div>
|
||||
<div v-if="qualificationLoadError" class="qualification-load-error" role="alert">{{ qualificationLoadError }}<el-button v-if="editingId" link type="primary" @click="loadEditorQualifications(editingId)">重试</el-button></div>
|
||||
<div class="qualification-table" role="table" aria-label="客户资质文件">
|
||||
<div class="qualification-row qualification-header" role="row"><span role="columnheader">文件类型</span><span role="columnheader">上传文件</span><span role="columnheader">有效期</span></div>
|
||||
<div v-for="draft in qualifications" :key="draft.type" class="qualification-row" role="row">
|
||||
<div class="qualification-label" role="cell"><span v-if="draft.required" aria-hidden="true">*</span>{{ draft.label }}<CheckCircle2 v-if="draft.uploaded" :size="16" aria-label="已上传" /></div>
|
||||
<div class="qualification-file" role="cell">
|
||||
<button v-if="draft.file || draft.uploaded" type="button" class="qualification-preview-trigger" :class="{ 'is-loading': draft.previewLoading }" :disabled="draft.previewLoading" :aria-label="`预览${draft.label}:${draft.file?.name || draft.uploadedName}`" @click="openQualificationPreview(draft)">
|
||||
<img v-if="draft.previewUrl && draft.previewKind === 'image' && !draft.previewFailed" :src="draft.previewUrl" :alt="`${draft.label}预览`" @error="handleQualificationPreviewError(draft)" />
|
||||
<span v-else class="qualification-preview-placeholder"><FileText :size="20" /><small>{{ draft.previewKind === 'pdf' ? 'PDF' : '文件' }}</small></span>
|
||||
<span class="qualification-preview-action"><Eye :size="14" />{{ draft.previewLoading ? '读取中' : (draft.previewFailed ? '重试' : '查看') }}</span>
|
||||
</button>
|
||||
<div class="qualification-file-control"><label class="file-picker" :class="{ 'is-disabled': !canUploadQualifications || draft.uploading }"><FileUp :size="16" /><span>{{ draft.uploading ? '上传中' : (draft.file ? '已选择新文件' : (draft.uploaded ? '更换文件' : '选择文件')) }}</span><input type="file" accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png" :disabled="!canUploadQualifications || draft.uploading" @change="selectQualificationFile($event, draft)" /></label><span class="qualification-file-name" :title="draft.file?.name || draft.uploadedName">{{ draft.file?.name || draft.uploadedName || '未选择文件' }}</span><small v-if="draft.error" class="qualification-error" role="alert">{{ draft.error }}</small></div>
|
||||
</div>
|
||||
<div role="cell"><el-date-picker v-model="draft.validTo" type="date" value-format="YYYY-MM-DD" placeholder="请选择有效期" :disabled="!canUploadQualifications || draft.uploaded" /></div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="qualification-hint">支持 PDF、JPG、PNG,单个文件不超过 10MB;<span>*</span> 为提交审核必填项。</p>
|
||||
</div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer customer-editor-footer"><span>保存资料时会一并上传已选资质;进入审核仍需点击“提交审核”并再次确认</span><div><el-button :disabled="editorLoading || saving || submitting || uploadingQualifications" @click="editorOpen = false">关闭</el-button><el-button :loading="saving" :disabled="editorLoading || submitting || uploadingQualifications" @click="saveCustomer">保存资料和资质</el-button><el-button v-if="canSubmitReview" type="primary" :loading="submitting" :disabled="editorLoading || saving || uploadingQualifications" @click="submitReview">提交审核</el-button></div></div></template>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog v-model="qualificationPreviewOpen" :title="qualificationPreviewName || '查看资质文件'" width="min(860px, calc(100vw - 28px))" class="qualification-preview-dialog" destroy-on-close>
|
||||
<div class="qualification-preview">
|
||||
<img v-if="qualificationPreviewUrl && qualificationPreviewKind === 'image'" :src="qualificationPreviewUrl" :alt="`${qualificationPreviewName}预览`" />
|
||||
<iframe v-else-if="qualificationPreviewUrl && qualificationPreviewKind === 'pdf'" :src="qualificationPreviewUrl" :title="`${qualificationPreviewName} PDF 预览`" />
|
||||
</div>
|
||||
<template #footer><el-button @click="qualificationPreviewOpen = false">关闭预览</el-button></template>
|
||||
</el-dialog>
|
||||
|
||||
<el-drawer v-model="detailOpen" title="客户详情" size="620px" class="business-drawer">
|
||||
<div v-loading="detailLoading" class="customer-detail">
|
||||
<template v-if="detail">
|
||||
<div class="detail-title">
|
||||
<span><Building2 :size="22" /></span>
|
||||
<div><h3>{{ detail.tenantName }}</h3><p>{{ detail.tenantCode }}</p></div>
|
||||
<el-tag :type="statusMeta(detail.status).type" effect="light">{{ statusMeta(detail.status).label }}</el-tag>
|
||||
</div>
|
||||
|
||||
<section class="customer-detail-section" aria-labelledby="customer-profile-heading">
|
||||
<h4 id="customer-profile-heading">企业资料</h4>
|
||||
<dl class="customer-detail-grid">
|
||||
<div class="customer-detail-item is-wide"><dt>统一社会信用代码</dt><dd>{{ displayText(detail.unifiedSocialCreditCode) }}</dd></div>
|
||||
<div class="customer-detail-item"><dt>联系人</dt><dd>{{ displayText(detail.contactName) }}</dd></div>
|
||||
<div class="customer-detail-item"><dt>联系电话</dt><dd>{{ displayText(detail.contactPhone) }}</dd></div>
|
||||
<div class="customer-detail-item is-wide"><dt>联系邮箱</dt><dd>{{ displayText(detail.contactEmail) }}</dd></div>
|
||||
<div class="customer-detail-item"><dt>客户套餐</dt><dd>{{ displayText(detail.servicePackage) }}</dd></div>
|
||||
<div class="customer-detail-item"><dt>账期</dt><dd>{{ detail.paymentTermDays ?? 0 }} 天</dd></div>
|
||||
<div class="customer-detail-item"><dt>销售人员</dt><dd>{{ displayText(detail.salesOwnerName) }}</dd></div>
|
||||
<div class="customer-detail-item"><dt>入驻时间</dt><dd>{{ formatDate(detail.createdAt) }}</dd></div>
|
||||
<div class="customer-detail-item is-wide"><dt>注册地址</dt><dd>{{ displayText(detail.registeredAddress) }}</dd></div>
|
||||
<div class="customer-detail-item is-wide"><dt>内部备注</dt><dd>{{ displayText(detail.internalRemark) }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section class="customer-detail-section detail-qualification-list" aria-labelledby="customer-qualification-heading">
|
||||
<div class="detail-section-heading"><h4 id="customer-qualification-heading">资质文件</h4><span>共 {{ detailQualifications.length }} 份</span></div>
|
||||
<div v-if="detailQualifications.length" class="detail-qualification-items">
|
||||
<button v-for="item in detailQualifications" :key="String(item.id)" type="button" class="detail-qualification-item" :disabled="detailQualificationPreviews[String(item.id)]?.loading" :aria-label="`查看${qualifications.find((draft) => draft.type === item.qualificationType)?.label || item.qualificationType}:${detailQualificationName(item)}`" @click="openDetailQualificationPreview(item)">
|
||||
<span class="detail-qualification-icon">
|
||||
<img v-if="detailQualificationPreviews[String(item.id)]?.url && detailQualificationPreviews[String(item.id)]?.kind === 'image' && !detailQualificationPreviews[String(item.id)]?.failed" :src="detailQualificationPreviews[String(item.id)]?.url" :alt="`${qualifications.find((draft) => draft.type === item.qualificationType)?.label || item.qualificationType}缩略图`" @error="handleDetailQualificationPreviewError(item)" />
|
||||
<FileText v-else :size="20" />
|
||||
<small v-if="detailQualificationPreviews[String(item.id)]?.kind === 'pdf'">PDF</small>
|
||||
</span>
|
||||
<span class="detail-qualification-copy"><strong>{{ qualifications.find((draft) => draft.type === item.qualificationType)?.label || item.qualificationType }}</strong><small class="detail-qualification-file-name">{{ detailQualificationName(item) }}</small><small>{{ item.validTo ? `有效期至 ${item.validTo}` : '长期有效或未设置有效期' }}</small></span>
|
||||
<span class="detail-qualification-meta"><el-tag :type="item.status === 'APPROVED' ? 'success' : item.status === 'REJECTED' ? 'danger' : 'warning'" size="small" effect="light">{{ item.status === 'APPROVED' ? '已通过' : item.status === 'REJECTED' ? '已驳回' : '待审核' }}</el-tag><span><Eye :size="14" />{{ detailQualificationPreviews[String(item.id)]?.loading ? '读取中' : (detailQualificationPreviews[String(item.id)]?.failed ? '重试' : '查看') }}</span></span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="detail-empty-qualification"><FileCheck2 :size="20" /><span>暂未上传资质文件</span></div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.customers-error { display:flex; min-width:0; align-items:center; justify-content:space-between; gap:16px; padding:18px 20px; border-color:#fecdca; background:#fffafa; }
|
||||
.customers-error strong { color:#7a271a; font-size:16px; } .customers-error p { margin:4px 0 0; color:#b54708; font-size:12px; overflow-wrap:anywhere; }
|
||||
.customers-table-header { display:flex; min-width:0; align-items:center; justify-content:space-between; gap:16px; padding:16px 18px; border-bottom:1px solid var(--cc-border); }
|
||||
.customers-table-heading { display:flex; min-width:0; align-items:baseline; gap:10px; } .customers-table-heading h2 { margin:0; color:var(--cc-text); font-size:16px; } .customers-table-heading span { color:var(--cc-muted); font-size:12px; white-space:nowrap; }
|
||||
.customers-table-actions { display:flex; flex-wrap:wrap; gap:8px; } .customers-table-actions :deep(.el-button + .el-button) { margin-left:0; }
|
||||
.customer-company-cell { display:flex; min-width:0; align-items:center; gap:10px; } .customer-company-cell > span,.detail-title > span { display:grid; width:34px; height:34px; flex:0 0 auto; place-items:center; border-radius:7px; background:#eef4ff; color:var(--cc-primary); } .customer-company-cell strong { overflow:hidden; text-overflow:ellipsis; }
|
||||
.capital-input { display:grid; grid-template-columns:minmax(0,1fr) 130px; width:100%; gap:8px; } .capital-input :deep(.el-input-number),.capital-input :deep(.el-select) { width:100%; }
|
||||
.qualification-heading { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; } .qualification-heading h3 { margin-bottom:4px; } .qualification-heading p,.qualification-hint { margin:0; color:var(--cc-muted); font-size:12px; line-height:1.6; } .qualification-hint { margin-top:12px; } .qualification-hint span,.qualification-label > span { color:var(--el-color-danger); }
|
||||
.qualification-table { overflow:hidden; margin-top:14px; border:1px solid var(--cc-border); border-radius:8px; } .qualification-row { display:grid; grid-template-columns:180px minmax(300px,1fr) 180px; min-width:0; border-top:1px solid var(--cc-border); } .qualification-row:first-child { border-top:0; } .qualification-row > * { display:flex; min-width:0; min-height:68px; align-items:center; padding:12px 14px; } .qualification-header { min-height:44px; background:#f7f8fc; color:var(--cc-muted); font-size:12px; font-weight:600; } .qualification-header > * { min-height:44px; }
|
||||
.qualification-label { gap:5px; font-weight:600; } .qualification-label svg { margin-left:auto; color:var(--el-color-success); }
|
||||
.qualification-file { gap:12px; } .qualification-file-control { display:flex; min-width:0; flex:1; flex-wrap:wrap; align-items:center; gap:8px; } .file-picker { position:relative; display:inline-flex; min-height:36px; flex:0 0 auto; align-items:center; gap:7px; overflow:hidden; padding:0 12px; border:1px solid var(--cc-border); border-radius:6px; background:#fff; color:var(--cc-text); cursor:pointer; } .file-picker:focus-within { outline:2px solid color-mix(in srgb,var(--cc-primary) 35%,transparent); outline-offset:2px; } .file-picker.is-disabled { cursor:not-allowed; opacity:.6; } .file-picker input { position:absolute; inset:0; width:100%; height:100%; opacity:0; cursor:inherit; } .qualification-file-name { min-width:0; max-width:180px; overflow:hidden; color:var(--cc-muted); font-size:12px; text-overflow:ellipsis; white-space:nowrap; } .qualification-error { width:100%; color:var(--el-color-danger); line-height:1.4; }
|
||||
.qualification-preview-trigger { position:relative; display:grid; width:68px; height:68px; flex:0 0 68px; overflow:hidden; place-items:center; padding:0; border:1px solid var(--cc-border); border-radius:6px; background:#f8fafc; color:var(--cc-muted); cursor:pointer; }
|
||||
.qualification-preview-trigger:hover { border-color:var(--cc-primary); color:var(--cc-primary); }
|
||||
.qualification-preview-trigger:focus-visible { outline:2px solid color-mix(in srgb,var(--cc-primary) 42%,transparent); outline-offset:2px; }
|
||||
.qualification-preview-trigger:disabled { cursor:wait; opacity:.72; }
|
||||
.qualification-preview-trigger img { width:100%; height:100%; object-fit:contain; background:#fff; }
|
||||
.qualification-preview-placeholder { display:grid; place-items:center; gap:2px; }
|
||||
.qualification-preview-placeholder small { font-size:10px; font-weight:700; }
|
||||
.qualification-preview-action { position:absolute; inset:auto 0 0; display:flex; min-height:22px; align-items:center; justify-content:center; gap:3px; background:rgba(23,32,51,.78); color:#fff; font-size:10px; }
|
||||
.qualification-preview { display:grid; max-height:min(70vh,760px); min-height:240px; place-items:center; overflow:auto; border:1px solid var(--cc-border); border-radius:6px; background:#f8fafc; }
|
||||
.qualification-preview img { display:block; max-width:100%; height:auto; }
|
||||
.qualification-preview iframe { width:100%; min-height:min(68vh,720px); border:0; background:#fff; }
|
||||
.qualification-load-error { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-top:12px; padding:10px 12px; border:1px solid #fecdca; border-radius:6px; background:#fffafa; color:#b42318; font-size:12px; }
|
||||
.customer-editor :deep(.el-drawer__body) { min-height:0; overflow-y:auto; overscroll-behavior:contain; }
|
||||
.customer-editor :deep(.el-drawer__footer) { flex:0 0 auto; }
|
||||
.customer-editor-footer { display:flex; align-items:center; justify-content:space-between; gap:16px; } .customer-editor-footer > span { color:var(--cc-muted); font-size:12px; text-align:left; } .customer-editor-footer > div { display:flex; flex:0 0 auto; gap:8px; } .customer-editor-footer :deep(.el-button + .el-button) { margin-left:0; }
|
||||
.customer-detail { min-height:200px; padding:20px 24px 24px; }
|
||||
.detail-title { display:grid; grid-template-columns:44px minmax(0,1fr) auto; align-items:center; gap:12px; margin-bottom:24px; padding:4px 0 20px; border-bottom:1px solid var(--cc-border); }
|
||||
.detail-title > span { width:44px; height:44px; border-radius:10px; }
|
||||
.detail-title h3 { margin:0; overflow:hidden; color:var(--cc-text); font-size:20px; line-height:1.35; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.detail-title p { margin:4px 0 0; color:var(--cc-muted); font-size:12px; letter-spacing:.02em; }
|
||||
.customer-detail-section + .customer-detail-section { margin-top:24px; }
|
||||
.customer-detail-section h4 { margin:0 0 12px; color:var(--cc-text); font-size:14px; }
|
||||
.customer-detail-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); overflow:hidden; margin:0; border:1px solid var(--cc-border); border-radius:10px; background:#fff; }
|
||||
.customer-detail-item { min-width:0; padding:13px 16px; border-bottom:1px solid var(--cc-border); }
|
||||
.customer-detail-item:nth-child(odd):not(.is-wide) { border-right:1px solid var(--cc-border); }
|
||||
.customer-detail-item.is-wide { grid-column:1 / -1; }
|
||||
.customer-detail-item:last-child { border-bottom:0; }
|
||||
.customer-detail-item dt { margin-bottom:5px; color:var(--cc-muted); font-size:12px; line-height:1.4; }
|
||||
.customer-detail-item dd { margin:0; color:var(--cc-text); font-size:14px; font-weight:600; line-height:1.55; overflow-wrap:anywhere; }
|
||||
.detail-section-heading { display:flex; align-items:baseline; justify-content:space-between; gap:12px; }
|
||||
.detail-section-heading h4 { margin-bottom:12px; }
|
||||
.detail-section-heading span { color:var(--cc-muted); font-size:12px; }
|
||||
.detail-qualification-items { display:flex; flex-direction:column; gap:8px; }
|
||||
.detail-qualification-item { display:grid; width:100%; grid-template-columns:52px minmax(0,1fr) auto; align-items:center; gap:12px; padding:12px 14px; border:1px solid var(--cc-border); border-radius:8px; background:#fff; color:inherit; text-align:left; cursor:pointer; }
|
||||
.detail-qualification-item:hover { border-color:color-mix(in srgb,var(--cc-primary) 48%,var(--cc-border)); background:#fbfdff; }
|
||||
.detail-qualification-item:focus-visible { outline:2px solid color-mix(in srgb,var(--cc-primary) 42%,transparent); outline-offset:2px; }
|
||||
.detail-qualification-item:disabled { cursor:wait; opacity:.75; }
|
||||
.detail-qualification-icon { display:grid; width:52px; height:52px; overflow:hidden; place-items:center; border-radius:8px; background:#eef4ff; color:var(--cc-primary); }
|
||||
.detail-qualification-icon img { width:100%; height:100%; object-fit:contain; background:#fff; }
|
||||
.detail-qualification-icon small { font-size:9px; font-weight:700; }
|
||||
.detail-qualification-copy { min-width:0; }
|
||||
.detail-qualification-item strong,.detail-qualification-item small { display:block; }
|
||||
.detail-qualification-item strong { color:var(--cc-text); font-size:13px; }
|
||||
.detail-qualification-item small { margin-top:4px; color:var(--cc-muted); font-size:11px; line-height:1.4; }
|
||||
.detail-qualification-file-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.detail-qualification-meta { display:flex; align-items:flex-end; gap:8px; flex-direction:column; }
|
||||
.detail-qualification-meta > span { display:flex; align-items:center; gap:4px; color:var(--cc-primary); font-size:11px; font-weight:600; }
|
||||
.detail-empty-qualification { display:flex; min-height:88px; align-items:center; justify-content:center; gap:8px; border:1px dashed var(--cc-border); border-radius:8px; background:#fafbfc; color:var(--cc-muted); font-size:12px; }
|
||||
@media (max-width:720px) { .customers-error,.customers-table-header,.customer-editor-footer { align-items:stretch; flex-direction:column; } .customers-table-actions { display:grid; grid-template-columns:1fr 1fr; } .customers-table-actions :deep(.el-button) { min-height:40px; margin:0; } .qualification-table { overflow-x:auto; } .qualification-row { min-width:640px; } .customer-editor-footer > div { display:grid; grid-template-columns:repeat(auto-fit,minmax(110px,1fr)); width:100%; } .customer-editor-footer :deep(.el-button) { min-height:40px; margin:0; } .customer-detail { padding:16px; } .customer-detail-grid { grid-template-columns:1fr; } .customer-detail-item,.customer-detail-item:nth-child(odd):not(.is-wide) { grid-column:1; border-right:0; } .customer-detail-item:last-child { border-bottom:0; } }
|
||||
@media (max-width:480px) { .detail-qualification-item { grid-template-columns:44px minmax(0,1fr); } .detail-qualification-icon { width:44px; height:44px; } .detail-qualification-meta { grid-column:2; align-items:center; flex-direction:row; justify-content:space-between; } }
|
||||
@media (max-width:360px) { .customers-table-actions,.capital-input { grid-template-columns:1fr; } }
|
||||
</style>
|
||||
@@ -0,0 +1,194 @@
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
approveEnterpriseReview,
|
||||
downloadTenantQualification,
|
||||
listEnterpriseReviews,
|
||||
listTenantQualifications,
|
||||
qualificationFileName,
|
||||
rejectEnterpriseReview,
|
||||
type EnterpriseReview,
|
||||
type PlatformTenantQualification,
|
||||
} from '@/modules/iam'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import EnterpriseReviewsView from './EnterpriseReviewsView.vue'
|
||||
|
||||
vi.mock('@/modules/iam', () => ({
|
||||
listEnterpriseReviews: vi.fn(),
|
||||
listTenantQualifications: vi.fn(),
|
||||
downloadTenantQualification: vi.fn(),
|
||||
qualificationFileName: vi.fn(() => 'test.png'),
|
||||
approveEnterpriseReview: vi.fn(),
|
||||
rejectEnterpriseReview: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
const pendingReview: EnterpriseReview = {
|
||||
id: 202607290005,
|
||||
tenantId: 202607290002,
|
||||
tenantName: '深圳测试跨境科技有限公司',
|
||||
tenantCode: 'TEN202607290002',
|
||||
qualificationId: 202607290004,
|
||||
qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: '91440300XXXXXXXXXX',
|
||||
documentUrl: '/api/merchant/v1/files/qualifications/test.png',
|
||||
contactName: '张三',
|
||||
contactPhone: '13800138000',
|
||||
contactEmail: 'test01@example.com',
|
||||
submittedAt: '2026-07-29T10:00:00Z',
|
||||
status: 'PENDING',
|
||||
}
|
||||
|
||||
const pendingQualification: PlatformTenantQualification = {
|
||||
id: 202607290004,
|
||||
tenantId: pendingReview.tenantId,
|
||||
qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: '91440300XXXXXXXXXX',
|
||||
documentUrl: '/api/merchant/v1/files/qualifications/test.png',
|
||||
status: 'PENDING',
|
||||
reviewComment: null,
|
||||
}
|
||||
|
||||
async function mountView() {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:customer:review', 'platform:customer:approve', 'platform:customer:reject']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
const wrapper = mount(EnterpriseReviewsView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia, ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
function buttonByText(text: string) {
|
||||
return [...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||
.find((button) => button.textContent?.trim() === text)
|
||||
}
|
||||
|
||||
function tableButtonByText(text: string) {
|
||||
return [...document.querySelectorAll<HTMLButtonElement>('.el-table__body button')]
|
||||
.find((button) => button.textContent?.trim() === text)
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
|
||||
describe('EnterpriseReviewsView', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
vi.mocked(listEnterpriseReviews).mockReset()
|
||||
vi.mocked(listTenantQualifications).mockReset()
|
||||
vi.mocked(downloadTenantQualification).mockReset()
|
||||
vi.mocked(downloadTenantQualification).mockResolvedValue(new Blob(['image'], { type: 'image/png' }))
|
||||
vi.mocked(approveEnterpriseReview).mockReset()
|
||||
vi.mocked(rejectEnterpriseReview).mockReset()
|
||||
vi.mocked(qualificationFileName).mockReset()
|
||||
vi.mocked(qualificationFileName).mockReturnValue('test.png')
|
||||
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:qualification-preview') })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('renders an honest empty state from the real review endpoint', async () => {
|
||||
vi.mocked(listEnterpriseReviews).mockResolvedValue([])
|
||||
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(listEnterpriseReviews).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.text()).toContain('暂无待审核企业')
|
||||
expect(wrapper.text()).toContain('共 0 条')
|
||||
})
|
||||
|
||||
it('shows review identity and submits approval with the review id', async () => {
|
||||
vi.mocked(listEnterpriseReviews).mockResolvedValue([pendingReview])
|
||||
vi.mocked(approveEnterpriseReview).mockResolvedValue(undefined)
|
||||
|
||||
const wrapper = await mountView()
|
||||
expect(wrapper.text()).toContain('深圳测试跨境科技有限公司')
|
||||
expect(wrapper.text()).toContain('91440300XXXXXXXXXX')
|
||||
|
||||
const approve = tableButtonByText('通过')
|
||||
expect(approve).toBeDefined()
|
||||
approve?.click()
|
||||
await flushPromises()
|
||||
|
||||
const confirm = buttonByText('确认通过')
|
||||
expect(confirm).toBeDefined()
|
||||
confirm?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(approveEnterpriseReview).toHaveBeenCalledWith(
|
||||
pendingReview.id,
|
||||
'企业资料与必填资质完整、清晰,审核通过',
|
||||
)
|
||||
expect(wrapper.text()).toContain('暂无待审核企业')
|
||||
expect(wrapper.text()).toContain('共 0 条')
|
||||
})
|
||||
|
||||
it('loads tenant qualifications when the reviewer opens the detail drawer', async () => {
|
||||
vi.mocked(listEnterpriseReviews).mockResolvedValue([pendingReview])
|
||||
vi.mocked(listTenantQualifications).mockResolvedValue([pendingQualification])
|
||||
|
||||
const wrapper = await mountView()
|
||||
tableButtonByText('详情')?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(listTenantQualifications).toHaveBeenCalledWith(pendingReview.tenantId)
|
||||
expect(downloadTenantQualification).toHaveBeenCalledWith(pendingReview.tenantId, pendingQualification.documentUrl)
|
||||
expect(wrapper.text()).toContain('信用代码:91440300XXXXXXXXXX')
|
||||
expect(document.querySelector<HTMLImageElement>('.qualification-thumbnail img')?.getAttribute('alt')).toBe('营业执照缩略图')
|
||||
})
|
||||
|
||||
it('keeps qualification loading recoverable without using a direct file link', async () => {
|
||||
vi.mocked(listEnterpriseReviews).mockResolvedValue([pendingReview])
|
||||
vi.mocked(listTenantQualifications).mockRejectedValue(new Error('qualification unavailable'))
|
||||
|
||||
const wrapper = await mountView()
|
||||
tableButtonByText('详情')?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.text()).toContain('资质暂时无法加载')
|
||||
expect(wrapper.text()).toContain('qualification unavailable')
|
||||
expect(wrapper.find('a[href*="qualifications"]').exists()).toBe(false)
|
||||
expect(buttonByText('重新加载')).toBeDefined()
|
||||
})
|
||||
|
||||
it('renders uploaded PDF qualifications in a PDF preview frame', async () => {
|
||||
vi.mocked(listEnterpriseReviews).mockResolvedValue([pendingReview])
|
||||
vi.mocked(listTenantQualifications).mockResolvedValue([pendingQualification])
|
||||
vi.mocked(downloadTenantQualification).mockResolvedValue(new Blob(['%PDF-1.4'], { type: 'application/pdf' }))
|
||||
vi.mocked(qualificationFileName).mockReturnValue('test.pdf')
|
||||
|
||||
await mountView()
|
||||
tableButtonByText('详情')?.click()
|
||||
await flushPromises()
|
||||
document.querySelector<HTMLButtonElement>('.qualification-thumbnail')?.click()
|
||||
await flushPromises()
|
||||
|
||||
const frame = document.querySelector<HTMLIFrameElement>('.qualification-preview iframe')
|
||||
expect(frame?.getAttribute('src')).toBe('blob:qualification-preview')
|
||||
expect(frame?.getAttribute('title')).toContain('PDF 预览')
|
||||
expect(downloadTenantQualification).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the page recoverable when the endpoint fails', async () => {
|
||||
vi.mocked(listEnterpriseReviews).mockRejectedValue(new Error('IAM unavailable'))
|
||||
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain('审核列表暂时无法加载')
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain('IAM unavailable')
|
||||
expect(buttonByText('重新加载')).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,500 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Eye, FileCheck2, FileText, ImageOff, LoaderCircle, ShieldCheck, ShieldX } from '@lucide/vue'
|
||||
import {
|
||||
approveEnterpriseReview,
|
||||
downloadTenantQualification,
|
||||
listEnterpriseReviews,
|
||||
listTenantQualifications,
|
||||
qualificationFileName,
|
||||
rejectEnterpriseReview,
|
||||
type EnterpriseReview,
|
||||
type PlatformTenantQualification,
|
||||
} from '@/modules/iam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const loading = ref(false)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const reviews = ref<EnterpriseReview[]>([])
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
type ReviewFilters = QueryModel & { keyword: string }
|
||||
const filters = ref<ReviewFilters>({ keyword: '' })
|
||||
const appliedFilters = ref<ReviewFilters>({ keyword: '' })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '企业名称、企业编号、信用代码或审核单号' },
|
||||
]
|
||||
const detailOpen = ref(false)
|
||||
const selectedReview = ref<EnterpriseReview | null>(null)
|
||||
const qualifications = ref<PlatformTenantQualification[]>([])
|
||||
const qualificationsLoading = ref(false)
|
||||
const qualificationsError = ref<ApiErrorDetails | null>(null)
|
||||
const previewOpen = ref(false)
|
||||
const previewUrl = ref('')
|
||||
const previewName = ref('')
|
||||
const previewKind = ref<'image' | 'pdf' | ''>('')
|
||||
type QualificationAsset = { url: string; name: string; kind: 'image' | 'pdf' }
|
||||
const qualificationAssets = ref<Record<string, QualificationAsset>>({})
|
||||
const qualificationAssetLoadingIds = ref<string[]>([])
|
||||
const qualificationAssetErrorIds = ref<string[]>([])
|
||||
const qualificationAssetRequests = new Map<string, Promise<QualificationAsset | undefined>>()
|
||||
const decisionOpen = ref(false)
|
||||
const submitting = ref(false)
|
||||
const decision = reactive({ type: 'approve' as 'approve' | 'reject', comment: '' })
|
||||
const decisionFormRef = ref<FormInstance>()
|
||||
const decisionRules: FormRules = {
|
||||
comment: [{
|
||||
validator: (_rule, value, callback) => {
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
callback()
|
||||
return
|
||||
}
|
||||
callback(new Error('请填写审核说明或驳回原因'))
|
||||
},
|
||||
trigger: ['blur', 'change'],
|
||||
}],
|
||||
}
|
||||
|
||||
const filteredReviews = computed(() => {
|
||||
const query = appliedFilters.value.keyword.trim().toLowerCase()
|
||||
if (!query) return reviews.value
|
||||
return reviews.value.filter((review) => [
|
||||
review.tenantName,
|
||||
review.tenantCode,
|
||||
review.certificateNo,
|
||||
String(review.tenantId),
|
||||
String(review.id),
|
||||
].some((value) => value?.toLowerCase().includes(query)))
|
||||
})
|
||||
|
||||
const pagedReviews = computed(() => {
|
||||
const start = (page.value - 1) * pageSize.value
|
||||
return filteredReviews.value.slice(start, start + pageSize.value)
|
||||
})
|
||||
|
||||
const reviewColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 250, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'company', label: '企业', minWidth: 230, slotName: 'company' },
|
||||
{ key: 'qualification', label: '资质', minWidth: 210, slotName: 'qualification' },
|
||||
{ key: 'contact', label: '联系人', minWidth: 180, slotName: 'contact' },
|
||||
{ key: 'submittedAt', label: '提交时间', minWidth: 175, slotName: 'submittedAt' },
|
||||
{ key: 'status', label: '状态', width: 110, slotName: 'status' },
|
||||
]
|
||||
|
||||
function displayText(value: unknown) {
|
||||
return typeof value === 'string' && value.trim() ? value : '—'
|
||||
}
|
||||
|
||||
function formatDate(value?: string | null) {
|
||||
if (!value) return '—'
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function qualificationName(value?: string | null) {
|
||||
const names: Record<string, string> = {
|
||||
BUSINESS_LICENSE: '营业执照',
|
||||
LEGAL_PERSON_ID: '法人身份证',
|
||||
FREIGHT_FORWARDER_CERTIFICATE: '货代资质证书',
|
||||
BANK_ACCOUNT_LICENSE: '银行开户许可证',
|
||||
}
|
||||
return value ? (names[value] || value) : '—'
|
||||
}
|
||||
|
||||
function qualificationStatus(status: PlatformTenantQualification['status']) {
|
||||
if (status === 'APPROVED') return { label: '已通过', tone: 'is-success' }
|
||||
if (status === 'REJECTED') return { label: '已驳回', tone: 'is-danger' }
|
||||
return { label: '待审核', tone: 'is-warning' }
|
||||
}
|
||||
|
||||
async function loadReviews() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
reviews.value = await listEnterpriseReviews()
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '审核列表加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function searchReviews() {
|
||||
appliedFilters.value = { ...filters.value }
|
||||
page.value = 1
|
||||
void loadReviews()
|
||||
}
|
||||
|
||||
async function loadSelectedQualifications() {
|
||||
const tenantId = selectedReview.value?.tenantId
|
||||
if (!tenantId) return
|
||||
previewOpen.value = false
|
||||
clearQualificationAssets()
|
||||
qualificationsLoading.value = true
|
||||
qualificationsError.value = null
|
||||
qualifications.value = []
|
||||
try {
|
||||
const result = await listTenantQualifications(tenantId)
|
||||
if (selectedReview.value?.tenantId === tenantId) {
|
||||
qualifications.value = result
|
||||
preloadQualificationAssets(result, tenantId)
|
||||
}
|
||||
} catch (error) {
|
||||
if (selectedReview.value?.tenantId === tenantId) {
|
||||
qualificationsError.value = getApiErrorDetails(error, '资质列表加载失败,请稍后重试')
|
||||
}
|
||||
} finally {
|
||||
if (selectedReview.value?.tenantId === tenantId) qualificationsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openDetail(review: EnterpriseReview) {
|
||||
selectedReview.value = review
|
||||
detailOpen.value = true
|
||||
void loadSelectedQualifications()
|
||||
}
|
||||
|
||||
function clearPreview() {
|
||||
previewUrl.value = ''
|
||||
previewName.value = ''
|
||||
previewKind.value = ''
|
||||
}
|
||||
|
||||
function qualificationKey(qualification: PlatformTenantQualification) {
|
||||
return String(qualification.id)
|
||||
}
|
||||
|
||||
function clearQualificationAssets() {
|
||||
Object.values(qualificationAssets.value).forEach((asset) => URL.revokeObjectURL(asset.url))
|
||||
qualificationAssets.value = {}
|
||||
qualificationAssetLoadingIds.value = []
|
||||
qualificationAssetErrorIds.value = []
|
||||
qualificationAssetRequests.clear()
|
||||
clearPreview()
|
||||
}
|
||||
|
||||
async function loadQualificationAsset(
|
||||
qualification: PlatformTenantQualification,
|
||||
tenantId: number | string,
|
||||
) {
|
||||
const key = qualificationKey(qualification)
|
||||
const cached = qualificationAssets.value[key]
|
||||
if (cached) return cached
|
||||
|
||||
const pending = qualificationAssetRequests.get(key)
|
||||
if (pending) return pending
|
||||
|
||||
qualificationAssetLoadingIds.value = [...qualificationAssetLoadingIds.value, key]
|
||||
qualificationAssetErrorIds.value = qualificationAssetErrorIds.value.filter((id) => id !== key)
|
||||
|
||||
const request = (async () => {
|
||||
const blob = await downloadTenantQualification(tenantId, qualification.documentUrl)
|
||||
if (!blob.size) throw new Error('资质文件内容为空')
|
||||
const name = qualificationFileName(qualification.documentUrl)
|
||||
const asset: QualificationAsset = {
|
||||
url: URL.createObjectURL(blob),
|
||||
name,
|
||||
kind: blob.type === 'application/pdf' || name.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image',
|
||||
}
|
||||
const isCurrent = detailOpen.value
|
||||
&& selectedReview.value?.tenantId === tenantId
|
||||
&& qualifications.value.some((item) => qualificationKey(item) === key && item.documentUrl === qualification.documentUrl)
|
||||
if (!isCurrent) {
|
||||
URL.revokeObjectURL(asset.url)
|
||||
return undefined
|
||||
}
|
||||
qualificationAssets.value = { ...qualificationAssets.value, [key]: asset }
|
||||
return asset
|
||||
})()
|
||||
|
||||
qualificationAssetRequests.set(key, request)
|
||||
try {
|
||||
return await request
|
||||
} catch (error) {
|
||||
if (detailOpen.value && selectedReview.value?.tenantId === tenantId) {
|
||||
qualificationAssetErrorIds.value = [...new Set([...qualificationAssetErrorIds.value, key])]
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
qualificationAssetLoadingIds.value = qualificationAssetLoadingIds.value.filter((id) => id !== key)
|
||||
if (qualificationAssetRequests.get(key) === request) qualificationAssetRequests.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
function preloadQualificationAssets(items: PlatformTenantQualification[], tenantId: number | string) {
|
||||
items.forEach((qualification) => {
|
||||
if (qualification.documentUrl) {
|
||||
void loadQualificationAsset(qualification, tenantId).catch(() => undefined)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function previewQualification(qualification: PlatformTenantQualification) {
|
||||
const tenantId = selectedReview.value?.tenantId
|
||||
if (!tenantId || !qualification.documentUrl) return
|
||||
try {
|
||||
const asset = await loadQualificationAsset(qualification, tenantId)
|
||||
if (!asset) return
|
||||
previewUrl.value = asset.url
|
||||
previewName.value = asset.name
|
||||
previewKind.value = asset.kind
|
||||
previewOpen.value = true
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '资质文件加载失败,请稍后重试'))
|
||||
}
|
||||
}
|
||||
|
||||
function openDecision(review: EnterpriseReview, type: 'approve' | 'reject') {
|
||||
selectedReview.value = review
|
||||
decision.type = type
|
||||
decision.comment = type === 'approve' ? '企业资料与必填资质完整、清晰,审核通过' : ''
|
||||
decisionOpen.value = true
|
||||
void nextTick(() => decisionFormRef.value?.clearValidate('comment'))
|
||||
}
|
||||
|
||||
async function submitDecision() {
|
||||
const review = selectedReview.value
|
||||
const form = decisionFormRef.value
|
||||
if (!review || !form || submitting.value) return
|
||||
const valid = await form.validate().then(() => true).catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
if (decision.type === 'approve') {
|
||||
await approveEnterpriseReview(review.id, decision.comment.trim())
|
||||
} else {
|
||||
await rejectEnterpriseReview(review.id, decision.comment.trim())
|
||||
}
|
||||
reviews.value = reviews.value.filter((item) => item.id !== review.id)
|
||||
decisionOpen.value = false
|
||||
detailOpen.value = false
|
||||
ElMessage.success(decision.type === 'approve' ? '企业资料已审核通过' : '企业资料已驳回')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '审核提交失败,请稍后重试'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [access.can('platform:customer:approve'), access.can('platform:customer:reject')],
|
||||
([canApprove, canReject]) => {
|
||||
if ((decision.type === 'approve' && !canApprove) || (decision.type === 'reject' && !canReject)) {
|
||||
decisionOpen.value = false
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
watch(previewOpen, (open) => {
|
||||
if (!open) clearPreview()
|
||||
})
|
||||
|
||||
watch(detailOpen, (open) => {
|
||||
if (!open) {
|
||||
previewOpen.value = false
|
||||
clearQualificationAssets()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(loadReviews)
|
||||
onBeforeUnmount(clearQualificationAssets)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page enterprise-review-page">
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="企业审核筛选" :fields="queryFields" @search="searchReviews" />
|
||||
|
||||
<section v-if="loadError" class="surface-panel review-error" role="alert">
|
||||
<ShieldX :size="22" />
|
||||
<div><strong>审核列表暂时无法加载</strong><p>{{ loadError.message }}</p><ApiErrorMeta :details="loadError" /></div>
|
||||
<el-button type="primary" @click="loadReviews">重新加载</el-button>
|
||||
</section>
|
||||
|
||||
<section v-else class="surface-panel table-panel" :aria-busy="loading">
|
||||
<DataTable
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:data="pagedReviews"
|
||||
:columns="reviewColumns"
|
||||
:loading="loading"
|
||||
:total="filteredReviews.length"
|
||||
aria-label="企业审核列表"
|
||||
row-key="id"
|
||||
empty-text="暂无待审核企业"
|
||||
>
|
||||
<template #actions="{ row }">
|
||||
<div class="table-actions">
|
||||
<el-button link type="primary" @click="openDetail(row as EnterpriseReview)"><Eye :size="15" />详情</el-button>
|
||||
<el-button v-if="access.can('platform:customer:approve')" link type="success" @click="openDecision(row as EnterpriseReview, 'approve')"><ShieldCheck :size="15" />通过</el-button>
|
||||
<el-button v-if="access.can('platform:customer:reject')" link type="danger" @click="openDecision(row as EnterpriseReview, 'reject')"><ShieldX :size="15" />驳回</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<template #company="{ row }"><div class="primary-cell"><strong>{{ displayText((row as EnterpriseReview).tenantName) }}</strong><span>{{ displayText((row as EnterpriseReview).tenantCode) }} · 租户 {{ (row as EnterpriseReview).tenantId }}</span></div></template>
|
||||
<template #qualification="{ row }"><div class="primary-cell"><strong>{{ qualificationName((row as EnterpriseReview).qualificationType) }}</strong><span>{{ displayText((row as EnterpriseReview).certificateNo) }}</span></div></template>
|
||||
<template #contact="{ row }"><div class="primary-cell"><strong>{{ displayText((row as EnterpriseReview).contactName) }}</strong><span>{{ displayText((row as EnterpriseReview).contactPhone) }}</span></div></template>
|
||||
<template #submittedAt="{ row }">{{ formatDate((row as EnterpriseReview).submittedAt ?? (row as EnterpriseReview).createdAt) }}</template>
|
||||
<template #status><span class="status-badge is-warning"><i />待审核</span></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="detailOpen" title="企业审核详情" size="620px" class="business-drawer">
|
||||
<template v-if="selectedReview">
|
||||
<div class="detail-identity">
|
||||
<span><FileCheck2 :size="20" /></span>
|
||||
<div><h2>{{ displayText(selectedReview.tenantName) }}</h2><p>审核单 {{ selectedReview.id }} · 租户 {{ selectedReview.tenantId }}</p></div>
|
||||
<span class="status-badge is-warning"><i />待审核</span>
|
||||
</div>
|
||||
<section class="detail-section">
|
||||
<h3>企业与联系人</h3>
|
||||
<el-descriptions :column="1" border>
|
||||
<el-descriptions-item label="企业编号">{{ displayText(selectedReview.tenantCode) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="联系人">{{ displayText(selectedReview.contactName) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="联系电话">{{ displayText(selectedReview.contactPhone) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="联系邮箱">{{ displayText(selectedReview.contactEmail) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</section>
|
||||
<section class="detail-section">
|
||||
<h3>资质文件</h3>
|
||||
<div class="qualification-state" :aria-busy="qualificationsLoading">
|
||||
<div v-if="qualificationsLoading" v-loading="true" class="qualification-loading">正在读取该企业资质…</div>
|
||||
<div v-else-if="qualificationsError" class="qualification-error" role="alert">
|
||||
<div><strong>资质暂时无法加载</strong><p>{{ qualificationsError.message }}</p><ApiErrorMeta :details="qualificationsError" /></div>
|
||||
<el-button type="primary" plain @click="loadSelectedQualifications">重新加载</el-button>
|
||||
</div>
|
||||
<el-empty v-else-if="qualifications.length === 0" :image-size="64" description="该企业暂未提交资质" />
|
||||
<div v-else class="qualification-list">
|
||||
<article v-for="qualification in qualifications" :key="qualification.id" class="qualification-item">
|
||||
<button
|
||||
type="button"
|
||||
class="qualification-thumbnail"
|
||||
:disabled="!qualification.documentUrl"
|
||||
:aria-label="qualification.documentUrl ? `查看${qualificationName(qualification.qualificationType)}大图` : `${qualificationName(qualification.qualificationType)}未上传文件`"
|
||||
@click="previewQualification(qualification)"
|
||||
>
|
||||
<img
|
||||
v-if="qualificationAssets[qualificationKey(qualification)]?.kind === 'image'"
|
||||
:src="qualificationAssets[qualificationKey(qualification)]?.url"
|
||||
:alt="`${qualificationName(qualification.qualificationType)}缩略图`"
|
||||
/>
|
||||
<span v-else-if="qualificationAssets[qualificationKey(qualification)]?.kind === 'pdf'" class="thumbnail-placeholder">
|
||||
<FileText :size="24" />
|
||||
<small>PDF</small>
|
||||
</span>
|
||||
<span v-else-if="qualificationAssetLoadingIds.includes(qualificationKey(qualification))" class="thumbnail-placeholder" role="status">
|
||||
<LoaderCircle :size="22" class="is-spinning" />
|
||||
<small>加载中</small>
|
||||
</span>
|
||||
<span v-else-if="qualificationAssetErrorIds.includes(qualificationKey(qualification))" class="thumbnail-placeholder is-error">
|
||||
<ImageOff :size="22" />
|
||||
<small>重新加载</small>
|
||||
</span>
|
||||
<span v-else class="thumbnail-placeholder">
|
||||
<FileText :size="22" />
|
||||
<small>未上传</small>
|
||||
</span>
|
||||
<span v-if="qualificationAssets[qualificationKey(qualification)]" class="thumbnail-action" aria-hidden="true"><Eye :size="15" /></span>
|
||||
</button>
|
||||
<div class="qualification-copy">
|
||||
<div><strong>{{ qualificationName(qualification.qualificationType) }}</strong><span class="status-badge" :class="qualificationStatus(qualification.status).tone"><i />{{ qualificationStatus(qualification.status).label }}</span></div>
|
||||
<p>信用代码:{{ displayText(qualification.certificateNo) }}</p>
|
||||
<p v-if="qualification.reviewComment">审核意见:{{ qualification.reviewComment }}</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
<p class="detail-note">请核对企业名称、统一社会信用代码和营业执照内容。通过后企业获得下单资格;驳回时必须说明原因。</p>
|
||||
</section>
|
||||
</template>
|
||||
<template #footer>
|
||||
<div class="drawer-footer">
|
||||
<el-button @click="detailOpen = false">关闭</el-button>
|
||||
<el-button v-if="selectedReview && access.can('platform:customer:reject')" type="danger" plain @click="openDecision(selectedReview, 'reject')">驳回</el-button>
|
||||
<el-button v-if="selectedReview && access.can('platform:customer:approve')" type="success" @click="openDecision(selectedReview, 'approve')">审核通过</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog v-model="previewOpen" :title="previewName || '查看资质文件'" width="min(860px, calc(100vw - 28px))" class="qualification-preview-dialog" destroy-on-close>
|
||||
<div class="qualification-preview">
|
||||
<img v-if="previewUrl && previewKind === 'image'" :src="previewUrl" :alt="`${previewName}预览`" />
|
||||
<iframe v-else-if="previewUrl && previewKind === 'pdf'" :src="previewUrl" :title="`${previewName} PDF 预览`" />
|
||||
</div>
|
||||
<template #footer><el-button @click="previewOpen = false">关闭预览</el-button></template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="decisionOpen" :title="decision.type === 'approve' ? '确认审核通过' : '确认驳回企业资料'" width="min(520px, calc(100vw - 28px))" class="review-decision-dialog" :close-on-click-modal="false">
|
||||
<div v-if="selectedReview" class="decision-summary">
|
||||
<strong>{{ displayText(selectedReview.tenantName) }}</strong>
|
||||
<span>审核单 {{ selectedReview.id }}</span>
|
||||
</div>
|
||||
<el-form ref="decisionFormRef" :model="decision" :rules="decisionRules" label-position="top">
|
||||
<el-form-item prop="comment" :label="decision.type === 'approve' ? '审核说明' : '驳回原因'" required>
|
||||
<el-input v-model="decision.comment" type="textarea" :rows="4" maxlength="300" show-word-limit :placeholder="decision.type === 'approve' ? '请填写审核通过说明' : '请明确说明需要企业修改的内容'" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="drawer-footer">
|
||||
<el-button :disabled="submitting" @click="decisionOpen = false">取消</el-button>
|
||||
<el-button :type="decision.type === 'approve' ? 'success' : 'danger'" :loading="submitting" @click="submitDecision">{{ decision.type === 'approve' ? '确认通过' : '确认驳回' }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.review-error { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 14px; padding: 18px 20px; border-color: #fecdca; background: #fffafa; color: #b42318; }
|
||||
.review-error strong { color: #7a271a; font-size: 13px; }
|
||||
.review-error p { margin: 4px 0 0; color: #b54708; font-size: 12px; }
|
||||
.qualification-state { min-height: 112px; }
|
||||
.qualification-loading { display: grid; min-height: 112px; place-items: center; color: var(--cc-muted); font-size: 12px; }
|
||||
.qualification-error { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 16px; padding: 14px; border: 1px solid #fecdca; border-radius: 6px; background: #fffafa; }
|
||||
.qualification-error strong { color: #7a271a; font-size: 13px; }
|
||||
.qualification-error p { margin: 4px 0 0; color: #b54708; font-size: 12px; overflow-wrap: anywhere; }
|
||||
.qualification-list { display: flex; flex-direction: column; gap: 10px; }
|
||||
.qualification-item { display: grid; min-width: 0; grid-template-columns: 112px minmax(0, 1fr); align-items: center; gap: 14px; padding: 12px; border: 1px solid var(--cc-border); border-radius: 6px; background: #fff; }
|
||||
.qualification-thumbnail { position: relative; display: grid; width: 112px; height: 84px; place-items: center; overflow: hidden; padding: 0; border: 1px solid #d5dce7; border-radius: 6px; background: #f8fafc; color: #475467; cursor: zoom-in; }
|
||||
.qualification-thumbnail:not(:disabled):hover { border-color: var(--cc-primary); }
|
||||
.qualification-thumbnail:focus-visible { outline: 2px solid var(--cc-primary); outline-offset: 2px; }
|
||||
.qualification-thumbnail:disabled { cursor: not-allowed; opacity: .72; }
|
||||
.qualification-thumbnail > img { display: block; width: 100%; height: 100%; object-fit: contain; background: #fff; }
|
||||
.thumbnail-placeholder { display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 5px; color: #667085; }
|
||||
.thumbnail-placeholder small { font-size: 10px; line-height: 1; }
|
||||
.thumbnail-placeholder.is-error { color: #b42318; }
|
||||
.thumbnail-action { position: absolute; top: 6px; right: 6px; display: grid; width: 28px; height: 28px; place-items: center; border-radius: 50%; background: rgba(23, 32, 51, .78); color: #fff; }
|
||||
.is-spinning { animation: thumbnail-spin 1s linear infinite; }
|
||||
.qualification-copy { min-width: 0; }
|
||||
.qualification-copy > div { display: flex; min-width: 0; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.qualification-copy strong { overflow-wrap: anywhere; font-size: 13px; }
|
||||
.qualification-copy p { margin: 5px 0 0; color: var(--cc-muted); font-size: 11px; line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.qualification-preview { display: grid; max-height: min(70vh, 760px); min-height: 240px; place-items: center; overflow: auto; border: 1px solid var(--cc-border); border-radius: 6px; background: #f8fafc; }
|
||||
.qualification-preview img { display: block; max-width: 100%; height: auto; }
|
||||
.qualification-preview iframe { width: 100%; min-height: min(68vh, 720px); border: 0; background: #fff; }
|
||||
.decision-summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 18px; padding: 12px 14px; border-radius: 8px; background: #f8fafc; }
|
||||
.decision-summary > * { min-width: 0; overflow-wrap: anywhere; }
|
||||
.decision-summary strong { color: #172033; font-size: 13px; }
|
||||
.decision-summary span { color: var(--cc-muted); font-size: 11px; }
|
||||
:deep(.review-decision-dialog .el-form-item__error) { line-height: 1.45; overflow-wrap: anywhere; }
|
||||
@media (max-width: 720px) {
|
||||
.review-error { grid-template-columns: auto minmax(0, 1fr); }
|
||||
.review-error .el-button { grid-column: 1 / -1; min-height: 44px; }
|
||||
.qualification-error { align-items: stretch; flex-direction: column; }
|
||||
.qualification-error .el-button { min-height: 44px; }
|
||||
.decision-summary { align-items: flex-start; flex-direction: column; }
|
||||
}
|
||||
@media (max-width: 420px) {
|
||||
.qualification-item { grid-template-columns: 96px minmax(0, 1fr); gap: 12px; padding: 10px; }
|
||||
.qualification-thumbnail { width: 96px; height: 76px; }
|
||||
}
|
||||
@keyframes thumbnail-spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.is-spinning { animation: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const customerRoutes = [
|
||||
{
|
||||
path: 'customers',
|
||||
name: 'customers',
|
||||
component: () => import('@/modules/customers/pages/CustomersView.vue'),
|
||||
meta: { title: '客户管理', description: '维护客户企业资料、合作状态和注册审核', permission: 'platform:customer:list' },
|
||||
},
|
||||
{
|
||||
path: 'customers/reviews',
|
||||
name: 'enterprise-reviews',
|
||||
component: () => import('@/modules/customers/pages/EnterpriseReviewsView.vue'),
|
||||
meta: { title: '企业审核', description: '核验企业资质并维护客户下单资格', permission: 'platform:customer:review' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,41 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
createPlatformExportTask,
|
||||
downloadPlatformExportTask,
|
||||
listPlatformExportTasks,
|
||||
retryPlatformExportTask,
|
||||
} from './platformExportTasks'
|
||||
|
||||
vi.mock('@/shared/api/http', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/shared/api/http')>('@/shared/api/http')
|
||||
return { ...actual, http: { get: vi.fn(), post: vi.fn() } }
|
||||
})
|
||||
|
||||
describe('platformExportTasks', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('creates a backend export task with the filter snapshot', async () => {
|
||||
const task = { id: '9', status: 'PENDING', exportType: 'CUSTOMER_LIST' }
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: task })
|
||||
const payload = { exportType: 'CUSTOMER_LIST', format: 'XLSX' as const, taskName: '客户列表', parameters: { status: 'ACTIVE' } }
|
||||
|
||||
await expect(createPlatformExportTask(payload)).resolves.toEqual(task)
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks', payload)
|
||||
})
|
||||
|
||||
it('lists, downloads, and retries export tasks through File service', async () => {
|
||||
const page = { records: [], page: '1', size: '20', total: '0', pages: '0' }
|
||||
const blob = new Blob(['xlsx'])
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', message: 'success', data: page }).mockResolvedValueOnce(blob)
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '9', status: 'PENDING' } })
|
||||
|
||||
await expect(listPlatformExportTasks({ page: 1, size: 20, status: 'FAILED' })).resolves.toEqual({ records: [], page: 1, size: 20, total: 0, pages: 0 })
|
||||
await expect(downloadPlatformExportTask('9')).resolves.toBe(blob)
|
||||
await expect(retryPlatformExportTask('9')).resolves.toMatchObject({ id: '9', status: 'PENDING' })
|
||||
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/files/export-tasks', { params: { page: 1, size: 20, status: 'FAILED' } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/files/export-tasks/9/download', { responseType: 'blob' })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks/9/retry', {})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
export type ExportTaskStatus = 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'EXPIRED'
|
||||
export type ExportTaskType = 'CUSTOMER_LIST' | string
|
||||
|
||||
export interface PlatformExportTask {
|
||||
id: string
|
||||
taskNo: string
|
||||
exportType: ExportTaskType
|
||||
format: 'XLSX' | string
|
||||
taskName: string
|
||||
status: ExportTaskStatus
|
||||
totalRows: number | null
|
||||
processedRows: number
|
||||
fileName: string | null
|
||||
contentType: string | null
|
||||
sizeBytes: number | null
|
||||
failureMessage: string | null
|
||||
requestedBy: string
|
||||
requestedUsername: string | null
|
||||
requestedAt: string
|
||||
startedAt: string | null
|
||||
completedAt: string | null
|
||||
expiresAt: string | null
|
||||
}
|
||||
|
||||
export interface PlatformExportTaskPage {
|
||||
records: PlatformExportTask[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
export interface PlatformExportTaskQuery {
|
||||
page: number
|
||||
size: number
|
||||
exportType?: string
|
||||
status?: ExportTaskStatus
|
||||
requestedFrom?: string
|
||||
requestedTo?: string
|
||||
}
|
||||
|
||||
export interface CreatePlatformExportTaskRequest {
|
||||
exportType: ExportTaskType
|
||||
format: 'XLSX'
|
||||
taskName: string
|
||||
parameters: Record<string, string | number | boolean | null | undefined>
|
||||
}
|
||||
|
||||
const basePath = '/platform/v1/files/export-tasks'
|
||||
|
||||
export async function createPlatformExportTask(payload: CreatePlatformExportTaskRequest) {
|
||||
const response = await http.post<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(basePath, payload)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function listPlatformExportTasks(query: PlatformExportTaskQuery) {
|
||||
const response = await http.get<ApiEnvelope<PlatformExportTaskPage>, ApiEnvelope<PlatformExportTaskPage>>(basePath, {
|
||||
params: query,
|
||||
})
|
||||
const page = unwrapApiResponse(response)
|
||||
return {
|
||||
...page,
|
||||
page: Number(page.page),
|
||||
size: Number(page.size),
|
||||
total: Number(page.total),
|
||||
pages: Number(page.pages),
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadPlatformExportTask(taskId: string) {
|
||||
return http.get<Blob, Blob>(`${basePath}/${encodeURIComponent(taskId)}/download`, { responseType: 'blob' })
|
||||
}
|
||||
|
||||
export async function retryPlatformExportTask(taskId: string) {
|
||||
const response = await http.post<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(
|
||||
`${basePath}/${encodeURIComponent(taskId)}/retry`,
|
||||
{},
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './api/platformExportTasks'
|
||||
@@ -0,0 +1,105 @@
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
downloadPlatformExportTask,
|
||||
listPlatformExportTasks,
|
||||
retryPlatformExportTask,
|
||||
type PlatformExportTask,
|
||||
} from '@/modules/downloads/api/platformExportTasks'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import DownloadCenterView from './DownloadCenterView.vue'
|
||||
|
||||
vi.mock('@/modules/downloads/api/platformExportTasks', () => ({
|
||||
downloadPlatformExportTask: vi.fn(),
|
||||
listPlatformExportTasks: vi.fn(),
|
||||
retryPlatformExportTask: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
const task: PlatformExportTask = {
|
||||
id: '9', taskNo: 'EXP9', exportType: 'CUSTOMER_LIST', format: 'XLSX', taskName: '客户列表',
|
||||
status: 'SUCCEEDED', totalRows: 12, processedRows: 12, fileName: '客户列表.xlsx',
|
||||
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', sizeBytes: 2048,
|
||||
failureMessage: null, requestedBy: '1', requestedUsername: 'admin', requestedAt: '2026-08-03T10:00:00',
|
||||
startedAt: '2026-08-03T10:00:01', completedAt: '2026-08-03T10:00:02', expiresAt: '2026-08-10T10:00:02',
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
describe('DownloadCenterView', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:export') })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:download:list', 'platform:customer:export']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [task], page: 1, size: 20, total: 1, pages: 1 })
|
||||
vi.mocked(downloadPlatformExportTask).mockResolvedValue(new Blob(['xlsx']))
|
||||
vi.mocked(retryPlatformExportTask).mockResolvedValue({ ...task, status: 'PENDING' })
|
||||
})
|
||||
|
||||
it('lists completed tasks and downloads the backend-generated artifact', async () => {
|
||||
const pinia = setActivePinia(createPinia())
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:download:list', 'platform:customer:export']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
|
||||
expect(document.body.textContent).toContain('客户列表')
|
||||
expect(document.querySelector('.failure-cell')?.classList.contains('failure-message')).toBe(false)
|
||||
const button = [...document.querySelectorAll<HTMLButtonElement>('button')].find((item) => item.textContent?.trim() === '下载')
|
||||
button?.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(downloadPlatformExportTask).toHaveBeenCalledWith('9')
|
||||
expect(URL.createObjectURL).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows retry only for failed tasks with the source export permission', async () => {
|
||||
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [{ ...task, status: 'FAILED', failureMessage: 'IAM timeout' }], page: 1, size: 20, total: 1, pages: 1 })
|
||||
const pinia = setActivePinia(createPinia())
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:download:list', 'platform:customer:export']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||
await flushPromises()
|
||||
|
||||
expect(document.querySelector('.failure-cell')?.classList.contains('failure-message')).toBe(true)
|
||||
const button = [...document.querySelectorAll<HTMLButtonElement>('button')].find((item) => item.textContent?.trim() === '重试')
|
||||
button?.click()
|
||||
await flushPromises()
|
||||
expect(retryPlatformExportTask).toHaveBeenCalledWith('9')
|
||||
})
|
||||
|
||||
it('does not schedule another refresh after an in-flight load finishes on an unmounted page', async () => {
|
||||
vi.useFakeTimers()
|
||||
let resolveRequest!: (value: { records: PlatformExportTask[]; page: number; size: number; total: number; pages: number }) => void
|
||||
vi.mocked(listPlatformExportTasks).mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
|
||||
const wrapper = mount(DownloadCenterView, { global: { plugins: [createPinia(), ElementPlus] } })
|
||||
|
||||
wrapper.unmount()
|
||||
resolveRequest({ records: [{ ...task, status: 'RUNNING' }], page: 1, size: 20, total: 1, pages: 1 })
|
||||
await flushPromises()
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
|
||||
expect(listPlatformExportTasks).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,229 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Download, RefreshCw, RotateCcw } from '@lucide/vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import {
|
||||
downloadPlatformExportTask,
|
||||
listPlatformExportTasks,
|
||||
retryPlatformExportTask,
|
||||
type ExportTaskStatus,
|
||||
type PlatformExportTask,
|
||||
} from '@/modules/downloads/api/platformExportTasks'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
|
||||
type DownloadFilters = QueryModel & {
|
||||
exportType: string
|
||||
status: ExportTaskStatus | ''
|
||||
requestedRange: string[]
|
||||
}
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const loading = ref(false)
|
||||
const downloadingId = ref('')
|
||||
const retryingId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const result = ref({ records: [] as PlatformExportTask[], total: 0, pages: 0 })
|
||||
const filters = ref<DownloadFilters>({ exportType: '', status: '', requestedRange: [] })
|
||||
let refreshTimer: number | undefined
|
||||
let disposed = false
|
||||
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'exportType', type: 'select', placeholder: '全部任务类型', options: [
|
||||
{ label: '客户列表', value: 'CUSTOMER_LIST' },
|
||||
] },
|
||||
{ key: 'status', type: 'select', placeholder: '全部任务状态', options: [
|
||||
{ label: '等待处理', value: 'PENDING' }, { label: '处理中', value: 'RUNNING' },
|
||||
{ label: '已完成', value: 'SUCCEEDED' }, { label: '失败', value: 'FAILED' },
|
||||
{ label: '已过期', value: 'EXPIRED' },
|
||||
] },
|
||||
{ key: 'requestedRange', type: 'daterange', placeholder: '请选择申请日期' },
|
||||
]
|
||||
|
||||
const columns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 150, fixed: 'left', slotName: 'actions' },
|
||||
{ prop: 'taskName', label: '任务名称', minWidth: 180, showOverflowTooltip: true },
|
||||
{ key: 'type', label: '任务类型', width: 120, slotName: 'type' },
|
||||
{ key: 'status', label: '状态', width: 110, slotName: 'status' },
|
||||
{ key: 'progress', label: '数据量', width: 120, slotName: 'progress' },
|
||||
{ prop: 'format', label: '格式', width: 80 },
|
||||
{ key: 'requester', label: '申请人', minWidth: 130, slotName: 'requester' },
|
||||
{ key: 'requestedAt', label: '申请时间', width: 170, slotName: 'requestedAt' },
|
||||
{ key: 'completedAt', label: '完成时间', width: 170, slotName: 'completedAt' },
|
||||
{ key: 'expiresAt', label: '过期时间', width: 170, slotName: 'expiresAt' },
|
||||
{ key: 'failure', label: '失败原因', minWidth: 240, slotName: 'failure' },
|
||||
]
|
||||
|
||||
const hasActiveTasks = computed(() => result.value.records.some((task) => ['PENDING', 'RUNNING'].includes(task.status)))
|
||||
|
||||
function clearRefreshTimer() {
|
||||
if (refreshTimer !== undefined) window.clearTimeout(refreshTimer)
|
||||
refreshTimer = undefined
|
||||
}
|
||||
|
||||
function scheduleRefresh() {
|
||||
clearRefreshTimer()
|
||||
if (!disposed && hasActiveTasks.value && !loadError.value) refreshTimer = window.setTimeout(() => { void loadTasks(true) }, 5000)
|
||||
}
|
||||
|
||||
async function loadTasks(background = false) {
|
||||
clearRefreshTimer()
|
||||
if (!background) loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const range = filters.value.requestedRange
|
||||
const response = await listPlatformExportTasks({
|
||||
page: page.value,
|
||||
size: pageSize.value,
|
||||
exportType: filters.value.exportType || undefined,
|
||||
status: filters.value.status || undefined,
|
||||
requestedFrom: range?.[0] || undefined,
|
||||
requestedTo: range?.[1] || undefined,
|
||||
})
|
||||
result.value = { records: response.records, total: response.total, pages: response.pages }
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '下载任务加载失败')
|
||||
} finally {
|
||||
if (!background) loading.value = false
|
||||
scheduleRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
function applyFilters() {
|
||||
if (page.value === 1) void loadTasks()
|
||||
else page.value = 1
|
||||
}
|
||||
|
||||
async function downloadTask(task: PlatformExportTask) {
|
||||
downloadingId.value = task.id
|
||||
try {
|
||||
const blob = await downloadPlatformExportTask(task.id)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = safeFileName(task.fileName || `${task.taskName}.xlsx`)
|
||||
document.body.append(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '文件下载失败,请刷新任务状态后重试'))
|
||||
} finally {
|
||||
downloadingId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function retryTask(task: PlatformExportTask) {
|
||||
retryingId.value = task.id
|
||||
try {
|
||||
await retryPlatformExportTask(task.id)
|
||||
ElMessage.success('导出任务已重新提交')
|
||||
await loadTasks()
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '任务重试失败'))
|
||||
} finally {
|
||||
retryingId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function safeFileName(value: string) {
|
||||
const safe = value.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim()
|
||||
return safe || '导出文件.xlsx'
|
||||
}
|
||||
|
||||
function typeLabel(type: string) { return type === 'CUSTOMER_LIST' ? '客户列表' : type }
|
||||
|
||||
function statusMeta(status: ExportTaskStatus) {
|
||||
const values = {
|
||||
PENDING: { label: '等待处理', type: 'info' as const },
|
||||
RUNNING: { label: '处理中', type: 'warning' as const },
|
||||
SUCCEEDED: { label: '已完成', type: 'success' as const },
|
||||
FAILED: { label: '失败', type: 'danger' as const },
|
||||
EXPIRED: { label: '已过期', type: 'info' as const },
|
||||
}
|
||||
return values[status]
|
||||
}
|
||||
|
||||
function formatDate(value: string | null) {
|
||||
if (!value) return '—'
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function formatSize(bytes: number | null) {
|
||||
if (bytes === null) return ''
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function canRetry(task: PlatformExportTask) {
|
||||
return task.status === 'FAILED' && task.exportType === 'CUSTOMER_LIST' && access.can('platform:customer:export')
|
||||
}
|
||||
|
||||
watch([page, pageSize], () => { void loadTasks() })
|
||||
onMounted(loadTasks)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
clearRefreshTimer()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page download-center-page">
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="下载任务筛选" :fields="queryFields" @search="applyFilters" />
|
||||
|
||||
<section v-if="loadError" class="surface-panel download-error" role="alert">
|
||||
<div><strong>下载任务暂时无法加载</strong><p>{{ loadError.message }}</p><ApiErrorMeta :details="loadError" /></div>
|
||||
<el-button type="primary" :loading="loading" @click="loadTasks()">重新加载</el-button>
|
||||
</section>
|
||||
|
||||
<section v-else class="surface-panel table-panel" :aria-busy="loading">
|
||||
<div class="download-table-header">
|
||||
<div><h2>下载任务</h2><span>共 {{ result.total }} 个任务</span></div>
|
||||
<el-button :loading="loading" @click="loadTasks()"><RefreshCw :size="16" />刷新</el-button>
|
||||
</div>
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="result.records" :columns="columns" :loading="loading" :total="result.total" row-key="id" empty-text="暂无符合筛选条件的下载任务" aria-label="下载任务列表">
|
||||
<template #actions="{ row }"><div class="table-actions">
|
||||
<el-button v-if="(row as PlatformExportTask).status === 'SUCCEEDED'" link type="primary" :loading="downloadingId === (row as PlatformExportTask).id" @click="downloadTask(row as PlatformExportTask)"><Download :size="15" />下载</el-button>
|
||||
<el-button v-if="canRetry(row as PlatformExportTask)" link type="primary" :loading="retryingId === (row as PlatformExportTask).id" @click="retryTask(row as PlatformExportTask)"><RotateCcw :size="15" />重试</el-button>
|
||||
<span v-if="(row as PlatformExportTask).status !== 'SUCCEEDED' && !canRetry(row as PlatformExportTask)" class="action-placeholder">—</span>
|
||||
</div></template>
|
||||
<template #type="{ row }">{{ typeLabel((row as PlatformExportTask).exportType) }}</template>
|
||||
<template #status="{ row }"><el-tag :type="statusMeta((row as PlatformExportTask).status).type" effect="light">{{ statusMeta((row as PlatformExportTask).status).label }}</el-tag></template>
|
||||
<template #progress="{ row }"><span>{{ (row as PlatformExportTask).processedRows }}<template v-if="(row as PlatformExportTask).totalRows !== null"> / {{ (row as PlatformExportTask).totalRows }}</template></span><small v-if="(row as PlatformExportTask).sizeBytes !== null">{{ formatSize((row as PlatformExportTask).sizeBytes) }}</small></template>
|
||||
<template #requester="{ row }">{{ (row as PlatformExportTask).requestedUsername || (row as PlatformExportTask).requestedBy }}</template>
|
||||
<template #requestedAt="{ row }">{{ formatDate((row as PlatformExportTask).requestedAt) }}</template>
|
||||
<template #completedAt="{ row }">{{ formatDate((row as PlatformExportTask).completedAt) }}</template>
|
||||
<template #expiresAt="{ row }">{{ formatDate((row as PlatformExportTask).expiresAt) }}</template>
|
||||
<template #failure="{ row }"><span class="failure-cell" :class="{ 'failure-message': Boolean((row as PlatformExportTask).failureMessage) }">{{ (row as PlatformExportTask).failureMessage || '—' }}</span></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.download-center-page { min-width: 0; }
|
||||
.download-error, .download-table-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
|
||||
.download-error { padding: 18px; }
|
||||
.download-error strong { color: var(--cc-danger); font-size: 14px; }
|
||||
.download-error p { margin: 5px 0; color: var(--cc-text); font-size: 13px; }
|
||||
.download-table-header { min-height: 64px; padding: 12px 18px; border-bottom: 1px solid var(--cc-border); }
|
||||
.download-table-header h2 { margin: 0; color: var(--cc-text); font-size: 16px; }
|
||||
.download-table-header span { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 12px; }
|
||||
.table-actions { display: flex; min-height: 32px; align-items: center; gap: 8px; }
|
||||
.table-actions :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
.action-placeholder { color: var(--cc-muted); }
|
||||
.failure-cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.failure-message { color: var(--cc-danger); }
|
||||
small { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 11px; }
|
||||
@media (max-width: 720px) {
|
||||
.download-error, .download-table-header { align-items: stretch; flex-direction: column; }
|
||||
.download-table-header :deep(.el-button) { min-height: 40px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const downloadRoutes = [
|
||||
{
|
||||
path: 'downloads',
|
||||
name: 'download-center',
|
||||
component: () => import('@/modules/downloads/pages/DownloadCenterView.vue'),
|
||||
meta: { title: '下载中心', description: '查看异步导出任务并下载已生成文件', permission: 'platform:download:list' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,72 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
acceptPlatformFirstLegOrder,
|
||||
addPlatformFirstLegOrderNote,
|
||||
approvePlatformFirstLegOrder,
|
||||
cancelPlatformFirstLegOrder,
|
||||
completePlatformFirstLegOrder,
|
||||
getPlatformFirstLegOrder,
|
||||
listPlatformFirstLegOrders,
|
||||
startPlatformFirstLegOrder,
|
||||
updatePlatformFirstLegOrderExpress,
|
||||
} from './platformFirstLegOrders'
|
||||
|
||||
vi.mock('@/shared/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: '200', 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: '200', message: 'success', data: { order: {} } })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', 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: '200', 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 '@/shared/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)
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import { ArrowLeft, Eye, FilePenLine, PackageCheck } from '@lucide/vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
acceptPlatformFirstLegOrder,
|
||||
addPlatformFirstLegOrderNote,
|
||||
approvePlatformFirstLegOrder,
|
||||
cancelPlatformFirstLegOrder,
|
||||
completePlatformFirstLegOrder,
|
||||
getPlatformFirstLegOrder,
|
||||
listPlatformFirstLegOrders,
|
||||
startPlatformFirstLegOrder,
|
||||
updatePlatformFirstLegOrderExpress,
|
||||
type PlatformFirstLegOrderDetailResource,
|
||||
type PlatformFirstLegOrderResource,
|
||||
type PlatformFirstLegOrderStatus,
|
||||
} from '@/modules/first-leg-orders/api/platformFirstLegOrders'
|
||||
import { ApiResponseError, getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
|
||||
const PHASE_ONE_TENANT_ID = '10001'
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const access = useAccessPreviewStore()
|
||||
const loadedTenantId = ref(PHASE_ONE_TENANT_ID)
|
||||
const orders = ref<PlatformFirstLegOrderResource[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const loading = ref(false)
|
||||
const actionLoadingId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
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 noteForm = reactive({ content: '' })
|
||||
const noteSaving = ref(false)
|
||||
const expressSaving = ref(false)
|
||||
const expressFormRef = ref<FormInstance>()
|
||||
const noteFormRef = ref<FormInstance>()
|
||||
const expressForm = reactive({ expressCompany: '', expressTrackingNo: '' })
|
||||
const filters = ref<QueryModel & {
|
||||
keyword: string
|
||||
status: PlatformFirstLegOrderStatus | ''
|
||||
dateRange: string[]
|
||||
}>({
|
||||
keyword: '',
|
||||
status: '',
|
||||
dateRange: [],
|
||||
})
|
||||
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '订单号或客户名称', props: { 'aria-label': '订单关键词' } },
|
||||
{
|
||||
key: 'status',
|
||||
type: 'select',
|
||||
placeholder: '全部状态',
|
||||
props: { 'aria-label': '订单状态' },
|
||||
options: [
|
||||
{ value: 'DRAFT', label: '草稿' },
|
||||
{ value: 'SUBMITTED', label: '待审核' },
|
||||
{ value: 'APPROVED', label: '已审核' },
|
||||
{ value: 'ACCEPTED', label: '已受理' },
|
||||
{ value: 'PROCESSING', label: '处理中' },
|
||||
{ value: 'COMPLETED', label: '已完成' },
|
||||
{ value: 'CANCELLED', label: '已取消' },
|
||||
{ value: 'REJECTED', label: '已驳回(旧契约)' },
|
||||
],
|
||||
},
|
||||
{ key: 'dateRange', type: 'daterange', props: { 'aria-label': '订单创建日期' } },
|
||||
]
|
||||
|
||||
const orderColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', minWidth: 200, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'orderInfo', label: '订单信息', minWidth: 210, slotName: 'orderInfo' },
|
||||
{ key: 'customer', label: '客户', minWidth: 190, showOverflowTooltip: true, slotName: 'customer' },
|
||||
{ key: 'transport', label: '运输方案', minWidth: 180, slotName: 'transport' },
|
||||
{ key: 'destination', label: '目的地', minWidth: 150, slotName: 'destination' },
|
||||
{ key: 'receivingWarehouse', label: '平台收货仓', minWidth: 180, slotName: 'receivingWarehouse' },
|
||||
{ key: 'express', label: '履约快递', minWidth: 160, slotName: 'express' },
|
||||
{ key: 'status', label: '状态', width: 120, slotName: 'status' },
|
||||
]
|
||||
|
||||
const expressRules: FormRules = {
|
||||
expressCompany: [{ required: true, message: '请填写快递公司', trigger: 'blur' }],
|
||||
expressTrackingNo: [
|
||||
{ required: true, message: '请填写快递单号', trigger: 'blur' },
|
||||
{ pattern: /^[A-Za-z0-9-]{4,128}$/, message: '快递单号格式不正确', trigger: 'blur' },
|
||||
],
|
||||
}
|
||||
|
||||
const noteRules: FormRules = {
|
||||
content: [{ required: true, message: '请填写内部备注', trigger: 'blur' }],
|
||||
}
|
||||
|
||||
const tenantReady = computed(() => loadedTenantId.value === PHASE_ONE_TENANT_ID)
|
||||
const detailOrderId = computed(() => {
|
||||
const orderId = route.query.orderId
|
||||
return typeof orderId === 'string' && orderId ? orderId : ''
|
||||
})
|
||||
const isDetailPage = computed(() => Boolean(detailOrderId.value))
|
||||
|
||||
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() {
|
||||
const targetTenantId = PHASE_ONE_TENANT_ID
|
||||
loadError.value = null
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await listPlatformFirstLegOrders(targetTenantId, {
|
||||
keyword: filters.value.keyword.trim() || undefined,
|
||||
status: filters.value.status || undefined,
|
||||
createdFrom: filters.value.dateRange.length === 2 ? `${filters.value.dateRange[0]}T00:00:00` : undefined,
|
||||
createdTo: filters.value.dateRange.length === 2 ? `${filters.value.dateRange[1]}T23:59:59` : undefined,
|
||||
page: page.value,
|
||||
size: pageSize.value,
|
||||
})
|
||||
orders.value = result.records
|
||||
total.value = result.total
|
||||
loadedTenantId.value = targetTenantId
|
||||
} catch (error) {
|
||||
orders.value = []
|
||||
total.value = 0
|
||||
loadError.value = getApiErrorDetails(error, '订单列表加载失败,请检查 Gateway、租户范围和订单权限')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function searchOrders() {
|
||||
if (page.value !== 1) {
|
||||
page.value = 1
|
||||
return
|
||||
}
|
||||
void loadOrders()
|
||||
}
|
||||
|
||||
watch([page, pageSize], () => {
|
||||
void loadOrders()
|
||||
})
|
||||
|
||||
async function openDetail(order: PlatformFirstLegOrderResource) {
|
||||
if (!tenantReady.value) return
|
||||
selectedOrder.value = order
|
||||
await router.push({ path: route.path, query: { ...route.query, orderId: String(order.id) } })
|
||||
}
|
||||
|
||||
async function loadDetail(orderId: string) {
|
||||
if (!tenantReady.value) return
|
||||
detail.value = null
|
||||
detailLoading.value = true
|
||||
try {
|
||||
detail.value = await getPlatformFirstLegOrder(loadedTenantId.value, orderId)
|
||||
selectedOrder.value = detail.value.order
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '订单详情加载失败')
|
||||
ElMessage.error(details.message)
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAfterAction(orderId: string) {
|
||||
await loadOrders()
|
||||
if (detailOrderId.value === orderId) {
|
||||
await loadDetail(orderId)
|
||||
}
|
||||
}
|
||||
|
||||
function closeDetailPage() {
|
||||
const { orderId: _orderId, ...query } = route.query
|
||||
void router.replace({ path: route.path, query })
|
||||
}
|
||||
|
||||
function getFieldValidationMessage(error: unknown, field: string, fallback: string) {
|
||||
const details = getApiErrorDetails(error, fallback)
|
||||
if (error instanceof ApiResponseError && error.details && typeof error.details === 'object') {
|
||||
const fieldMessage = (error.details as Record<string, unknown>)[field]
|
||||
if (typeof fieldMessage === 'string' && fieldMessage) {
|
||||
return `${details.message}:${fieldMessage}`
|
||||
}
|
||||
}
|
||||
return details.message
|
||||
}
|
||||
|
||||
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
|
||||
void nextTick(() => expressFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
async function saveExpress() {
|
||||
if (!selectedOrder.value || !tenantReady.value) return
|
||||
const valid = await expressFormRef.value?.validate().catch(() => false)
|
||||
if (!valid) 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(getFieldValidationMessage(error, 'expressTrackingNo', '履约快递信息保存失败'))
|
||||
} finally {
|
||||
expressSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openNote(order: PlatformFirstLegOrderResource) {
|
||||
selectedOrder.value = order
|
||||
noteForm.content = ''
|
||||
noteDialogOpen.value = true
|
||||
void nextTick(() => noteFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
async function saveNote() {
|
||||
if (!selectedOrder.value || !tenantReady.value) return
|
||||
const valid = await noteFormRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
noteSaving.value = true
|
||||
try {
|
||||
await addPlatformFirstLegOrderNote(loadedTenantId.value, String(selectedOrder.value.id), noteForm.content.trim())
|
||||
noteDialogOpen.value = false
|
||||
await refreshAfterAction(String(selectedOrder.value.id))
|
||||
ElMessage.success('内部备注已保存')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorDetails(error, '内部备注保存失败').message)
|
||||
} finally {
|
||||
noteSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(detailOrderId, (orderId) => {
|
||||
if (orderId) {
|
||||
void loadDetail(orderId)
|
||||
return
|
||||
}
|
||||
detail.value = null
|
||||
selectedOrder.value = null
|
||||
void loadOrders()
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<template v-if="isDetailPage">
|
||||
<section class="surface-panel detail-page" v-loading="detailLoading">
|
||||
<header class="detail-page-header">
|
||||
<div>
|
||||
<h1>订单详情</h1>
|
||||
<p>查看订单信息、履约快递、内部备注和状态历史。</p>
|
||||
</div>
|
||||
<el-button @click="closeDetailPage"><ArrowLeft :size="16" />返回订单列表</el-button>
|
||||
</header>
|
||||
|
||||
<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>
|
||||
<div class="detail-table-scroll">
|
||||
<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>
|
||||
|
||||
<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="订单详情暂不可用"><el-button type="primary" @click="closeDetailPage">返回订单列表</el-button></el-empty>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<QueryToolbar
|
||||
v-model="filters"
|
||||
ariaLabel="头程订单筛选"
|
||||
:fields="queryFields"
|
||||
search-text="查询"
|
||||
:search-on-reset="true"
|
||||
@search="searchOrders"
|
||||
/>
|
||||
|
||||
<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 link type="danger" @click="loadOrders">重新加载</el-button>
|
||||
</el-alert>
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<DataTable
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:data="orders"
|
||||
:columns="orderColumns"
|
||||
:loading="loading"
|
||||
:total="total"
|
||||
:page-sizes="[20, 50, 100]"
|
||||
empty-text="当前没有符合条件的头程订单"
|
||||
row-key="id"
|
||||
>
|
||||
<template #actions="{ 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>
|
||||
<template #orderInfo="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).orderNo || '-' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).referenceId || '无客户参考号' }} · {{ formattedDate((row as PlatformFirstLegOrderResource).createdAt) }}</span></div></template>
|
||||
<template #customer="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).customerName }}</strong><span>租户 {{ (row as PlatformFirstLegOrderResource).tenantId }}</span></div></template>
|
||||
<template #transport="{ row }"><div class="primary-cell"><strong>{{ transportLabel(row as PlatformFirstLegOrderResource) }}</strong><span>{{ (row as PlatformFirstLegOrderResource).channelName || '未填写渠道' }}</span></div></template>
|
||||
<template #destination="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).destinationWarehouseName || '-' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).destinationCountryCode || '-' }}</span></div></template>
|
||||
<template #receivingWarehouse="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).receivingWarehouseName || '-' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).receivingWarehouseAddress || '-' }}</span></div></template>
|
||||
<template #express="{ row }"><div class="primary-cell"><strong>{{ (row as PlatformFirstLegOrderResource).expressCompany || '未维护' }}</strong><span>{{ (row as PlatformFirstLegOrderResource).expressTrackingNo || '—' }}</span></div></template>
|
||||
<template #status="{ row }"><StatusBadge :status="statusLabel((row as PlatformFirstLegOrderResource).status)" /></template>
|
||||
<template #empty><el-empty description="当前没有符合条件的头程订单" /></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<el-dialog v-model="expressDialogOpen" title="维护履约快递" width="520px">
|
||||
<el-alert title="当前后端契约只接收快递公司名称和快递单号;快递主数据关联待后端补充。" type="info" :closable="false" show-icon />
|
||||
<el-form ref="expressFormRef" :model="expressForm" :rules="expressRules" label-position="top" class="delivery-form"><el-form-item label="快递公司" prop="expressCompany" required><el-input v-model.trim="expressForm.expressCompany" maxlength="64" placeholder="例如 顺丰速运" /></el-form-item><el-form-item label="快递单号" prop="expressTrackingNo" 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 ref="noteFormRef" :model="noteForm" :rules="noteRules" label-position="top"><el-form-item label="内部备注" prop="content" required><el-input v-model.trim="noteForm.content" 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>
|
||||
.detail-page { overflow: hidden; }
|
||||
.detail-page-header { display: flex; min-height: 88px; align-items: center; justify-content: space-between; gap: 18px; padding: 20px 24px; border-bottom: 1px solid var(--cc-border); }
|
||||
.detail-page-header h1 { margin: 0; font-size: 20px; line-height: 1.35; }
|
||||
.detail-page-header p { margin: 5px 0 0; color: var(--cc-muted); font-size: 12px; line-height: 1.5; }
|
||||
.detail-table-scroll { overflow-x: auto; }
|
||||
.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) {
|
||||
.detail-page-header { align-items: flex-start; flex-direction: column; padding: 16px; }
|
||||
.detail-page-header .el-button { width: 100%; min-height: 40px; }
|
||||
.detail-table-scroll :deep(.el-table) { min-width: 560px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import PlatformFirstLegOrdersPanel from '@/modules/first-leg-orders/components/PlatformFirstLegOrdersPanel.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PlatformFirstLegOrdersPanel />
|
||||
</template>
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const firstLegOrderRoutes = [
|
||||
{
|
||||
path: 'orders/first-leg',
|
||||
name: 'first-leg-orders',
|
||||
component: () => import('@/modules/first-leg-orders/pages/FirstLegOrdersView.vue'),
|
||||
meta: { title: '头程订单', description: '创建、受理和跟进客户提交的头程运输订单', permission: 'platform:order:list' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,326 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
assignPlatformInternalUserRoles,
|
||||
changePlatformManagedUserStatus,
|
||||
changePlatformInternalUserStatus,
|
||||
changePlatformTenantStatus,
|
||||
changePlatformPermissionStatus,
|
||||
changePlatformRoleStatus,
|
||||
createPlatformPermission,
|
||||
createPlatformManagedUser,
|
||||
createPlatformRole,
|
||||
createPlatformTenant,
|
||||
deletePlatformPermission,
|
||||
deletePlatformRole,
|
||||
downloadTenantQualification,
|
||||
listPlatformTenants,
|
||||
listPlatformTenantOrderCounts,
|
||||
listTenantQualifications,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
listPlatformInternalUsers,
|
||||
listPlatformManagedUsers,
|
||||
getPlatformUserOptions,
|
||||
qualificationFileName,
|
||||
replacePlatformRolePermissions,
|
||||
resetPlatformInternalUserPassword,
|
||||
resetPlatformManagedUserPassword,
|
||||
submitPlatformTenantReview,
|
||||
updatePlatformInternalUser,
|
||||
updatePlatformManagedUser,
|
||||
updatePlatformPermission,
|
||||
updatePlatformRole,
|
||||
updatePlatformTenant,
|
||||
uploadPlatformTenantQualification,
|
||||
type PlatformPermissionResource,
|
||||
type PlatformInternalUser,
|
||||
type PlatformManagedUser,
|
||||
type PlatformRoleResource,
|
||||
} from './platformIam'
|
||||
|
||||
vi.mock('@/shared/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
const role: PlatformRoleResource = {
|
||||
id: 4000002,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
roleType: 'SYSTEM',
|
||||
status: 'ACTIVE',
|
||||
description: '企业资料与入驻审核',
|
||||
permissionIds: ['5100010'],
|
||||
}
|
||||
|
||||
const permission: PlatformPermissionResource = {
|
||||
id: 5100010,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: 5100000,
|
||||
permissionCode: 'platform:customer:list',
|
||||
permissionName: '企业客户',
|
||||
routePath: '/customers',
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
builtIn: false,
|
||||
}
|
||||
|
||||
const internalUser: PlatformInternalUser = {
|
||||
membershipId: 3000001,
|
||||
userId: 2000001,
|
||||
authUserId: 2000001,
|
||||
username: 'platform_admin',
|
||||
displayName: '平台管理员',
|
||||
phone: '13800138000',
|
||||
email: 'admin@example.com',
|
||||
memberType: 'INTERNAL',
|
||||
memberNo: 'PLATFORM-0001',
|
||||
status: 'ACTIVE',
|
||||
roleIds: [4000001],
|
||||
}
|
||||
|
||||
const managedUser: PlatformManagedUser = {
|
||||
membershipId: '3000002',
|
||||
userId: '2000002',
|
||||
authUserId: '1000002',
|
||||
username: 'zhangwei',
|
||||
displayName: '张伟',
|
||||
phone: '13800138000',
|
||||
email: 'zhangwei@example.com',
|
||||
tenantId: '10001',
|
||||
tenantName: '华远贸易',
|
||||
memberType: 'EMPLOYEE',
|
||||
memberNo: 'MEMBER-3000002',
|
||||
status: 'ACTIVE',
|
||||
roleIds: ['40001'],
|
||||
roleNames: ['租户管理员'],
|
||||
lastLoginAt: '2026-06-01T10:30:00',
|
||||
protectedAccount: false,
|
||||
}
|
||||
|
||||
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 () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [role] })
|
||||
|
||||
await expect(listPlatformRoles()).resolves.toEqual([role])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/roles')
|
||||
})
|
||||
|
||||
it('creates a platform role with the documented payload', async () => {
|
||||
const payload = {
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
description: '企业资料与入驻审核',
|
||||
}
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: role })
|
||||
|
||||
await expect(createPlatformRole(payload)).resolves.toEqual(role)
|
||||
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: '200', message: 'success', data: role })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '200', 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: '200', message: 'success', data: [permission] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: permission })
|
||||
const payload = {
|
||||
type: 'MENU' as const,
|
||||
code: permission.permissionCode,
|
||||
name: permission.permissionName,
|
||||
parentId: permission.parentId,
|
||||
routePath: permission.routePath,
|
||||
httpMethod: null,
|
||||
sortNo: permission.sortNo,
|
||||
}
|
||||
|
||||
await expect(listPlatformPermissions()).resolves.toEqual([permission])
|
||||
await expect(createPlatformPermission(payload)).resolves.toEqual(permission)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/permissions')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/permissions', payload)
|
||||
})
|
||||
|
||||
it('updates, changes status, and deletes custom permission resources with IAM routes', async () => {
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: permission })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
const payload = { name: '企业客户', parentId: permission.parentId, routePath: '/customers', httpMethod: null, sortNo: 10 }
|
||||
|
||||
await expect(updatePlatformPermission(permission.id, payload)).resolves.toEqual(permission)
|
||||
await expect(changePlatformPermissionStatus(permission.id, 'DISABLED')).resolves.toEqual(permission)
|
||||
await expect(deletePlatformPermission(permission.id)).resolves.toBeNull()
|
||||
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/permissions/${permission.id}`, payload)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/permissions/${permission.id}/status`, { status: 'DISABLED' })
|
||||
expect(http.delete).toHaveBeenCalledWith(`/platform/v1/iam/permissions/${permission.id}`)
|
||||
})
|
||||
|
||||
it('maintains internal users through their public membership ID', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [internalUser] })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: internalUser })
|
||||
const update = {
|
||||
displayName: '平台管理员',
|
||||
phone: '13800138000',
|
||||
email: 'admin@example.com',
|
||||
memberNo: 'PLATFORM-0001',
|
||||
roleIds: [4000001],
|
||||
}
|
||||
|
||||
await expect(listPlatformInternalUsers()).resolves.toEqual([internalUser])
|
||||
await expect(updatePlatformInternalUser(internalUser.membershipId, update)).resolves.toEqual(internalUser)
|
||||
await expect(changePlatformInternalUserStatus(internalUser.membershipId, 'DISABLED')).resolves.toEqual(internalUser)
|
||||
await expect(resetPlatformInternalUserPassword(internalUser.membershipId, 'ChangeMe123')).resolves.toEqual(internalUser)
|
||||
await expect(assignPlatformInternalUserRoles(internalUser.membershipId, [4000001])).resolves.toEqual(internalUser)
|
||||
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/internal-users')
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/internal-users/${internalUser.membershipId}`, update)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/internal-users/${internalUser.membershipId}/status`, { status: 'DISABLED' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(3, `/platform/v1/iam/internal-users/${internalUser.membershipId}/password`, { newPassword: 'ChangeMe123' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(4, `/platform/v1/iam/internal-users/${internalUser.membershipId}/roles`, { roleIds: [4000001] })
|
||||
})
|
||||
|
||||
it('maintains platform and tenant users through the unified user contract', async () => {
|
||||
const userOptions = {
|
||||
tenants: [{ id: '10001', name: '华远贸易', status: 'ACTIVE' }],
|
||||
roles: [{ id: '40001', tenantId: '10001', name: '租户管理员', status: 'ACTIVE' }],
|
||||
}
|
||||
const create = {
|
||||
username: 'zhangwei', displayName: '张伟', phone: '13800138000', email: 'zhangwei@example.com',
|
||||
tenantId: '10001', roleIds: ['40001'], password: 'Password1', status: 'ACTIVE' as const,
|
||||
}
|
||||
const update = {
|
||||
displayName: '张伟', phone: '13800138000', email: 'zhangwei@example.com',
|
||||
tenantId: '10001', roleIds: ['40001'],
|
||||
}
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', message: 'success', data: [managedUser] })
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: userOptions })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: managedUser })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: managedUser })
|
||||
|
||||
await expect(listPlatformManagedUsers()).resolves.toEqual([managedUser])
|
||||
await expect(getPlatformUserOptions()).resolves.toEqual(userOptions)
|
||||
await expect(createPlatformManagedUser(create)).resolves.toEqual(managedUser)
|
||||
await expect(updatePlatformManagedUser(managedUser.membershipId, update)).resolves.toEqual(managedUser)
|
||||
await expect(changePlatformManagedUserStatus(managedUser.membershipId, 'DISABLED')).resolves.toEqual(managedUser)
|
||||
await expect(resetPlatformManagedUserPassword(managedUser.membershipId, 'ChangeMe123')).resolves.toEqual(managedUser)
|
||||
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/iam/users')
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/iam/users/options')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/users', create)
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/users/${managedUser.membershipId}`, update)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/users/${managedUser.membershipId}/status`, { status: 'DISABLED' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(3, `/platform/v1/iam/users/${managedUser.membershipId}/password`, { newPassword: 'ChangeMe123' })
|
||||
})
|
||||
|
||||
it('loads qualifications for the selected tenant', async () => {
|
||||
const qualification = {
|
||||
id: 12,
|
||||
tenantId: 8,
|
||||
qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: '91440300XXXXXXXXXX',
|
||||
documentUrl: '/api/merchant/v1/files/qualifications/license.png',
|
||||
status: 'PENDING' as const,
|
||||
reviewComment: null,
|
||||
}
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [qualification] })
|
||||
|
||||
await expect(listTenantQualifications(8)).resolves.toEqual([qualification])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/tenants/8/qualifications')
|
||||
})
|
||||
|
||||
it('loads paginated tenants with the documented filters', async () => {
|
||||
const page = { records: [], page: 2, size: 10, total: 11, pages: 2 }
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { ...page, page: '2', size: '10', total: '11', pages: '2' } })
|
||||
|
||||
await expect(listPlatformTenants({ page: 2, size: 10, keyword: '柏悦', status: 'ACTIVE' })).resolves.toEqual(page)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/tenants', {
|
||||
params: { page: 2, size: 10, keyword: '柏悦', status: 'ACTIVE' },
|
||||
})
|
||||
})
|
||||
|
||||
it('creates, updates, and changes customer status with the platform tenant contract', async () => {
|
||||
const tenant = { id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'ACTIVE' }
|
||||
const create = {
|
||||
tenantName: '柏悦物流', legalName: '柏悦物流有限公司', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
||||
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com', servicePackage: '标准版',
|
||||
contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30, enterpriseType: '有限责任公司',
|
||||
establishedDate: '2020-01-01', registeredCapital: 1000, registeredCapitalCurrency: 'CNY',
|
||||
registeredAddress: '深圳市宝安区', internalRemark: '重点客户',
|
||||
}
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: tenant })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: tenant })
|
||||
|
||||
await expect(createPlatformTenant(create)).resolves.toEqual(tenant)
|
||||
const { unifiedSocialCreditCode: _creditCode, ...update } = create
|
||||
await expect(updatePlatformTenant('8', update)).resolves.toEqual(tenant)
|
||||
await expect(changePlatformTenantStatus('8', 'DISABLED')).resolves.toEqual(tenant)
|
||||
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/tenants', create)
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, '/platform/v1/iam/tenants/8', update)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, '/platform/v1/iam/tenants/8/status', { status: 'DISABLED' })
|
||||
})
|
||||
|
||||
it('loads real order totals for the visible customer tenants', async () => {
|
||||
const counts = [{ tenantId: '8', orderCount: 12 }, { tenantId: '9', orderCount: 0 }]
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: counts })
|
||||
await expect(listPlatformTenantOrderCounts(['8', '9'])).resolves.toEqual(counts)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/orders/first-leg/tenant-counts?tenantIds=8,9')
|
||||
})
|
||||
|
||||
it('uploads qualification metadata before explicitly submitting the customer review', async () => {
|
||||
const uploadResult = { qualificationId: '91', reviewId: null, tenantStatus: 'PROFILE_REQUIRED', documentUrl: '/file.pdf' }
|
||||
const tenant = { id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'PENDING' }
|
||||
vi.mocked(http.post).mockResolvedValueOnce({ code: '200', message: 'success', data: uploadResult })
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: tenant })
|
||||
const file = new File(['%PDF-1.4'], '营业执照.pdf', { type: 'application/pdf' })
|
||||
|
||||
await expect(uploadPlatformTenantQualification('8', 'BUSINESS_LICENSE', file, '2030-12-31', '91440300MA5ABCDE12', true)).resolves.toEqual(uploadResult)
|
||||
await expect(submitPlatformTenantReview('8')).resolves.toEqual(tenant)
|
||||
|
||||
const form = vi.mocked(http.post).mock.calls[0]?.[1] as FormData
|
||||
expect(http.post).toHaveBeenNthCalledWith(1, '/platform/v1/files/qualifications/8', expect.any(FormData))
|
||||
expect(form.get('file')).toBe(file)
|
||||
expect(form.get('qualificationType')).toBe('BUSINESS_LICENSE')
|
||||
expect(form.get('validTo')).toBe('2030-12-31')
|
||||
expect(form.get('certificateNo')).toBe('91440300MA5ABCDE12')
|
||||
expect(form.get('replace')).toBe('true')
|
||||
expect(http.post).toHaveBeenNthCalledWith(2, '/platform/v1/iam/tenants/8/submit-review', {})
|
||||
})
|
||||
|
||||
it('downloads a qualification with the platform file endpoint and a safe filename', async () => {
|
||||
const blob = new Blob(['image'], { type: 'image/png' })
|
||||
vi.mocked(http.get).mockResolvedValue(blob)
|
||||
|
||||
expect(qualificationFileName('/api/merchant/v1/files/qualifications/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png?token=ignored')).toBe('营业执照.png')
|
||||
await expect(downloadTenantQualification(8, '/api/merchant/v1/files/qualifications/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png')).resolves.toBe(blob)
|
||||
expect(http.get).toHaveBeenCalledWith(
|
||||
'/platform/v1/files/qualifications/8/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png',
|
||||
{ responseType: 'blob' },
|
||||
)
|
||||
expect(() => qualificationFileName('/api/merchant/v1/files/qualifications/%2Fetc%2Fpasswd')).toThrow('资质文件地址无效')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,446 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import type { PlatformPermissionResource } from '@/shared/types/platformPermission'
|
||||
|
||||
export type { PlatformPermissionResource } from '@/shared/types/platformPermission'
|
||||
|
||||
export interface EnterpriseReview {
|
||||
id: number
|
||||
tenantId: number
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
tenantName?: string | null
|
||||
tenantCode?: string | null
|
||||
qualificationId?: number | null
|
||||
qualificationType?: string | null
|
||||
certificateNo?: string | null
|
||||
documentUrl?: string | null
|
||||
contactName?: string | null
|
||||
contactPhone?: string | null
|
||||
contactEmail?: string | null
|
||||
submittedAt?: string | null
|
||||
createdAt?: string | null
|
||||
reviewComment?: string | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type PlatformTenantStatus = 'PENDING' | 'ACTIVE' | 'REJECTED' | 'INACTIVE' | string
|
||||
|
||||
export interface PlatformTenantResource {
|
||||
id: number | string
|
||||
tenantCode: string
|
||||
tenantName: string
|
||||
status: PlatformTenantStatus
|
||||
legalName: string | null
|
||||
unifiedSocialCreditCode: string | null
|
||||
contactName: string | null
|
||||
contactPhone: string | null
|
||||
contactEmail: string | null
|
||||
servicePackage: string | null
|
||||
contactWechat: string | null
|
||||
salesOwnerName: string | null
|
||||
paymentTermDays: number | null
|
||||
enterpriseType: string | null
|
||||
establishedDate: string | null
|
||||
registeredCapital: number | string | null
|
||||
registeredCapitalCurrency: string | null
|
||||
registeredAddress: string | null
|
||||
internalRemark: string | null
|
||||
createdAt: string | null
|
||||
approvedAt: string | null
|
||||
}
|
||||
|
||||
export interface CreatePlatformTenantRequest {
|
||||
tenantName: string
|
||||
legalName: string
|
||||
unifiedSocialCreditCode: string
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
contactEmail: string
|
||||
servicePackage: string
|
||||
contactWechat: string
|
||||
salesOwnerName: string
|
||||
paymentTermDays: number
|
||||
enterpriseType: string
|
||||
establishedDate: string | null
|
||||
registeredCapital: number | null
|
||||
registeredCapitalCurrency: string
|
||||
registeredAddress: string
|
||||
internalRemark: string
|
||||
}
|
||||
|
||||
export type UpdatePlatformTenantRequest = Omit<CreatePlatformTenantRequest, 'unifiedSocialCreditCode'>
|
||||
|
||||
export interface PlatformTenantOrderCount {
|
||||
tenantId: number | string
|
||||
orderCount: number
|
||||
}
|
||||
|
||||
export interface PlatformTenantPage {
|
||||
records: PlatformTenantResource[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
export interface PlatformTenantQuery {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
status?: PlatformTenantStatus
|
||||
}
|
||||
|
||||
export interface PlatformTenantQualification {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
qualificationType: 'BUSINESS_LICENSE' | string
|
||||
certificateNo: string | null
|
||||
documentUrl: string
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
reviewComment: string | null
|
||||
validTo?: string | null
|
||||
}
|
||||
|
||||
export type PlatformQualificationType = 'BUSINESS_LICENSE' | 'LEGAL_PERSON_ID' | 'FREIGHT_FORWARDER_CERTIFICATE' | 'BANK_ACCOUNT_LICENSE'
|
||||
|
||||
export interface PlatformQualificationUploadResponse {
|
||||
qualificationId: number | string
|
||||
reviewId: number | string | null
|
||||
tenantStatus: PlatformTenantStatus
|
||||
documentUrl: string
|
||||
replacedDocumentUrl?: string | null
|
||||
}
|
||||
|
||||
export interface PlatformRoleResource {
|
||||
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 {
|
||||
roleCode: string
|
||||
roleName: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface UpdatePlatformRoleRequest {
|
||||
roleName: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface CreatePlatformPermissionRequest {
|
||||
type: 'MENU' | 'BUTTON'
|
||||
code: string
|
||||
name: string
|
||||
parentId: number | string
|
||||
routePath: string | null
|
||||
httpMethod: null
|
||||
sortNo: number
|
||||
}
|
||||
|
||||
export interface UpdatePlatformPermissionRequest {
|
||||
name: string
|
||||
parentId: number | string | null
|
||||
routePath: string | null
|
||||
httpMethod: string | null
|
||||
sortNo: number
|
||||
}
|
||||
|
||||
export interface PlatformInternalUser {
|
||||
membershipId: number | string
|
||||
userId: number | string
|
||||
authUserId: number | string
|
||||
username: string
|
||||
displayName: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
memberType: string
|
||||
memberNo: string | null
|
||||
status: 'ACTIVE' | 'DISABLED' | string
|
||||
roleIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface CreatePlatformInternalUserRequest {
|
||||
authUserId: number | string
|
||||
userType: string
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
memberNo?: string
|
||||
roleIds?: Array<number | string>
|
||||
}
|
||||
|
||||
export interface UpdatePlatformInternalUserRequest {
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
memberNo: string
|
||||
roleIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface PlatformManagedUser {
|
||||
membershipId: number | string
|
||||
userId: number | string
|
||||
authUserId: number | string
|
||||
username: string
|
||||
displayName: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
tenantId: number | string
|
||||
tenantName: string
|
||||
memberType: string
|
||||
memberNo: string | null
|
||||
status: 'ACTIVE' | 'DISABLED'
|
||||
roleIds: Array<number | string>
|
||||
roleNames: string[]
|
||||
lastLoginAt: string | null
|
||||
protectedAccount: boolean
|
||||
}
|
||||
|
||||
export interface PlatformUserOptions {
|
||||
tenants: Array<{ id: number | string; name: string; status: string }>
|
||||
roles: Array<{ id: number | string; tenantId: number | string; name: string; status: string }>
|
||||
}
|
||||
|
||||
export interface CreatePlatformManagedUserRequest {
|
||||
username: string
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
tenantId: number | string
|
||||
roleIds: Array<number | string>
|
||||
password: string
|
||||
status: 'ACTIVE' | 'DISABLED'
|
||||
}
|
||||
|
||||
export interface UpdatePlatformManagedUserRequest {
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
tenantId: number | string
|
||||
roleIds: Array<number | string>
|
||||
}
|
||||
|
||||
async function getData<T>(path: string): Promise<T> {
|
||||
const response = await http.get<ApiEnvelope<T>, ApiEnvelope<T>>(path)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function postData<T>(path: string, body: unknown): Promise<T> {
|
||||
const response = await http.post<ApiEnvelope<T>, ApiEnvelope<T>>(path, body)
|
||||
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 listEnterpriseReviews() {
|
||||
return getData<EnterpriseReview[]>('/platform/v1/iam/reviews')
|
||||
}
|
||||
|
||||
export async function listPlatformTenants(query: PlatformTenantQuery) {
|
||||
const response = await http.get<ApiEnvelope<PlatformTenantPage>, ApiEnvelope<PlatformTenantPage>>(
|
||||
'/platform/v1/iam/tenants',
|
||||
{
|
||||
params: {
|
||||
page: query.page,
|
||||
size: query.size,
|
||||
...(query.keyword ? { keyword: query.keyword } : {}),
|
||||
...(query.status ? { status: query.status } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
const data = unwrapApiResponse(response)
|
||||
return {
|
||||
...data,
|
||||
page: Number(data.page),
|
||||
size: Number(data.size),
|
||||
total: Number(data.total),
|
||||
pages: Number(data.pages),
|
||||
}
|
||||
}
|
||||
|
||||
export function getPlatformTenant(tenantId: number | string) {
|
||||
return getData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}`)
|
||||
}
|
||||
|
||||
export function createPlatformTenant(payload: CreatePlatformTenantRequest) {
|
||||
return postData<PlatformTenantResource>('/platform/v1/iam/tenants', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformTenant(tenantId: number | string, payload: UpdatePlatformTenantRequest) {
|
||||
return putData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformTenantStatus(tenantId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}/status`, { status })
|
||||
}
|
||||
|
||||
export function submitPlatformTenantReview(tenantId: number | string) {
|
||||
return postData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}/submit-review`, {})
|
||||
}
|
||||
|
||||
export async function uploadPlatformTenantQualification(
|
||||
tenantId: number | string,
|
||||
qualificationType: PlatformQualificationType,
|
||||
file: File,
|
||||
validTo?: string,
|
||||
certificateNo?: string,
|
||||
replace = false,
|
||||
) {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
form.append('qualificationType', qualificationType)
|
||||
if (validTo) form.append('validTo', validTo)
|
||||
if (certificateNo) form.append('certificateNo', certificateNo)
|
||||
if (replace) form.append('replace', 'true')
|
||||
const response = await http.post<ApiEnvelope<PlatformQualificationUploadResponse>, ApiEnvelope<PlatformQualificationUploadResponse>>(
|
||||
`/platform/v1/files/qualifications/${tenantId}`,
|
||||
form,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export function listPlatformTenantOrderCounts(tenantIds: Array<number | string>) {
|
||||
const ids = tenantIds.map((id) => encodeURIComponent(String(id))).join(',')
|
||||
return getData<PlatformTenantOrderCount[]>(`/platform/v1/orders/first-leg/tenant-counts?tenantIds=${ids}`)
|
||||
}
|
||||
|
||||
export function listTenantQualifications(tenantId: number | string) {
|
||||
return getData<PlatformTenantQualification[]>(`/platform/v1/iam/tenants/${tenantId}/qualifications`)
|
||||
}
|
||||
|
||||
export function qualificationFileName(documentUrl: string) {
|
||||
const path = documentUrl.split(/[?#]/, 1)[0]
|
||||
const encodedName = path.split('/').filter(Boolean).at(-1)
|
||||
if (!encodedName) throw new Error('资质文件地址无效')
|
||||
let fileName: string
|
||||
try {
|
||||
fileName = decodeURIComponent(encodedName)
|
||||
} catch {
|
||||
throw new Error('资质文件地址无效')
|
||||
}
|
||||
if (!fileName || fileName === '.' || fileName === '..' || /[\\/]/.test(fileName)) {
|
||||
throw new Error('资质文件地址无效')
|
||||
}
|
||||
return fileName
|
||||
}
|
||||
|
||||
export function downloadTenantQualification(tenantId: number | string, documentUrl: string) {
|
||||
const fileName = qualificationFileName(documentUrl)
|
||||
return http.get<Blob, Blob>(`/platform/v1/files/qualifications/${tenantId}/${encodeURIComponent(fileName)}`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
}
|
||||
|
||||
export function listPlatformRoles() {
|
||||
return getData<PlatformRoleResource[]>('/platform/v1/iam/roles')
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
export function updatePlatformPermission(permissionId: number | string, payload: UpdatePlatformPermissionRequest) {
|
||||
return putData<PlatformPermissionResource>(`/platform/v1/iam/permissions/${permissionId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformPermissionStatus(permissionId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformPermissionResource>(`/platform/v1/iam/permissions/${permissionId}/status`, { status })
|
||||
}
|
||||
|
||||
export function deletePlatformPermission(permissionId: number | string) {
|
||||
return deleteData<void>(`/platform/v1/iam/permissions/${permissionId}`)
|
||||
}
|
||||
|
||||
export function listPlatformInternalUsers() {
|
||||
return getData<PlatformInternalUser[]>('/platform/v1/iam/internal-users')
|
||||
}
|
||||
|
||||
export function createPlatformInternalUser(payload: CreatePlatformInternalUserRequest) {
|
||||
return postData<PlatformInternalUser>('/platform/v1/iam/internal-users', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformInternalUser(membershipId: number | string, payload: UpdatePlatformInternalUserRequest) {
|
||||
return putData<PlatformInternalUser>(`/platform/v1/iam/internal-users/${membershipId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformInternalUserStatus(membershipId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformInternalUser>(`/platform/v1/iam/internal-users/${membershipId}/status`, { status })
|
||||
}
|
||||
|
||||
export function resetPlatformInternalUserPassword(membershipId: number | string, newPassword: string) {
|
||||
return putData<void>(`/platform/v1/iam/internal-users/${membershipId}/password`, { newPassword })
|
||||
}
|
||||
|
||||
export function assignPlatformInternalUserRoles(membershipId: number | string, roleIds: Array<number | string>) {
|
||||
return putData<PlatformInternalUser>(`/platform/v1/iam/internal-users/${membershipId}/roles`, { roleIds })
|
||||
}
|
||||
|
||||
export function listPlatformManagedUsers() {
|
||||
return getData<PlatformManagedUser[]>('/platform/v1/iam/users')
|
||||
}
|
||||
|
||||
export function getPlatformUserOptions() {
|
||||
return getData<PlatformUserOptions>('/platform/v1/iam/users/options')
|
||||
}
|
||||
|
||||
export function createPlatformManagedUser(payload: CreatePlatformManagedUserRequest) {
|
||||
return postData<PlatformManagedUser>('/platform/v1/iam/users', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformManagedUser(membershipId: number | string, payload: UpdatePlatformManagedUserRequest) {
|
||||
return putData<PlatformManagedUser>(`/platform/v1/iam/users/${membershipId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformManagedUserStatus(membershipId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformManagedUser>(`/platform/v1/iam/users/${membershipId}/status`, { status })
|
||||
}
|
||||
|
||||
export function resetPlatformManagedUserPassword(membershipId: number | string, newPassword: string) {
|
||||
return putData<void>(`/platform/v1/iam/users/${membershipId}/password`, { newPassword })
|
||||
}
|
||||
|
||||
export function approveEnterpriseReview(reviewId: number, comment: string) {
|
||||
return postData<unknown>(`/platform/v1/iam/reviews/${reviewId}/approve`, { comment })
|
||||
}
|
||||
|
||||
export function rejectEnterpriseReview(reviewId: number, comment: string) {
|
||||
return postData<unknown>(`/platform/v1/iam/reviews/${reviewId}/reject`, { comment })
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './api/platformIam'
|
||||
@@ -0,0 +1,123 @@
|
||||
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 {
|
||||
getPlatformUserOptions,
|
||||
listPlatformManagedUsers,
|
||||
type PlatformManagedUser,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import InternalUsersView from './InternalUsersView.vue'
|
||||
|
||||
vi.mock('@/modules/iam/api/platformIam', () => ({
|
||||
listPlatformManagedUsers: vi.fn(),
|
||||
getPlatformUserOptions: vi.fn(),
|
||||
createPlatformManagedUser: vi.fn(),
|
||||
updatePlatformManagedUser: vi.fn(),
|
||||
changePlatformManagedUserStatus: vi.fn(),
|
||||
resetPlatformManagedUserPassword: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
const user: PlatformManagedUser = {
|
||||
membershipId: '30', userId: '20', authUserId: '10', username: 'zhangwei', displayName: '张伟',
|
||||
phone: '13800138000', email: 'zhangwei@example.com', tenantId: '10001', tenantName: '华远贸易',
|
||||
memberType: 'EMPLOYEE', memberNo: 'MEMBER-30', status: 'ACTIVE', roleIds: ['40'],
|
||||
roleNames: ['租户管理员'], lastLoginAt: '2026-06-01T10:30:00',
|
||||
protectedAccount: false,
|
||||
}
|
||||
|
||||
async function mountView() {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = [
|
||||
'platform:user:list', 'platform:user:create', 'platform:user:edit',
|
||||
'platform:user:status', 'platform:user:reset-password', 'platform:user:grant-role',
|
||||
]
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
const wrapper = mount(InternalUsersView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia, ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
afterAll(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('InternalUsersView unified platform user management', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
document.body.innerHTML = ''
|
||||
vi.mocked(listPlatformManagedUsers).mockReset().mockResolvedValue([user])
|
||||
vi.mocked(getPlatformUserOptions).mockReset().mockResolvedValue({
|
||||
tenants: [
|
||||
{ id: '0', name: '平台', status: 'ACTIVE' },
|
||||
{ id: '10001', name: '华远贸易', status: 'ACTIVE' },
|
||||
],
|
||||
roles: [{ id: '40', tenantId: '10001', name: '租户管理员', status: 'ACTIVE' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('loads and renders prototype fields from the unified API', async () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(listPlatformManagedUsers).toHaveBeenCalledOnce()
|
||||
expect(getPlatformUserOptions).toHaveBeenCalledOnce()
|
||||
expect(wrapper.text()).toContain('zhangwei')
|
||||
expect(wrapper.text()).toContain('张伟')
|
||||
expect(wrapper.text()).toContain('华远贸易')
|
||||
expect(wrapper.text()).toContain('租户管理员')
|
||||
expect(wrapper.text()).toContain('2026-06-01 10:30')
|
||||
expect(wrapper.text()).not.toContain('认证用户 ID')
|
||||
expect(wrapper.text()).not.toContain('成员编号')
|
||||
})
|
||||
|
||||
it('opens the complete prototype create form', async () => {
|
||||
const wrapper = await mountView()
|
||||
const createButton = wrapper.findAll('button').find((button) => button.text().trim() === '新增用户')
|
||||
await createButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(document.querySelector('input[placeholder="登录用户名"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="真实姓名"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="手机号码"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="邮箱地址"]')).not.toBeNull()
|
||||
expect(document.body.textContent).toContain('所属租户')
|
||||
expect(document.body.textContent).toContain('初始密码')
|
||||
expect(document.body.textContent).toContain('确认添加')
|
||||
})
|
||||
|
||||
it('shows a recoverable API error without fake users', async () => {
|
||||
vi.mocked(listPlatformManagedUsers).mockRejectedValueOnce(new Error('Gateway unavailable'))
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.text()).toContain('Gateway unavailable')
|
||||
expect(wrapper.text()).toContain('重新加载')
|
||||
expect(wrapper.text()).not.toContain('zhangwei')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,377 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Pencil, Plus } from '@lucide/vue'
|
||||
import {
|
||||
changePlatformManagedUserStatus,
|
||||
createPlatformManagedUser,
|
||||
getPlatformUserOptions,
|
||||
listPlatformManagedUsers,
|
||||
resetPlatformManagedUserPassword,
|
||||
updatePlatformManagedUser,
|
||||
type PlatformManagedUser,
|
||||
type PlatformUserOptions,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const auth = useAuthStore()
|
||||
const users = ref<PlatformManagedUser[]>([])
|
||||
const options = ref<PlatformUserOptions>({ tenants: [], roles: [] })
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const editorOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const editingUser = ref<PlatformManagedUser | null>(null)
|
||||
const rowActionId = ref('')
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const filters = reactive({ keyword: '', tenantId: '', status: '' })
|
||||
|
||||
const emptyForm = () => ({
|
||||
username: '',
|
||||
displayName: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
tenantId: '' as string,
|
||||
roleIds: [] as string[],
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
status: 'ACTIVE' as 'ACTIVE' | 'DISABLED',
|
||||
resetPassword: false,
|
||||
})
|
||||
const form = reactive(emptyForm())
|
||||
|
||||
const canCreate = computed(() => access.can('platform:user:create') && access.can('platform:user:grant-role'))
|
||||
const canEdit = computed(() => access.can('platform:user:edit'))
|
||||
const canGrantRoles = computed(() => access.can('platform:user:grant-role'))
|
||||
const canChangeStatus = computed(() => access.can('platform:user:status'))
|
||||
const canResetPassword = computed(() => access.can('platform:user:reset-password'))
|
||||
const editorLabel = computed(() => editingUser.value ? `编辑用户 - ${editingUser.value.displayName}` : '新增用户')
|
||||
|
||||
useUnsavedWorkRegistration({
|
||||
key: 'platform-user-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission: computed(() => editingUser.value ? 'platform:user:edit' : 'platform:user:create'),
|
||||
})
|
||||
|
||||
const enabledTenants = computed(() => options.value.tenants.filter((tenant) =>
|
||||
tenant.status === 'ACTIVE' || String(tenant.id) === form.tenantId,
|
||||
))
|
||||
const availableRoles = computed(() => options.value.roles.filter((role) =>
|
||||
String(role.tenantId) === form.tenantId
|
||||
&& (role.status === 'ACTIVE' || form.roleIds.includes(String(role.id))),
|
||||
))
|
||||
|
||||
const formRules = computed<FormRules>(() => ({
|
||||
username: editingUser.value ? [] : [
|
||||
{ required: true, whitespace: true, message: '请输入用户名', trigger: 'blur' },
|
||||
{ pattern: /^[A-Za-z0-9_.@-]{4,64}$/, message: '用户名为 4-64 位字母、数字或 _ . @ -', trigger: 'blur' },
|
||||
],
|
||||
displayName: editingUser.value && !canEdit.value ? [] : [{ required: true, whitespace: true, message: '请输入姓名', trigger: 'blur' }],
|
||||
phone: editingUser.value && !canEdit.value ? [] : [
|
||||
{ required: true, message: '请输入手机号', trigger: 'blur' },
|
||||
{ pattern: /^1\d{10}$/, message: '请输入正确的 11 位手机号', trigger: 'blur' },
|
||||
],
|
||||
email: editingUser.value && !canEdit.value ? [] : [{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }],
|
||||
tenantId: editingUser.value && !canEdit.value ? [] : [{ required: true, message: '请选择所属租户', trigger: 'change' }],
|
||||
roleIds: editingUser.value && !canEdit.value ? [] : [{ type: 'array', required: true, min: 1, message: '请选择角色', trigger: 'change' }],
|
||||
password: editingUser.value && !form.resetPassword ? [] : [
|
||||
{ required: true, message: '请输入密码', trigger: 'blur' },
|
||||
{ pattern: /^(?=.*[A-Za-z])(?=.*\d).{8,64}$/, message: '密码为 8-64 位,且必须包含字母和数字', trigger: 'blur' },
|
||||
],
|
||||
confirmPassword: editingUser.value && !form.resetPassword ? [] : [
|
||||
{ required: true, message: '请再次输入密码', trigger: 'blur' },
|
||||
{ validator: (_rule, value, callback) => value === form.password ? callback() : callback(new Error('两次输入的密码不一致')), trigger: 'blur' },
|
||||
],
|
||||
}))
|
||||
|
||||
const filteredRows = computed(() => {
|
||||
const keyword = filters.keyword.trim().toLowerCase()
|
||||
return users.value.filter((item) => {
|
||||
const matchesKeyword = !keyword || [item.username, item.displayName, item.phone ?? '', item.email ?? '', item.tenantName, ...item.roleNames]
|
||||
.some((value) => value.toLowerCase().includes(keyword))
|
||||
return matchesKeyword
|
||||
&& (!filters.tenantId || String(item.tenantId) === filters.tenantId)
|
||||
&& (!filters.status || item.status === filters.status)
|
||||
})
|
||||
})
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
|
||||
const userColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 170, fixed: 'left', slotName: 'actions' },
|
||||
{ prop: 'username', label: '用户名', minWidth: 145 },
|
||||
{ prop: 'displayName', label: '姓名', minWidth: 130 },
|
||||
{ prop: 'tenantName', label: '所属租户', minWidth: 190 },
|
||||
{ key: 'roles', label: '角色', minWidth: 180, slotName: 'roles' },
|
||||
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
|
||||
{ key: 'lastLoginAt', label: '最后登录', minWidth: 170, slotName: 'lastLoginAt' },
|
||||
]
|
||||
|
||||
async function loadUsers() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const [userRecords, optionRecords] = await Promise.all([
|
||||
listPlatformManagedUsers(),
|
||||
getPlatformUserOptions(),
|
||||
])
|
||||
users.value = userRecords
|
||||
options.value = optionRecords
|
||||
} catch (error) {
|
||||
users.value = []
|
||||
loadError.value = getApiErrorDetails(error, '用户列表加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, emptyForm())
|
||||
const defaultTenant = options.value.tenants.find((tenant) => tenant.status === 'ACTIVE')
|
||||
form.tenantId = defaultTenant ? String(defaultTenant.id) : ''
|
||||
editingUser.value = null
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function openEdit(row: PlatformManagedUser) {
|
||||
editingUser.value = row
|
||||
Object.assign(form, {
|
||||
username: row.username,
|
||||
displayName: row.displayName,
|
||||
phone: row.phone ?? '',
|
||||
email: row.email ?? '',
|
||||
tenantId: String(row.tenantId),
|
||||
roleIds: row.roleIds.map(String),
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
status: row.status,
|
||||
resetPassword: false,
|
||||
})
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function handleTenantChange() {
|
||||
const validRoleIds = new Set(availableRoles.value.map((role) => String(role.id)))
|
||||
form.roleIds = form.roleIds.filter((roleId) => validRoleIds.has(roleId))
|
||||
}
|
||||
|
||||
function isCurrentUser(row: PlatformManagedUser | null) {
|
||||
if (!row) return false
|
||||
return String(row.userId) === auth.user?.id || String(row.authUserId) === auth.user?.id
|
||||
}
|
||||
|
||||
function cannotDisable(row: PlatformManagedUser | null) {
|
||||
return Boolean(row?.protectedAccount) || isCurrentUser(row)
|
||||
}
|
||||
|
||||
async function saveUser() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
saving.value = true
|
||||
try {
|
||||
if (!editingUser.value) {
|
||||
await createPlatformManagedUser({
|
||||
username: form.username.trim(),
|
||||
displayName: form.displayName.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim(),
|
||||
tenantId: form.tenantId,
|
||||
roleIds: form.roleIds,
|
||||
password: form.password,
|
||||
status: form.status,
|
||||
})
|
||||
ElMessage.success('用户添加成功')
|
||||
} else {
|
||||
const row = editingUser.value
|
||||
if (canEdit.value) {
|
||||
await updatePlatformManagedUser(row.membershipId, {
|
||||
displayName: form.displayName.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim(),
|
||||
tenantId: form.tenantId,
|
||||
roleIds: form.roleIds,
|
||||
})
|
||||
}
|
||||
if (canChangeStatus.value && form.status !== row.status) {
|
||||
await changePlatformManagedUserStatus(row.membershipId, form.status)
|
||||
}
|
||||
if (canResetPassword.value && form.resetPassword) {
|
||||
await resetPlatformManagedUserPassword(row.membershipId, form.password)
|
||||
}
|
||||
ElMessage.success(form.resetPassword ? '用户信息已更新,密码已重置' : '用户信息已更新')
|
||||
}
|
||||
editorOpen.value = false
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, editingUser.value ? '用户更新失败,请稍后重试' : '用户添加失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(row: PlatformManagedUser) {
|
||||
const targetStatus = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
|
||||
const targetLabel = targetStatus === 'ACTIVE' ? '启用' : '禁用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${targetLabel}用户“${row.displayName}”吗?`, `${targetLabel}用户`, {
|
||||
confirmButtonText: `确认${targetLabel}`,
|
||||
cancelButtonText: '取消',
|
||||
type: targetStatus === 'DISABLED' ? 'warning' : 'info',
|
||||
})
|
||||
rowActionId.value = String(row.membershipId)
|
||||
const updated = await changePlatformManagedUserStatus(row.membershipId, targetStatus)
|
||||
Object.assign(row, updated)
|
||||
ElMessage.success(`用户已${targetLabel}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, `用户${targetLabel}失败,请稍后重试`))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function formatLogin(value: string | null) {
|
||||
if (!value) return '—'
|
||||
return value.replace('T', ' ').slice(0, 16)
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
filters.keyword = ''
|
||||
filters.tenantId = ''
|
||||
filters.status = ''
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
onMounted(loadUsers)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<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="loadUsers">重新加载</el-button>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading">
|
||||
<div><h2>用户管理 <span class="secondary-text">共 {{ filteredRows.length }} 条</span></h2></div>
|
||||
<el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新增用户</el-button>
|
||||
</header>
|
||||
|
||||
<div class="query-toolbar">
|
||||
<el-input v-model="filters.keyword" clearable placeholder="用户名、姓名、手机号、租户或角色" @keyup.enter="page = 1" />
|
||||
<el-select v-model="filters.tenantId" clearable placeholder="全部租户" @change="page = 1">
|
||||
<el-option v-for="tenant in options.tenants" :key="tenant.id" :label="tenant.name" :value="String(tenant.id)" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.status" clearable placeholder="全部状态" @change="page = 1">
|
||||
<el-option label="正常" value="ACTIVE" />
|
||||
<el-option label="禁用" value="DISABLED" />
|
||||
</el-select>
|
||||
<el-button @click="resetFilters">重置</el-button>
|
||||
</div>
|
||||
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRows" :columns="userColumns"
|
||||
:loading="loading" :total="filteredRows.length" row-key="membershipId" empty-text="暂无用户数据">
|
||||
<template #actions="{ row }">
|
||||
<div class="table-actions">
|
||||
<el-button v-if="canEdit || canChangeStatus || canResetPassword" link type="primary" @click="openEdit(row as PlatformManagedUser)">
|
||||
<Pencil :size="15" />编辑
|
||||
</el-button>
|
||||
<el-button v-if="canChangeStatus" link :type="(row as PlatformManagedUser).status === 'ACTIVE' ? 'danger' : 'success'"
|
||||
:loading="rowActionId === String((row as PlatformManagedUser).membershipId)"
|
||||
:disabled="cannotDisable(row as PlatformManagedUser)"
|
||||
:title="(row as PlatformManagedUser).protectedAccount ? '系统管理员不能被禁用' : isCurrentUser(row as PlatformManagedUser) ? '不能禁用当前登录用户' : undefined"
|
||||
@click="toggleStatus(row as PlatformManagedUser)">
|
||||
{{ (row as PlatformManagedUser).status === 'ACTIVE' ? '禁用' : '启用' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<template #roles="{ row }">
|
||||
<div class="tag-list">
|
||||
<el-tag v-for="role in (row as PlatformManagedUser).roleNames" :key="role" effect="plain" size="small">{{ role }}</el-tag>
|
||||
<span v-if="!(row as PlatformManagedUser).roleNames.length" class="secondary-text">未分配</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #status="{ row }"><StatusBadge :status="(row as PlatformManagedUser).status === 'ACTIVE' ? '正常' : '禁用'" /></template>
|
||||
<template #lastLoginAt="{ row }">{{ formatLogin((row as PlatformManagedUser).lastLoginAt) }}</template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="editorOpen" :title="editorLabel" width="min(760px, calc(100vw - 32px))" :close-on-click-modal="false" destroy-on-close>
|
||||
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top">
|
||||
<div class="form-grid two-cols">
|
||||
<el-form-item label="用户名" prop="username" required>
|
||||
<el-input v-model="form.username" :disabled="Boolean(editingUser)" placeholder="登录用户名" maxlength="64" />
|
||||
</el-form-item>
|
||||
<el-form-item label="姓名" prop="displayName" required>
|
||||
<el-input v-model="form.displayName" :disabled="Boolean(editingUser) && !canEdit" placeholder="真实姓名" maxlength="64" />
|
||||
</el-form-item>
|
||||
<el-form-item label="手机号" prop="phone" required>
|
||||
<el-input v-model="form.phone" :disabled="Boolean(editingUser) && !canEdit" placeholder="手机号码" inputmode="tel" maxlength="11" />
|
||||
</el-form-item>
|
||||
<el-form-item label="邮箱" prop="email">
|
||||
<el-input v-model="form.email" :disabled="Boolean(editingUser) && !canEdit" placeholder="邮箱地址" inputmode="email" maxlength="128" />
|
||||
</el-form-item>
|
||||
<el-form-item label="所属租户" prop="tenantId" required>
|
||||
<el-select v-model="form.tenantId" :disabled="Boolean(editingUser) && (!canEdit || !canGrantRoles || editingUser?.protectedAccount)" placeholder="选择所属租户" @change="handleTenantChange">
|
||||
<el-option v-for="tenant in enabledTenants" :key="tenant.id" :label="tenant.name" :value="String(tenant.id)" :disabled="tenant.status !== 'ACTIVE'" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="角色" prop="roleIds" required>
|
||||
<el-select v-model="form.roleIds" multiple collapse-tags collapse-tags-tooltip
|
||||
:disabled="Boolean(editingUser) && (!canEdit || !canGrantRoles || editingUser?.protectedAccount)" placeholder="选择角色">
|
||||
<el-option v-for="role in availableRoles" :key="role.id" :label="role.name" :value="String(role.id)" :disabled="role.status !== 'ACTIVE'" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-select v-model="form.status" :disabled="Boolean(editingUser) && (!canChangeStatus || cannotDisable(editingUser))">
|
||||
<el-option label="正常" value="ACTIVE" />
|
||||
<el-option label="禁用" value="DISABLED" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="editingUser" label="最后登录">
|
||||
<el-input :model-value="formatLogin(editingUser.lastLoginAt)" disabled />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<template v-if="!editingUser || canResetPassword">
|
||||
<el-checkbox v-if="editingUser" v-model="form.resetPassword">同时重置密码</el-checkbox>
|
||||
<div v-if="!editingUser || form.resetPassword" class="form-grid two-cols password-fields">
|
||||
<el-form-item :label="editingUser ? '新密码' : '初始密码'" prop="password" required>
|
||||
<el-input v-model="form.password" type="password" show-password autocomplete="new-password" placeholder="8-64 位,包含字母和数字" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认密码" prop="confirmPassword" required>
|
||||
<el-input v-model="form.confirmPassword" type="password" show-password autocomplete="new-password" placeholder="再次输入密码" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</template>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button :disabled="saving" @click="editorOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveUser">{{ editingUser ? '保存修改' : '确认添加' }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-toolbar { display: grid; grid-template-columns: minmax(240px, 1fr) 220px 160px auto; gap: 12px; padding: 0 20px 16px; }
|
||||
.password-fields { margin-top: 16px; }
|
||||
@media (max-width: 720px) {
|
||||
.query-toolbar, .form-grid.two-cols { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { flushPromises, shallowMount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { listPlatformPermissions, type PlatformPermissionResource } from '@/modules/iam/api/platformIam'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import PermissionsView from './PermissionsView.vue'
|
||||
|
||||
vi.mock('@/modules/iam/api/platformIam', () => ({
|
||||
changePlatformPermissionStatus: vi.fn(),
|
||||
createPlatformPermission: vi.fn(),
|
||||
deletePlatformPermission: vi.fn(),
|
||||
listPlatformPermissions: vi.fn(),
|
||||
updatePlatformPermission: vi.fn(),
|
||||
}))
|
||||
|
||||
const permission: PlatformPermissionResource = {
|
||||
id: 5100010,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: 5100000,
|
||||
permissionCode: 'platform:customer:list',
|
||||
permissionName: '企业客户',
|
||||
routePath: '/customers',
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
}
|
||||
|
||||
function mountServerView() {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.isServerSession = true
|
||||
auth.permissions = ['platform:permission:list', 'platform:permission:create']
|
||||
return shallowMount(PermissionsView, {
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
directives: { loading: () => undefined },
|
||||
stubs: {
|
||||
'el-alert': { props: ['title'], template: '<div role="alert">{{ title }}<slot name="title" /></div>' },
|
||||
'el-input': true,
|
||||
'el-option': true,
|
||||
'el-select': true,
|
||||
'el-button': true,
|
||||
'el-table': true,
|
||||
'el-table-column': true,
|
||||
'el-input-number': true,
|
||||
'el-radio-group': true,
|
||||
'el-radio-button': true,
|
||||
'el-drawer': { template: '<section><slot /><slot name="footer" /></section>' },
|
||||
'el-form': { template: '<form><slot /></form>' },
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('PermissionsView IAM mode', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(listPlatformPermissions).mockReset()
|
||||
})
|
||||
|
||||
it('loads the platform permission resource tree from IAM', async () => {
|
||||
vi.mocked(listPlatformPermissions).mockResolvedValue([permission])
|
||||
|
||||
const wrapper = mountServerView()
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformPermissions).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.text()).toContain('权限资源树')
|
||||
expect(wrapper.text()).toContain('共 1 项')
|
||||
})
|
||||
|
||||
it('shows a recoverable state when the permission list fails', async () => {
|
||||
vi.mocked(listPlatformPermissions).mockRejectedValue(new Error('IAM unavailable'))
|
||||
|
||||
const wrapper = mountServerView()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.findAll('[role="alert"]').map((item) => item.text()).join(' ')).toContain('IAM unavailable')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,285 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Braces, FolderTree, Pencil, Plus, ShieldCheck, Trash2 } from '@lucide/vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import {
|
||||
changePlatformPermissionStatus,
|
||||
createPlatformPermission,
|
||||
deletePlatformPermission,
|
||||
listPlatformPermissions,
|
||||
updatePlatformPermission,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import type { Permission, PermissionType } from '@/modules/iam/types'
|
||||
import { buildPermissionTree, getDescendantIds, type PermissionTreeNode } from '@/modules/iam/utils/permissionTree'
|
||||
import { mapPlatformPermission } from '@/modules/iam/utils/platformPermission'
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const serverPermissions = ref<Permission[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const rowActionId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
type PermissionFilters = QueryModel & { keyword: string; type: string; status: string }
|
||||
const filters = ref<PermissionFilters>({ keyword: '', type: '', status: '' })
|
||||
const appliedFilters = ref<PermissionFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '权限名称、编码或路径' },
|
||||
{ key: 'type', type: 'select', placeholder: '全部类型', options: [{ label: '菜单', value: '菜单' }, { label: '按钮', value: '按钮' }] },
|
||||
{ key: 'status', type: 'select', placeholder: '全部状态', options: [{ label: '启用', value: '启用' }, { label: '停用', value: '停用' }] },
|
||||
]
|
||||
const expandedRowKeys = ref<string[]>([])
|
||||
const tableRenderKey = ref(0)
|
||||
const emptyForm = (): Permission => ({ id: '', parentId: null, name: '', code: '', type: '菜单', path: '', method: '-', status: '启用', sort: 10 })
|
||||
const form = reactive(emptyForm())
|
||||
const formRules = computed<FormRules>(() => ({
|
||||
name: [{ required: true, whitespace: true, message: '请输入权限名称', trigger: 'blur' }],
|
||||
code: [{ required: true, whitespace: true, message: '请输入权限编码', trigger: 'blur' }],
|
||||
type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
|
||||
parentId: form.type === '按钮' ? [{ required: true, message: '请选择上级菜单', trigger: 'change' }] : [],
|
||||
path: form.type === '菜单' ? [{ required: true, whitespace: true, message: '请输入菜单路由', trigger: 'blur' }] : [],
|
||||
sort: [{ required: true, type: 'number', message: '请输入显示排序', trigger: 'change' }],
|
||||
}))
|
||||
const editorLabel = computed(() => form.id ? '编辑权限' : '新增权限')
|
||||
const requiredPermission = computed(() => form.id ? 'platform:permission:edit' : 'platform:permission:create')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'permission-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission,
|
||||
})
|
||||
const availablePermissionTypes: PermissionType[] = ['菜单', '按钮']
|
||||
const permissions = computed(() => serverPermissions.value)
|
||||
const canCreate = computed(() => access.can('platform:permission:create'))
|
||||
const canEdit = computed(() => access.can('platform:permission:edit'))
|
||||
const canChangeStatus = computed(() => access.can('platform:permission:status'))
|
||||
const canDelete = computed(() => access.can('platform:permission:delete'))
|
||||
|
||||
function matches(item: Permission) {
|
||||
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
||||
return (!keyword || [item.name, item.code, item.path].some((value) => value.toLowerCase().includes(keyword))) && (!appliedFilters.value.type || item.type === appliedFilters.value.type) && (!appliedFilters.value.status || item.status === appliedFilters.value.status)
|
||||
}
|
||||
const treeRows = computed(() => buildPermissionTree(permissions.value, matches))
|
||||
const pagedTreeRows = computed(() => treeRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
const rootRowKeys = computed(() => treeRows.value.map((item) => item.id))
|
||||
const blockedParentIds = computed(() => new Set(
|
||||
form.id ? [form.id, ...getDescendantIds(permissions.value, form.id)] : [],
|
||||
))
|
||||
const parentOptions = computed(() => permissions.value.filter((item) => (
|
||||
item.type === '菜单' && !blockedParentIds.value.has(item.id)
|
||||
)))
|
||||
const permissionColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 280, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'name', label: '权限名称', minWidth: 260, slotName: 'name' },
|
||||
{ key: 'code', label: '权限编码', minWidth: 220, slotName: 'code' },
|
||||
{ prop: 'type', label: '类型', width: 80 },
|
||||
{ key: 'endpoint', label: '路由 / 接口', minWidth: 260, slotName: 'endpoint' },
|
||||
{ prop: 'sort', label: '排序', width: 72, align: 'right' },
|
||||
{ key: 'status', label: '状态', width: 88, slotName: 'status' },
|
||||
]
|
||||
|
||||
async function loadPermissions() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
serverPermissions.value = []
|
||||
try {
|
||||
serverPermissions.value = (await listPlatformPermissions()).map(mapPlatformPermission)
|
||||
expandedRowKeys.value = rootRowKeys.value
|
||||
tableRenderKey.value += 1
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '权限资源加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function applyFilters() {
|
||||
appliedFilters.value = { ...filters.value }
|
||||
page.value = 1
|
||||
void loadPermissions()
|
||||
}
|
||||
|
||||
function collectDescendantIds(nodes: PermissionTreeNode[], ids: string[] = []) {
|
||||
nodes.forEach((node) => {
|
||||
ids.push(node.id)
|
||||
if (node.children) collectDescendantIds(node.children, ids)
|
||||
})
|
||||
return ids
|
||||
}
|
||||
|
||||
function permissionSummary(row: PermissionTreeNode) {
|
||||
const descendants = collectDescendantIds(row.children ?? [])
|
||||
.map((id) => permissions.value.find((item) => item.id === id))
|
||||
.filter((item): item is Permission => Boolean(item))
|
||||
const menuCount = descendants.filter((item) => item.type === '菜单').length
|
||||
const actionCount = descendants.filter((item) => ['按钮', '接口'].includes(item.type)).length
|
||||
if (menuCount === 0 && actionCount === 0) return '无下级权限'
|
||||
return [menuCount ? `${menuCount} 个菜单` : '', actionCount ? `${actionCount} 项操作` : ''].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
function expandAllRows() {
|
||||
expandedRowKeys.value = collectDescendantIds(treeRows.value)
|
||||
tableRenderKey.value += 1
|
||||
}
|
||||
|
||||
function collapseActionRows() {
|
||||
expandedRowKeys.value = rootRowKeys.value
|
||||
tableRenderKey.value += 1
|
||||
}
|
||||
|
||||
function openCreate(parentId: string | null = null) {
|
||||
Object.assign(form, emptyForm(), { parentId })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
function openEdit(row: Permission) {
|
||||
if (!canEdit.value || row.builtIn) return
|
||||
Object.assign(form, { ...row })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
function handleTypeChange() {
|
||||
if (form.type === '按钮') form.path = ''
|
||||
nextTick(() => formRef.value?.clearValidate(['parentId', 'path']))
|
||||
}
|
||||
async function savePermission() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
if (permissions.value.some((item) => item.code.toLowerCase() === form.code.toLowerCase() && item.id !== form.id)) { ElMessage.error('权限编码已经存在'); return }
|
||||
saving.value = true
|
||||
try {
|
||||
if (form.id) {
|
||||
const updated = await updatePlatformPermission(form.id, {
|
||||
name: form.name.trim(),
|
||||
parentId: form.parentId,
|
||||
routePath: form.type === '菜单' ? form.path.trim() : null,
|
||||
httpMethod: form.method === '-' ? null : form.method,
|
||||
sortNo: form.sort,
|
||||
})
|
||||
const index = serverPermissions.value.findIndex((item) => item.id === form.id)
|
||||
if (index >= 0) serverPermissions.value[index] = mapPlatformPermission(updated)
|
||||
ElMessage.success('权限资源已更新')
|
||||
} else {
|
||||
const created = await createPlatformPermission({
|
||||
type: form.type === '按钮' ? 'BUTTON' : 'MENU',
|
||||
code: form.code.trim(),
|
||||
name: form.name.trim(),
|
||||
parentId: form.parentId || '0',
|
||||
routePath: form.type === '菜单' ? form.path.trim() : null,
|
||||
httpMethod: null,
|
||||
sortNo: form.sort,
|
||||
})
|
||||
serverPermissions.value.push(mapPlatformPermission(created))
|
||||
ElMessage.success('权限资源已创建')
|
||||
}
|
||||
editorOpen.value = false
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, form.id ? '权限资源更新失败,请稍后重试' : '权限资源创建失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
async function toggleStatus(row: Permission) {
|
||||
if (row.builtIn) return
|
||||
const target = row.status === '启用' ? '停用' : '启用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${target}权限“${row.name}”吗?`, '权限状态', { confirmButtonText: '确认', cancelButtonText: '取消' })
|
||||
rowActionId.value = row.id
|
||||
const updated = await changePlatformPermissionStatus(row.id, target === '启用' ? 'ACTIVE' : 'DISABLED')
|
||||
Object.assign(row, mapPlatformPermission(updated))
|
||||
ElMessage.success(`权限已${target}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '权限状态更新失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function removePermission(row: Permission) {
|
||||
if (row.builtIn) return
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除权限“${row.name}”吗?删除前需确保没有下级资源且未分配给角色。`, '删除权限', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
|
||||
rowActionId.value = row.id
|
||||
await deletePlatformPermission(row.id)
|
||||
await loadPermissions()
|
||||
ElMessage.success('权限资源已删除')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '权限资源删除失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
function typeClass(type: PermissionType) { return { '目录': 'directory', '菜单': 'menu', '按钮': 'action', '接口': 'api' }[type] }
|
||||
|
||||
onMounted(loadPermissions)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<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="loadPermissions">重新加载</el-button></template></el-alert>
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="权限筛选" :fields="queryFields" @search="applyFilters" />
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading"><div><h2>权限资源树 <span class="secondary-text">共 {{ permissions.length }} 项</span></h2><p>默认展示目录与菜单,展开菜单后查看按钮权限;接口权限将在服务端契约确定后补充。</p></div><div class="permission-tree-heading-actions"><div class="permission-tree-tools"><div class="legend-list"><span><i class="is-menu" />目录 / 菜单</span><span><i class="is-action" />操作</span><span><i class="is-api" />接口预留</span></div><div class="tree-view-actions"><el-button link type="primary" @click="expandAllRows">展开全部</el-button><el-button link @click="collapseActionRows">收起操作权限</el-button></div></div><el-button v-if="canCreate" type="primary" @click="openCreate(null)"><Plus :size="16" />新增权限</el-button></div></header>
|
||||
<DataTable :key="tableRenderKey" v-model:page="page" v-model:page-size="pageSize" :data="pagedTreeRows" :columns="permissionColumns" :loading="loading" :total="treeRows.length" row-key="id" :expand-row-keys="expandedRowKeys" :tree-props="{ children: 'children' }" empty-text="没有符合条件的权限资源">
|
||||
<template #actions="{ row }"><div v-if="canCreate || canEdit || canChangeStatus || canDelete" class="table-actions"><el-button v-if="canCreate && (row as Permission).type === '菜单'" link type="primary" @click="openCreate((row as Permission).id)"><Plus :size="15" />添加下级</el-button><el-button v-if="canEdit" link type="primary" :disabled="(row as Permission).builtIn || rowActionId === (row as Permission).id" @click="openEdit(row as Permission)"><Pencil :size="15" />编辑</el-button><el-button v-if="canChangeStatus" link :type="(row as Permission).status === '启用' ? 'danger' : 'success'" :loading="rowActionId === (row as Permission).id" :disabled="(row as Permission).builtIn" @click="toggleStatus(row as Permission)">{{ (row as Permission).status === '启用' ? '停用' : '启用' }}</el-button><el-button v-if="canDelete" link type="danger" :disabled="(row as Permission).builtIn || rowActionId === (row as Permission).id" @click="removePermission(row as Permission)"><Trash2 :size="15" />删除</el-button><span v-if="(row as Permission).builtIn" class="secondary-text">系统内置</span></div><span v-else class="secondary-text">仅查看</span></template>
|
||||
<template #name="{ row }"><div class="permission-name"><span :class="`is-${typeClass((row as Permission).type)}`"><FolderTree v-if="(row as Permission).type === '目录' || (row as Permission).type === '菜单'" :size="16" /><ShieldCheck v-else-if="(row as Permission).type === '按钮'" :size="16" /><Braces v-else :size="16" /></span><div><strong>{{ (row as Permission).name }}</strong><small v-if="(row as PermissionTreeNode).children?.length">{{ permissionSummary(row as PermissionTreeNode) }}</small></div></div></template>
|
||||
<template #code="{ row }"><code class="code-value">{{ (row as Permission).code }}</code></template>
|
||||
<template #endpoint="{ row }"><div class="endpoint-cell"><span v-if="(row as Permission).method !== '-'">{{ (row as Permission).method }}</span><code>{{ (row as Permission).path || '-' }}</code></div></template>
|
||||
<template #status="{ row }"><StatusBadge :status="(row as Permission).status" /></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="form.id ? '编辑权限资源' : '新增权限资源'" size="600px" class="business-drawer editor-drawer" :modal="false" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top" class="drawer-form">
|
||||
<div class="form-section">
|
||||
<h3>资源定义</h3>
|
||||
<div class="form-grid two-cols">
|
||||
<el-form-item label="权限名称" prop="name" required><el-input v-model="form.name" placeholder="用户可理解的中文名称" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="权限编码" prop="code" required><el-input v-model="form.code" :disabled="Boolean(form.id)" placeholder="如:platform:customer:list" maxlength="128" /></el-form-item>
|
||||
<el-form-item label="资源类型" prop="type" required><el-select v-model="form.type" :disabled="Boolean(form.id)" @change="handleTypeChange"><el-option v-for="item in availablePermissionTypes" :key="item" :label="item" :value="item" /></el-select></el-form-item>
|
||||
<el-form-item label="上级资源" prop="parentId" :required="form.type === '按钮'"><el-select v-model="form.parentId" clearable placeholder="作为一级资源"><el-option v-for="item in parentOptions" :key="item.id" :label="`${item.name} (${item.code})`" :value="item.id" /></el-select></el-form-item>
|
||||
<el-form-item v-if="form.type === '菜单'" label="路由路径" prop="path" required><el-input v-model="form.path" placeholder="如:/customers" /></el-form-item>
|
||||
<el-form-item label="显示排序" prop="sort" required><el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" /></el-form-item>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-callout"><Braces :size="18" /><div><strong>权限编码约定</strong><p>使用稳定的“业务域:资源:动作”编码;一期真实资源只创建菜单和按钮,接口鉴权由服务端实现。</p></div></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button v-if="form.id ? canEdit : canCreate" type="primary" :loading="saving" @click="savePermission">{{ form.id ? '保存修改' : '保存权限' }}</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.permission-tree-tools { display: flex; align-items: center; gap: 16px; }
|
||||
.permission-tree-heading-actions { display: flex; align-items: center; gap: 12px; }
|
||||
.tree-view-actions { display: flex; align-items: center; gap: 4px; white-space: nowrap; }
|
||||
.tree-view-actions .el-button + .el-button { margin-left: 0; }
|
||||
.permission-name > div { display: flex; min-width: 0; flex-direction: column; gap: 2px; }
|
||||
.permission-name small { color: var(--cc-muted); font-size: 11px; line-height: 1.35; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.permission-tree-heading-actions { width: 100%; align-items: flex-start; flex-direction: column; gap: 8px; }
|
||||
.permission-tree-tools { width: 100%; align-items: flex-start; flex-direction: column; gap: 8px; }
|
||||
.permission-tree-heading-actions > .el-button { min-height: 40px; }
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.tree-view-actions { width: 100%; justify-content: flex-start; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { flushPromises, shallowMount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPlatformRole, listPlatformInternalUsers, listPlatformPermissions, listPlatformRoles, type PlatformRoleResource } from '@/modules/iam/api/platformIam'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import RolesView from './RolesView.vue'
|
||||
|
||||
vi.mock('@/modules/iam/api/platformIam', () => ({
|
||||
createPlatformRole: vi.fn(),
|
||||
listPlatformInternalUsers: vi.fn(),
|
||||
listPlatformPermissions: vi.fn(),
|
||||
listPlatformRoles: vi.fn(),
|
||||
updatePlatformRole: vi.fn(),
|
||||
changePlatformRoleStatus: vi.fn(),
|
||||
deletePlatformRole: vi.fn(),
|
||||
replacePlatformRolePermissions: vi.fn(),
|
||||
}))
|
||||
|
||||
const platformRole: PlatformRoleResource = {
|
||||
id: 4000002,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
roleType: 'SYSTEM',
|
||||
status: 'ACTIVE',
|
||||
description: '企业资料与入驻审核',
|
||||
}
|
||||
|
||||
function mountView(pinia = createPinia()) {
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
if (auth.permissions.length === 0) auth.permissions = ['platform:role:list', 'platform:role:create', 'platform:role:grant']
|
||||
return shallowMount(RolesView, {
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
directives: { loading: () => undefined },
|
||||
stubs: {
|
||||
'el-alert': { props: ['title'], template: '<div role="alert">{{ title }}<slot name="title" /></div>' },
|
||||
'el-input': true,
|
||||
'el-option': true,
|
||||
'el-select': true,
|
||||
'el-button': true,
|
||||
'el-table': true,
|
||||
'el-table-column': true,
|
||||
'el-tag': true,
|
||||
'el-radio-group': true,
|
||||
'el-radio-button': true,
|
||||
'el-drawer': {
|
||||
props: ['modelValue'],
|
||||
template: '<section><slot /><slot name="footer" /></section>',
|
||||
},
|
||||
'el-form': { template: '<form><slot /></form>' },
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
'el-tree': {
|
||||
props: { checkStrictly: Boolean },
|
||||
template: '<div data-testid="permission-tree" :data-check-strictly="String(checkStrictly)" />',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('RolesView', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(listPlatformRoles).mockReset()
|
||||
vi.mocked(listPlatformPermissions).mockReset()
|
||||
vi.mocked(listPlatformInternalUsers).mockReset()
|
||||
vi.mocked(listPlatformPermissions).mockResolvedValue([])
|
||||
vi.mocked(listPlatformInternalUsers).mockResolvedValue([])
|
||||
vi.mocked(createPlatformRole).mockReset()
|
||||
})
|
||||
|
||||
it('keeps directory, menu, and action permissions independently checkable', () => {
|
||||
const wrapper = mountView()
|
||||
|
||||
expect(wrapper.get('[data-testid="permission-tree"]').attributes('data-check-strictly')).toBe('true')
|
||||
})
|
||||
|
||||
it('loads platform roles from IAM for a server session', async () => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.isServerSession = true
|
||||
auth.permissions = ['platform:role:list', 'platform:role:create']
|
||||
vi.mocked(listPlatformRoles).mockResolvedValue([platformRole])
|
||||
|
||||
const wrapper = mountView(pinia)
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformRoles).toHaveBeenCalledTimes(1)
|
||||
expect(listPlatformInternalUsers).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.text()).toContain('角色负责聚合菜单、操作和数据范围,内部用户可分配多个角色')
|
||||
expect(wrapper.find('[data-testid="permission-tree"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a failed IAM role list recoverable', async () => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.isServerSession = true
|
||||
auth.permissions = ['platform:role:list']
|
||||
vi.mocked(listPlatformRoles).mockRejectedValue(new Error('IAM unavailable'))
|
||||
|
||||
const wrapper = mountView(pinia)
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.findAll('[role="alert"]').map((item) => item.text()).join(' ')).toContain('IAM unavailable')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,257 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Pencil, Plus, ShieldCheck, Trash2 } from '@lucide/vue'
|
||||
import {
|
||||
changePlatformRoleStatus,
|
||||
createPlatformRole,
|
||||
deletePlatformRole,
|
||||
listPlatformInternalUsers,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
replacePlatformRolePermissions,
|
||||
updatePlatformRole,
|
||||
type PlatformRoleResource,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import type { Permission, Role } from '@/modules/iam/types'
|
||||
import { buildPermissionTree, summarizePermissionSelection } from '@/modules/iam/utils/permissionTree'
|
||||
import { mapPlatformPermission } from '@/modules/iam/utils/platformPermission'
|
||||
|
||||
interface TreeController {
|
||||
getCheckedKeys: (leafOnly?: boolean) => Array<string | number>
|
||||
getHalfCheckedKeys: () => Array<string | number>
|
||||
setCheckedKeys: (keys: string[]) => void
|
||||
}
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
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 page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
type RoleFilters = QueryModel & { keyword: string; status: string }
|
||||
const filters = ref<RoleFilters>({ keyword: '', status: '' })
|
||||
const appliedFilters = ref<RoleFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '角色名称、编码或描述' },
|
||||
{ key: 'status', type: 'select', placeholder: '全部状态', options: [{ label: '启用', value: '启用' }, { label: '停用', value: '停用' }] },
|
||||
]
|
||||
const emptyForm = (): Omit<Role, 'userCount'> => ({ id: '', name: '', code: '', description: '', dataScope: '本部门数据', status: '启用', permissionIds: [], builtIn: false })
|
||||
const form = reactive(emptyForm())
|
||||
const formRules: FormRules = {
|
||||
name: [{ required: true, whitespace: true, message: '请输入角色名称', trigger: 'blur' }],
|
||||
code: [{ required: true, whitespace: true, message: '请输入角色编码', trigger: 'blur' }],
|
||||
}
|
||||
const editorLabel = computed(() => form.id ? '配置角色' : '新增角色')
|
||||
const canEdit = computed(() => access.can('platform:role:edit'))
|
||||
const canGrant = computed(() => access.can('platform:role:grant'))
|
||||
const requiredPermission = computed(() => form.id && canEdit.value ? 'platform:role:edit' : form.id ? 'platform:role:grant' : 'platform:role:create')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'role-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission,
|
||||
})
|
||||
const roles = computed(() => serverRoles.value)
|
||||
const canCreate = computed(() => access.can('platform:role:create'))
|
||||
const filteredRows = computed(() => roles.value.filter((item) => {
|
||||
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
||||
return (!keyword || [item.name, item.code, item.description].some((value) => value.toLowerCase().includes(keyword))) && (!appliedFilters.value.status || item.status === appliedFilters.value.status)
|
||||
}))
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
const roleColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 235, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'role', label: '角色', minWidth: 210, slotName: 'role' },
|
||||
{ prop: 'description', label: '说明', minWidth: 240, showOverflowTooltip: true },
|
||||
{ key: 'permissionSummary', label: '授权范围', minWidth: 170, slotName: 'permissionSummary' },
|
||||
{ prop: 'userCount', label: '用户数', width: 86, align: 'right' },
|
||||
{ key: 'roleType', label: '类型', width: 95, slotName: 'roleType' },
|
||||
{ key: 'status', label: '状态', width: 88, slotName: 'status' },
|
||||
]
|
||||
const availablePermissions = computed(() => serverPermissions.value)
|
||||
const permissionTree = computed(() => buildPermissionTree(availablePermissions.value))
|
||||
|
||||
function applyFilters() {
|
||||
appliedFilters.value = { ...filters.value }
|
||||
page.value = 1
|
||||
void loadRoles()
|
||||
}
|
||||
|
||||
function mapPlatformRole(role: PlatformRoleResource, userCount = 0): Role {
|
||||
return {
|
||||
id: String(role.id),
|
||||
name: role.roleName,
|
||||
code: role.roleCode,
|
||||
description: role.description ?? '暂无角色说明',
|
||||
userCount,
|
||||
dataScope: '全部数据',
|
||||
status: role.status === 'ACTIVE' ? '启用' : '停用',
|
||||
permissionIds: (role.permissionIds ?? []).map(String),
|
||||
builtIn: role.roleType === 'SYSTEM',
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRoles() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
serverRoles.value = []
|
||||
serverPermissions.value = []
|
||||
try {
|
||||
const [roleRecords, permissionRecords, memberRecords] = await Promise.all([
|
||||
listPlatformRoles(),
|
||||
listPlatformPermissions(),
|
||||
listPlatformInternalUsers(),
|
||||
])
|
||||
const roleMemberCounts = new Map<string, number>()
|
||||
for (const member of memberRecords) {
|
||||
for (const roleId of member.roleIds) {
|
||||
const key = String(roleId)
|
||||
roleMemberCounts.set(key, (roleMemberCounts.get(key) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
serverPermissions.value = permissionRecords.map(mapPlatformPermission)
|
||||
serverRoles.value = roleRecords.map((role) => mapPlatformRole(role, roleMemberCounts.get(String(role.id)) ?? 0))
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '平台角色列表加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, emptyForm())
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => { formRef.value?.clearValidate(); treeRef.value?.setCheckedKeys([]) })
|
||||
}
|
||||
function openEdit(row: Role) {
|
||||
if (!canEdit.value && !canGrant.value) return
|
||||
Object.assign(form, { ...row, permissionIds: [...row.permissionIds] })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => { formRef.value?.clearValidate(); treeRef.value?.setCheckedKeys([...row.permissionIds]) })
|
||||
}
|
||||
|
||||
function selectedPermissionIds() {
|
||||
const checked = treeRef.value?.getCheckedKeys(false).map(String) || []
|
||||
const halfChecked = treeRef.value?.getHalfCheckedKeys().map(String) || []
|
||||
return [...new Set([...checked, ...halfChecked])]
|
||||
}
|
||||
|
||||
function syncPermissionIds() {
|
||||
form.permissionIds = selectedPermissionIds()
|
||||
}
|
||||
|
||||
async function saveRole() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
const normalizedCode = form.code.trim().toUpperCase()
|
||||
const duplicate = roles.value.some((item) => item.code.toLowerCase() === normalizedCode.toLowerCase() && item.id !== form.id)
|
||||
if (duplicate) { ElMessage.error('角色编码已经存在'); return }
|
||||
saving.value = true
|
||||
try {
|
||||
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(form.id ? '角色已更新' : '角色已创建')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '角色保存失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRole(row: Role) {
|
||||
if (row.builtIn) { ElMessage.warning('系统内置角色不能删除'); return }
|
||||
if (row.userCount > 0) { ElMessage.warning('请先移除该角色下的用户'); return }
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除角色“${row.name}”吗?`, '删除角色', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
|
||||
rowActionId.value = row.id
|
||||
await deletePlatformRole(row.id)
|
||||
serverRoles.value = serverRoles.value.filter((item) => item.id !== row.id)
|
||||
ElMessage.success('角色已删除')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '角色删除失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(row: Role) {
|
||||
if (row.builtIn) { ElMessage.warning('系统内置角色不能停用'); return }
|
||||
const target = row.status === '启用' ? '停用' : '启用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${target}角色“${row.name}”吗?`, '角色状态', { confirmButtonText: '确认', cancelButtonText: '取消' })
|
||||
rowActionId.value = row.id
|
||||
const updated = await changePlatformRoleStatus(row.id, target === '启用' ? 'ACTIVE' : 'DISABLED')
|
||||
Object.assign(row, mapPlatformRole(updated))
|
||||
ElMessage.success(`角色已${target}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '角色状态更新失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function permissionSummary(row: Role) {
|
||||
const { menuCount, actionCount } = summarizePermissionSelection(availablePermissions.value, row.permissionIds)
|
||||
return `${menuCount} 菜单 · ${actionCount} 操作`
|
||||
}
|
||||
|
||||
onMounted(loadRoles)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<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>
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="角色筛选" :fields="queryFields" @search="applyFilters" />
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading"><div><h2>角色与授权 <span class="secondary-text">共 {{ filteredRows.length }} 条</span></h2><p>角色负责聚合菜单、操作和数据范围,内部用户可分配多个角色。</p></div><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新增角色</el-button></header>
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRows" :columns="roleColumns" :loading="loading" :total="filteredRows.length" row-key="id" empty-text="没有符合条件的角色">
|
||||
<template #actions="{ row }"><div v-if="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 as Role).id || (row as Role).builtIn" @click="openEdit(row as Role)"><Pencil :size="15" />配置</el-button><el-button v-if="access.can('platform:role:status')" link :type="(row as Role).status === '启用' ? 'danger' : 'success'" :loading="rowActionId === (row as Role).id" :disabled="(row as Role).builtIn" @click="toggleStatus(row as Role)">{{ (row as Role).status === '启用' ? '停用' : '启用' }}</el-button><el-button v-if="access.can('platform:role:delete')" link type="danger" :disabled="(row as Role).builtIn || (row as Role).userCount > 0 || rowActionId === (row as Role).id" @click="removeRole(row as Role)"><Trash2 :size="15" />删除</el-button></div><span v-else class="secondary-text">仅查看</span></template>
|
||||
<template #role="{ row }"><div class="role-cell"><span><ShieldCheck :size="18" /></span><div><strong>{{ (row as Role).name }}</strong><small>{{ (row as Role).code }}</small></div></div></template>
|
||||
<template #permissionSummary="{ row }"><div class="primary-cell"><strong>{{ permissionSummary(row as Role) }}</strong><span>平台 IAM 权限</span></div></template>
|
||||
<template #roleType="{ row }"><el-tag :type="(row as Role).builtIn ? 'warning' : 'info'" effect="plain" size="small">{{ (row as Role).builtIn ? '系统内置' : '自定义' }}</el-tag></template>
|
||||
<template #status="{ row }"><StatusBadge :status="(row as Role).status" /></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="form.id ? '配置角色' : '新增角色'" size="760px" class="business-drawer editor-drawer" :modal="false" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top" class="drawer-form">
|
||||
<div class="form-section"><h3>基本信息</h3><div class="form-grid two-cols"><el-form-item label="角色名称" prop="name" required><el-input v-model="form.name" :disabled="Boolean(form.id) && !canEdit" placeholder="如:订单运营专员" maxlength="64" /></el-form-item><el-form-item label="角色编码" prop="code" required><el-input v-model="form.code" :disabled="Boolean(form.id)" placeholder="如:ORDER_OPERATOR" maxlength="64" /></el-form-item></div><el-form-item label="角色说明"><el-input v-model="form.description" :disabled="Boolean(form.id) && !canEdit" type="textarea" :rows="2" placeholder="说明该角色的工作范围" maxlength="200" show-word-limit /></el-form-item></div>
|
||||
<div v-if="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 :disabled="saving" @click="editorOpen = false">取消</el-button><el-button v-if="form.id ? canEdit || canGrant : canCreate" type="primary" :loading="saving" @click="saveRole">保存角色</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const iamRoutes = [
|
||||
{
|
||||
path: 'system/users',
|
||||
name: 'users',
|
||||
component: () => import('@/modules/iam/pages/InternalUsersView.vue'),
|
||||
meta: { title: '用户管理', description: '统一管理平台和企业租户用户、状态及角色', permission: 'platform:user:list' },
|
||||
},
|
||||
{
|
||||
path: 'system/roles',
|
||||
name: 'roles',
|
||||
component: () => import('@/modules/iam/pages/RolesView.vue'),
|
||||
meta: { title: '角色管理', description: '维护平台角色并配置菜单及操作权限', permission: 'platform:role:list' },
|
||||
},
|
||||
{
|
||||
path: 'system/permissions',
|
||||
name: 'permissions',
|
||||
component: () => import('@/modules/iam/pages/PermissionsView.vue'),
|
||||
meta: { title: '菜单权限', description: '维护菜单、页面、按钮和接口权限编码', permission: 'platform:permission:list' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,42 @@
|
||||
export type RecordStatus = '正常' | '停用'
|
||||
export type RoleStatus = '启用' | '停用'
|
||||
export type PermissionType = '目录' | '菜单' | '按钮' | '接口'
|
||||
export type DataScope = '全部数据' | '本部门数据' | '本人数据' | '自定义'
|
||||
|
||||
export interface InternalUser {
|
||||
id: string
|
||||
account: string
|
||||
name: string
|
||||
department: string
|
||||
phone: string
|
||||
email: string
|
||||
roleIds: string[]
|
||||
status: RecordStatus
|
||||
lastLogin: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: string
|
||||
name: string
|
||||
code: string
|
||||
description: string
|
||||
userCount: number
|
||||
dataScope: DataScope
|
||||
status: RoleStatus
|
||||
permissionIds: string[]
|
||||
builtIn?: boolean
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
id: string
|
||||
parentId: string | null
|
||||
name: string
|
||||
code: string
|
||||
type: PermissionType
|
||||
path: string
|
||||
method: string
|
||||
status: RoleStatus
|
||||
sort: number
|
||||
builtIn?: boolean
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Permission } from '@/modules/iam/types'
|
||||
import { buildPermissionTree, getDescendantIds, summarizePermissionSelection } from '@/modules/iam/utils/permissionTree'
|
||||
|
||||
const permissions: Permission[] = [
|
||||
{ id: 'action-b', parentId: 'menu', name: '操作 B', code: 'demo:b', type: '按钮', path: '', method: '-', status: '启用', sort: 20 },
|
||||
{ id: 'menu', parentId: 'directory', name: '页面', code: 'demo:list', type: '菜单', path: '/demo', method: '-', status: '启用', sort: 10 },
|
||||
{ id: 'directory', parentId: null, name: '目录', code: 'demo', type: '目录', path: '', method: '-', status: '启用', sort: 10 },
|
||||
{ id: 'action-a', parentId: 'menu', name: '操作 A', code: 'demo:a', type: '按钮', path: '', method: '-', status: '启用', sort: 10 },
|
||||
]
|
||||
|
||||
describe('permissionTree', () => {
|
||||
it('builds arbitrary-depth trees and sorts siblings', () => {
|
||||
const tree = buildPermissionTree(permissions)
|
||||
|
||||
expect(tree[0]?.children?.[0]?.children?.map((node) => node.id)).toEqual(['action-a', 'action-b'])
|
||||
})
|
||||
|
||||
it('keeps the ancestor chain when a deep descendant matches', () => {
|
||||
const tree = buildPermissionTree(permissions, (item) => item.code === 'demo:a')
|
||||
|
||||
expect(tree.map((node) => node.id)).toEqual(['directory'])
|
||||
expect(tree[0]?.children?.map((node) => node.id)).toEqual(['menu'])
|
||||
expect(tree[0]?.children?.[0]?.children?.map((node) => node.id)).toEqual(['action-a'])
|
||||
})
|
||||
|
||||
it('stops building a branch when malformed data repeats an ancestor id', () => {
|
||||
const malformed = [
|
||||
...permissions,
|
||||
{ id: 'loop', parentId: null, name: '循环目录', code: 'loop', type: '目录', path: '', method: '-', status: '启用', sort: 20 },
|
||||
{ id: 'loop', parentId: 'loop', name: '循环下级', code: 'loop:child', type: '目录', path: '', method: '-', status: '启用', sort: 10 },
|
||||
] satisfies Permission[]
|
||||
|
||||
const tree = buildPermissionTree(malformed)
|
||||
|
||||
expect(tree.find((node) => node.code === 'loop')).not.toHaveProperty('children')
|
||||
})
|
||||
|
||||
it('collects descendants once when malformed data contains a cycle', () => {
|
||||
const malformed = [
|
||||
...permissions,
|
||||
{ id: 'cycle-a', parentId: 'cycle-b', name: 'A', code: 'cycle:a', type: '目录', path: '', method: '-', status: '启用', sort: 1 },
|
||||
{ id: 'cycle-b', parentId: 'cycle-a', name: 'B', code: 'cycle:b', type: '目录', path: '', method: '-', status: '启用', sort: 2 },
|
||||
] satisfies Permission[]
|
||||
|
||||
expect(getDescendantIds(malformed, 'cycle-a')).toEqual(['cycle-b'])
|
||||
})
|
||||
|
||||
it('counts page menus and operations without treating directories as menus', () => {
|
||||
expect(summarizePermissionSelection(permissions, ['directory', 'menu', 'action-a'])).toEqual({
|
||||
menuCount: 1,
|
||||
actionCount: 1,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { Permission } from '@/modules/iam/types'
|
||||
|
||||
export type PermissionTreeNode = Permission & { children?: PermissionTreeNode[] }
|
||||
export type PermissionMatcher = (permission: Permission) => boolean
|
||||
|
||||
function groupByParent(permissions: Permission[]) {
|
||||
const childrenByParent = new Map<string | null, Permission[]>()
|
||||
|
||||
permissions.forEach((permission) => {
|
||||
const siblings = childrenByParent.get(permission.parentId) ?? []
|
||||
siblings.push(permission)
|
||||
childrenByParent.set(permission.parentId, siblings)
|
||||
})
|
||||
|
||||
childrenByParent.forEach((siblings) => {
|
||||
siblings.sort((left, right) => left.sort - right.sort)
|
||||
})
|
||||
|
||||
return childrenByParent
|
||||
}
|
||||
|
||||
export function buildPermissionTree(
|
||||
permissions: Permission[],
|
||||
matches: PermissionMatcher = () => true,
|
||||
): PermissionTreeNode[] {
|
||||
const childrenByParent = groupByParent(permissions)
|
||||
|
||||
function buildNode(permission: Permission, ancestors: Set<string>): PermissionTreeNode | null {
|
||||
if (ancestors.has(permission.id)) return null
|
||||
|
||||
const nextAncestors = new Set(ancestors).add(permission.id)
|
||||
const children = (childrenByParent.get(permission.id) ?? [])
|
||||
.map((child) => buildNode(child, nextAncestors))
|
||||
.filter((child): child is PermissionTreeNode => child !== null)
|
||||
|
||||
if (!matches(permission) && children.length === 0) return null
|
||||
|
||||
return {
|
||||
...permission,
|
||||
...(children.length ? { children } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
return (childrenByParent.get(null) ?? [])
|
||||
.map((permission) => buildNode(permission, new Set()))
|
||||
.filter((node): node is PermissionTreeNode => node !== null)
|
||||
}
|
||||
|
||||
export function getDescendantIds(permissions: Permission[], permissionId: string): string[] {
|
||||
const childrenByParent = groupByParent(permissions)
|
||||
const visited = new Set([permissionId])
|
||||
const descendants: string[] = []
|
||||
const queue = [...(childrenByParent.get(permissionId) ?? [])]
|
||||
|
||||
while (queue.length) {
|
||||
const current = queue.shift()
|
||||
if (!current || visited.has(current.id)) continue
|
||||
|
||||
visited.add(current.id)
|
||||
descendants.push(current.id)
|
||||
queue.push(...(childrenByParent.get(current.id) ?? []))
|
||||
}
|
||||
|
||||
return descendants
|
||||
}
|
||||
|
||||
export function summarizePermissionSelection(permissions: Permission[], selectedIds: string[]) {
|
||||
const selected = new Set(selectedIds)
|
||||
const selectedPermissions = permissions.filter((permission) => selected.has(permission.id))
|
||||
|
||||
return {
|
||||
menuCount: selectedPermissions.filter((permission) => permission.type === '菜单').length,
|
||||
actionCount: selectedPermissions.filter((permission) => ['按钮', '接口'].includes(permission.type)).length,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mapPlatformPermission } from '@/modules/iam/utils/platformPermission'
|
||||
|
||||
describe('mapPlatformPermission', () => {
|
||||
it('treats the string root parent as a root node and preserves long ids', () => {
|
||||
expect(mapPlatformPermission({
|
||||
id: '2082813911786024961',
|
||||
tenantId: '0',
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: '0',
|
||||
permissionCode: 'platform:audit',
|
||||
permissionName: '审计管理',
|
||||
routePath: '/audit',
|
||||
httpMethod: null,
|
||||
sortNo: 50,
|
||||
status: 'ACTIVE',
|
||||
})).toMatchObject({ id: '2082813911786024961', parentId: null, code: 'platform:audit' })
|
||||
})
|
||||
|
||||
it('preserves a long string parent id for child resources', () => {
|
||||
expect(mapPlatformPermission({
|
||||
id: '2082813911786024962',
|
||||
tenantId: '0',
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'BUTTON',
|
||||
parentId: '2082813911786024961',
|
||||
permissionCode: 'platform:audit:list',
|
||||
permissionName: '操作日志',
|
||||
routePath: null,
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
})).toMatchObject({ id: '2082813911786024962', parentId: '2082813911786024961', type: '按钮' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PlatformPermissionResource } from '@/modules/iam/api/platformIam'
|
||||
import type { Permission } from '@/modules/iam/types'
|
||||
|
||||
export function mapPlatformPermission(item: PlatformPermissionResource): Permission {
|
||||
const parentId = String(item.parentId)
|
||||
return {
|
||||
id: String(item.id),
|
||||
parentId: parentId === '0' ? null : parentId,
|
||||
name: item.permissionName,
|
||||
code: item.permissionCode,
|
||||
type: item.permissionType === 'BUTTON' ? '按钮' : '菜单',
|
||||
path: item.routePath ?? '',
|
||||
method: item.httpMethod ?? '-',
|
||||
status: item.status === 'ACTIVE' ? '启用' : '停用',
|
||||
sort: item.sortNo,
|
||||
builtIn: Boolean(item.builtIn),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
changePlatformPartnerStatus,
|
||||
createPlatformPartner,
|
||||
downloadPlatformPartnerImportTemplate,
|
||||
getPlatformPartner,
|
||||
importPlatformPartners,
|
||||
listPlatformPartners,
|
||||
updatePlatformPartner,
|
||||
type SavePlatformPartnerRequest,
|
||||
} from './platformPartners'
|
||||
|
||||
vi.mock('@/shared/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
const payload: SavePlatformPartnerRequest = {
|
||||
partnerCode: 'CUS-001',
|
||||
partnerName: '测试往来单位',
|
||||
partnerType: 'CUSTOMER',
|
||||
types: ['CUSTOMER', 'SHIPPER'],
|
||||
contactName: '测试联系人',
|
||||
contactPhone: '13800000000',
|
||||
contactEmail: null,
|
||||
countryCode: 'CN',
|
||||
province: '广东省',
|
||||
city: '深圳市',
|
||||
district: null,
|
||||
addressLine: '测试地址 1 号',
|
||||
postalCode: null,
|
||||
status: 'ACTIVE',
|
||||
remark: '测试档案',
|
||||
}
|
||||
|
||||
describe('platform partner API', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('queries the platform partner page with tenant and filters', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { records: [], page: '1', size: '20', total: '1', pages: '1' } })
|
||||
|
||||
const result = await listPlatformPartners(10001, { page: 1, size: 20, keyword: '测试', type: 'CUSTOMER', status: 'ACTIVE' })
|
||||
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/partners', {
|
||||
params: { tenantId: 10001, page: 1, size: 20, keyword: '测试', type: 'CUSTOMER', status: 'ACTIVE' },
|
||||
})
|
||||
expect(result).toMatchObject({ page: 1, size: 20, total: 1, pages: 1 })
|
||||
})
|
||||
|
||||
it('uses the backend create, update and status contracts', async () => {
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: '19001' })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
vi.mocked(http.patch).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
|
||||
await createPlatformPartner(10001, payload)
|
||||
await updatePlatformPartner(10001, '19001', payload)
|
||||
await changePlatformPartnerStatus(10001, '19001', 'INACTIVE')
|
||||
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/partners', payload, { params: { tenantId: 10001 } })
|
||||
expect(http.put).toHaveBeenCalledWith('/platform/v1/partners/19001', payload, { params: { tenantId: 10001 } })
|
||||
expect(http.patch).toHaveBeenCalledWith('/platform/v1/partners/19001/status', { status: 'INACTIVE' }, { params: { tenantId: 10001 } })
|
||||
})
|
||||
|
||||
it('normalizes legacy detail types and uses import contracts', async () => {
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: {
|
||||
id: '19001', tenantId: 10001, partnerCode: 'CUS-001', partnerName: '测试单位',
|
||||
partnerType: 'BOTH', contactName: '张三', contactPhone: '13800000000', contactEmail: null,
|
||||
countryCode: 'CN', province: null, city: '深圳市', district: null, addressLine: '测试地址',
|
||||
postalCode: null, status: 'ACTIVE',
|
||||
} })
|
||||
.mockResolvedValueOnce(new Blob(['template']))
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: {
|
||||
fileName: 'partners.xlsx', totalRows: 1, importedRows: 1, success: true, errors: [],
|
||||
} })
|
||||
|
||||
const detail = await getPlatformPartner(10001, '19001')
|
||||
const template = await downloadPlatformPartnerImportTemplate()
|
||||
const file = new File(['xlsx'], 'partners.xlsx')
|
||||
const result = await importPlatformPartners(10001, file)
|
||||
|
||||
expect(detail.types).toEqual(['CUSTOMER', 'SUPPLIER'])
|
||||
expect(detail.dataScopeId).toBe(10001)
|
||||
expect(template).toBeInstanceOf(Blob)
|
||||
expect(result.success).toBe(true)
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/partners/19001', { params: { tenantId: 10001 } })
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/partners/import-template', { responseType: 'blob' })
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/partners/import', expect.any(FormData), { params: { tenantId: 10001 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
export type PlatformPartnerType = 'CUSTOMER' | 'SUPPLIER' | 'CARRIER' | 'CUSTOMS_BROKER' | 'SHIPPER' | 'CONSIGNEE'
|
||||
export type PlatformPartnerLegacyType = PlatformPartnerType | 'BOTH'
|
||||
export type PlatformPartnerStatus = 'ACTIVE' | 'INACTIVE'
|
||||
|
||||
export interface PlatformPartnerResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
dataScopeId: number | string
|
||||
partnerCode: string
|
||||
partnerName: string
|
||||
partnerType: PlatformPartnerLegacyType
|
||||
types: PlatformPartnerType[]
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
contactEmail: string | null
|
||||
countryCode: string
|
||||
province: string | null
|
||||
city: string
|
||||
district: string | null
|
||||
addressLine: string
|
||||
postalCode: string | null
|
||||
status: PlatformPartnerStatus
|
||||
remark: string | null
|
||||
createdAt?: string | null
|
||||
updatedAt?: string | null
|
||||
}
|
||||
|
||||
export interface PlatformPartnerPage {
|
||||
records: PlatformPartnerResource[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
type PlatformPartnerPagePayload = Omit<PlatformPartnerPage, 'page' | 'size' | 'total' | 'pages'> & {
|
||||
page: number | string
|
||||
size: number | string
|
||||
total: number | string
|
||||
pages: number | string
|
||||
}
|
||||
|
||||
export interface PlatformPartnerQuery {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
type?: PlatformPartnerType
|
||||
status?: PlatformPartnerStatus
|
||||
}
|
||||
|
||||
export interface SavePlatformPartnerRequest {
|
||||
partnerCode: string
|
||||
partnerName: string
|
||||
partnerType: PlatformPartnerType
|
||||
types: PlatformPartnerType[]
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
contactEmail: string | null
|
||||
countryCode: string
|
||||
province: string | null
|
||||
city: string
|
||||
district: string | null
|
||||
addressLine: string
|
||||
postalCode: string | null
|
||||
status: PlatformPartnerStatus
|
||||
remark: string | null
|
||||
}
|
||||
|
||||
export interface PlatformPartnerImportError {
|
||||
row: number
|
||||
field: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface PlatformPartnerImportResult {
|
||||
fileName: string
|
||||
totalRows: number
|
||||
importedRows: number
|
||||
success: boolean
|
||||
errors: PlatformPartnerImportError[]
|
||||
}
|
||||
|
||||
const basePath = '/platform/v1/partners'
|
||||
|
||||
function normalizePartner(resource: PlatformPartnerResource): PlatformPartnerResource {
|
||||
const legacyTypes: PlatformPartnerType[] = resource.partnerType === 'BOTH'
|
||||
? ['CUSTOMER', 'SUPPLIER']
|
||||
: [resource.partnerType]
|
||||
return {
|
||||
...resource,
|
||||
dataScopeId: resource.dataScopeId ?? resource.tenantId,
|
||||
types: resource.types?.length ? resource.types : legacyTypes,
|
||||
remark: resource.remark ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export async function listPlatformPartners(tenantId: number, query: PlatformPartnerQuery) {
|
||||
const response = await http.get<ApiEnvelope<PlatformPartnerPagePayload>, ApiEnvelope<PlatformPartnerPagePayload>>(basePath, {
|
||||
params: { tenantId, ...query },
|
||||
})
|
||||
const page = unwrapApiResponse(response)
|
||||
return {
|
||||
...page,
|
||||
records: page.records.map(normalizePartner),
|
||||
page: Number(page.page),
|
||||
size: Number(page.size),
|
||||
total: Number(page.total),
|
||||
pages: Number(page.pages),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPlatformPartner(tenantId: number, partnerId: number | string) {
|
||||
const response = await http.get<ApiEnvelope<PlatformPartnerResource>, ApiEnvelope<PlatformPartnerResource>>(
|
||||
`${basePath}/${partnerId}`,
|
||||
{ params: { tenantId } },
|
||||
)
|
||||
return normalizePartner(unwrapApiResponse(response))
|
||||
}
|
||||
|
||||
export async function downloadPlatformPartnerImportTemplate() {
|
||||
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
|
||||
}
|
||||
|
||||
export async function importPlatformPartners(tenantId: number, file: File) {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
const response = await http.post<ApiEnvelope<PlatformPartnerImportResult>, ApiEnvelope<PlatformPartnerImportResult>>(
|
||||
`${basePath}/import`,
|
||||
form,
|
||||
{ params: { tenantId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function createPlatformPartner(tenantId: number, payload: SavePlatformPartnerRequest) {
|
||||
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function updatePlatformPartner(
|
||||
tenantId: number,
|
||||
partnerId: number | string,
|
||||
payload: SavePlatformPartnerRequest,
|
||||
) {
|
||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${partnerId}`, payload, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function changePlatformPartnerStatus(
|
||||
tenantId: number,
|
||||
partnerId: number | string,
|
||||
status: PlatformPartnerStatus,
|
||||
) {
|
||||
const response = await http.patch<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${partnerId}/status`, { status }, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
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 {
|
||||
listPlatformPartners,
|
||||
type PlatformPartnerResource,
|
||||
} from '@/modules/master-data/counterparties/api/platformPartners'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import PartnersView from './PartnersView.vue'
|
||||
|
||||
vi.mock('@/modules/master-data/counterparties/api/platformPartners', () => ({
|
||||
listPlatformPartners: vi.fn(),
|
||||
createPlatformPartner: vi.fn(),
|
||||
getPlatformPartner: vi.fn(),
|
||||
downloadPlatformPartnerImportTemplate: vi.fn(),
|
||||
importPlatformPartners: vi.fn(),
|
||||
updatePlatformPartner: vi.fn(),
|
||||
changePlatformPartnerStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
const partner: PlatformPartnerResource = {
|
||||
id: '19001',
|
||||
tenantId: 10001,
|
||||
dataScopeId: 10001,
|
||||
partnerCode: 'CUS-001',
|
||||
partnerName: '深圳示例贸易有限公司',
|
||||
partnerType: 'CUSTOMER',
|
||||
types: ['CUSTOMER', 'SHIPPER'],
|
||||
contactName: '张三',
|
||||
contactPhone: '13800138000',
|
||||
contactEmail: 'contact@example.com',
|
||||
countryCode: 'CN',
|
||||
province: '广东省',
|
||||
city: '深圳市',
|
||||
district: '宝安区',
|
||||
addressLine: '航城街道示例路 1 号',
|
||||
postalCode: '518000',
|
||||
status: 'ACTIVE',
|
||||
remark: '长期合作单位',
|
||||
updatedAt: '2026-07-30T22:45:00',
|
||||
}
|
||||
|
||||
async function mountView() {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = [
|
||||
'platform:counterparty:list',
|
||||
'platform:counterparty:create',
|
||||
'platform:counterparty:edit',
|
||||
'platform:counterparty:status',
|
||||
]
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
const wrapper = mount(PartnersView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia, ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
afterAll(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('PartnersView real API integration', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
document.body.innerHTML = ''
|
||||
vi.mocked(listPlatformPartners).mockReset().mockResolvedValue({
|
||||
records: [partner], page: 1, size: 20, total: 1, pages: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('loads the fixed tenant page and renders the real partner fields', async () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(listPlatformPartners).toHaveBeenCalledWith(10001, {
|
||||
page: 1, size: 20, keyword: undefined, type: undefined, status: undefined,
|
||||
})
|
||||
expect(wrapper.text()).toContain('深圳示例贸易有限公司')
|
||||
expect(wrapper.text()).toContain('CUS-001')
|
||||
expect(wrapper.text()).toContain('contact@example.com')
|
||||
expect(wrapper.text()).toContain('广东省 深圳市 宝安区 航城街道示例路 1 号')
|
||||
expect(wrapper.text()).not.toContain('往来单位总数')
|
||||
expect(wrapper.text()).not.toContain('往来单位档案')
|
||||
expect(wrapper.find('.query-toolbar').exists()).toBe(true)
|
||||
expect(wrapper.find('.data-table').exists()).toBe(true)
|
||||
expect(wrapper.find('.table-panel').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('updates filters locally and only requests after search', async () => {
|
||||
const wrapper = await mountView()
|
||||
const keywordInput = wrapper.find('input[placeholder="单位名称、编码、联系人或电话"]')
|
||||
|
||||
await keywordInput.setValue('深圳')
|
||||
await flushPromises()
|
||||
expect(listPlatformPartners).toHaveBeenCalledTimes(1)
|
||||
|
||||
const searchButton = wrapper.findAll('button').find((button) => button.text().trim() === '查询')
|
||||
expect(searchButton).toBeDefined()
|
||||
await searchButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformPartners).toHaveBeenCalledTimes(2)
|
||||
expect(listPlatformPartners).toHaveBeenLastCalledWith(10001, {
|
||||
page: 1, size: 20, keyword: '深圳', type: undefined, status: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('shows useful placeholders and visible required markers in the create form', async () => {
|
||||
const wrapper = await mountView()
|
||||
const createButton = wrapper.findAll('button').find((button) => button.text().trim() === '新增往来单位')
|
||||
expect(createButton).toBeDefined()
|
||||
await createButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(document.querySelector('input[placeholder="请输入工商登记或常用单位名称"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="请输入主要联系人姓名"]')).not.toBeNull()
|
||||
expect(document.querySelector('textarea[placeholder="请输入街道、园区、楼栋及门牌信息"]')).not.toBeNull()
|
||||
expect(document.querySelectorAll('.el-form-item.is-required').length).toBe(9)
|
||||
})
|
||||
|
||||
it('shows a recoverable API failure without demo data', async () => {
|
||||
vi.mocked(listPlatformPartners).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('深圳示例贸易有限公司')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,565 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
|
||||
import { Building2, Download, Eye, MapPin, Pencil, Plus, Power, Upload } from '@lucide/vue'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import {
|
||||
changePlatformPartnerStatus,
|
||||
createPlatformPartner,
|
||||
downloadPlatformPartnerImportTemplate,
|
||||
getPlatformPartner,
|
||||
importPlatformPartners,
|
||||
listPlatformPartners,
|
||||
updatePlatformPartner,
|
||||
type PlatformPartnerImportResult,
|
||||
type PlatformPartnerResource,
|
||||
type PlatformPartnerStatus,
|
||||
type PlatformPartnerLegacyType,
|
||||
type PlatformPartnerType,
|
||||
type SavePlatformPartnerRequest,
|
||||
} from '@/modules/master-data/counterparties/api/platformPartners'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
|
||||
const fixedTenantId = 10001
|
||||
const pageSize = ref(20)
|
||||
const access = useAccessPreviewStore()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const editorOpen = ref(false)
|
||||
const detailOpen = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<PlatformPartnerResource | null>(null)
|
||||
const importOpen = ref(false)
|
||||
const importFile = ref<File | null>(null)
|
||||
const importing = ref(false)
|
||||
const downloadingTemplate = ref(false)
|
||||
const importResult = ref<PlatformPartnerImportResult | null>(null)
|
||||
const formRef = ref<FormInstance>()
|
||||
const rows = ref<PlatformPartnerResource[]>([])
|
||||
const page = ref(1)
|
||||
const total = ref(0)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const statusLoadingIds = ref(new Set<string>())
|
||||
|
||||
type PartnerFilters = QueryModel & {
|
||||
keyword: string
|
||||
type: PlatformPartnerType | ''
|
||||
status: PlatformPartnerStatus | ''
|
||||
}
|
||||
|
||||
const filters = ref<PartnerFilters>({
|
||||
keyword: '',
|
||||
type: '',
|
||||
status: '',
|
||||
})
|
||||
const appliedFilters = ref<PartnerFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '单位名称、编码、联系人或电话' },
|
||||
{
|
||||
key: 'type',
|
||||
type: 'select',
|
||||
placeholder: '全部类型',
|
||||
options: [
|
||||
{ label: '客户', value: 'CUSTOMER' },
|
||||
{ label: '供应商', value: 'SUPPLIER' },
|
||||
{ label: '承运商', value: 'CARRIER' },
|
||||
{ label: '报关行', value: 'CUSTOMS_BROKER' },
|
||||
{ label: '发货单位', value: 'SHIPPER' },
|
||||
{ label: '收货单位', value: 'CONSIGNEE' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
type: 'select',
|
||||
placeholder: '全部状态',
|
||||
options: [
|
||||
{ label: '启用', value: 'ACTIVE' },
|
||||
{ label: '停用', value: 'INACTIVE' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
interface PartnerForm extends SavePlatformPartnerRequest {
|
||||
id: string
|
||||
}
|
||||
|
||||
const emptyForm = (): PartnerForm => ({
|
||||
id: '',
|
||||
partnerCode: '',
|
||||
partnerName: '',
|
||||
partnerType: 'CUSTOMER',
|
||||
types: ['CUSTOMER'],
|
||||
contactName: '',
|
||||
contactPhone: '',
|
||||
contactEmail: null,
|
||||
countryCode: 'CN',
|
||||
province: null,
|
||||
city: '',
|
||||
district: null,
|
||||
addressLine: '',
|
||||
postalCode: null,
|
||||
status: 'ACTIVE',
|
||||
remark: null,
|
||||
})
|
||||
const form = reactive<PartnerForm>(emptyForm())
|
||||
const editorLabel = computed(() => form.id ? '编辑往来单位' : '新增往来单位')
|
||||
const editorPermission = computed(() => form.id ? 'platform:counterparty:edit' : 'platform:counterparty:create')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'partner-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission: editorPermission,
|
||||
})
|
||||
|
||||
const rules: FormRules<PartnerForm> = {
|
||||
partnerCode: [{ required: true, whitespace: true, message: '请输入往来单位编码', trigger: 'blur' }],
|
||||
partnerName: [{ required: true, whitespace: true, message: '请输入往来单位名称', trigger: 'blur' }],
|
||||
types: [{ required: true, type: 'array', min: 1, message: '请至少选择一个单位类型', trigger: 'change' }],
|
||||
contactName: [{ required: true, whitespace: true, message: '请输入联系人', trigger: 'blur' }],
|
||||
contactPhone: [{ required: true, whitespace: true, message: '请输入联系电话', trigger: 'blur' }],
|
||||
contactEmail: [{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }],
|
||||
countryCode: [
|
||||
{ required: true, whitespace: true, message: '请输入国家二字码', trigger: 'blur' },
|
||||
{ pattern: /^[A-Z]{2}$/, message: '国家码须为两个大写英文字母', trigger: 'blur' },
|
||||
],
|
||||
city: [{ required: true, whitespace: true, message: '请输入城市', trigger: 'blur' }],
|
||||
addressLine: [{ required: true, whitespace: true, message: '请输入详细地址', trigger: 'blur' }],
|
||||
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
|
||||
}
|
||||
|
||||
const typeLabels: Record<PlatformPartnerType, string> = {
|
||||
CUSTOMER: '客户',
|
||||
SUPPLIER: '供应商',
|
||||
CARRIER: '承运商',
|
||||
CUSTOMS_BROKER: '报关行',
|
||||
SHIPPER: '发货单位',
|
||||
CONSIGNEE: '收货单位',
|
||||
}
|
||||
const typeOptions = Object.entries(typeLabels).map(([value, label]) => ({ value: value as PlatformPartnerType, label }))
|
||||
function partnerTypeLabel(type: PlatformPartnerLegacyType) {
|
||||
return type === 'BOTH' ? '客户 / 供应商' : typeLabels[type]
|
||||
}
|
||||
const partnerColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 210, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'partner', label: '往来单位', minWidth: 210, slotName: 'partner' },
|
||||
{ key: 'type', label: '类型', minWidth: 115, slotName: 'type' },
|
||||
{ key: 'contact', label: '联系人', minWidth: 165, slotName: 'contact' },
|
||||
{ key: 'address', label: '地址', minWidth: 240, slotName: 'address' },
|
||||
{ key: 'status', label: '状态', width: 90, slotName: 'status' },
|
||||
{ prop: 'updatedAt', label: '更新时间', minWidth: 140, formatter: (row: PlatformPartnerResource) => formatUpdatedAt(row.updatedAt) },
|
||||
]
|
||||
|
||||
watch(
|
||||
() => access.can(editorPermission.value),
|
||||
(canWrite) => {
|
||||
if (canWrite || !editorOpen.value) return
|
||||
editorOpen.value = false
|
||||
Object.assign(form, emptyForm())
|
||||
},
|
||||
{ flush: 'sync' },
|
||||
)
|
||||
|
||||
function queryParams() {
|
||||
return {
|
||||
page: page.value,
|
||||
size: pageSize.value,
|
||||
keyword: appliedFilters.value.keyword.trim() || undefined,
|
||||
type: appliedFilters.value.type || undefined,
|
||||
status: appliedFilters.value.status || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPartners() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const result = await listPlatformPartners(fixedTenantId, queryParams())
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '往来单位加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function searchPartners(model: QueryModel) {
|
||||
appliedFilters.value = {
|
||||
keyword: String(model.keyword || ''),
|
||||
type: (model.type || '') as PlatformPartnerType | '',
|
||||
status: (model.status || '') as PlatformPartnerStatus | '',
|
||||
}
|
||||
if (page.value === 1) {
|
||||
void loadPartners()
|
||||
return
|
||||
}
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, emptyForm())
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
requestAnimationFrame(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function nullable(value: string | null) {
|
||||
return value?.trim() || null
|
||||
}
|
||||
|
||||
function openEdit(row: PlatformPartnerResource) {
|
||||
Object.assign(form, {
|
||||
id: String(row.id),
|
||||
partnerCode: row.partnerCode,
|
||||
partnerName: row.partnerName,
|
||||
partnerType: row.types[0],
|
||||
types: [...row.types],
|
||||
contactName: row.contactName,
|
||||
contactPhone: row.contactPhone,
|
||||
contactEmail: row.contactEmail,
|
||||
countryCode: row.countryCode,
|
||||
province: row.province,
|
||||
city: row.city,
|
||||
district: row.district,
|
||||
addressLine: row.addressLine,
|
||||
postalCode: row.postalCode,
|
||||
status: row.status,
|
||||
remark: row.remark,
|
||||
})
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
requestAnimationFrame(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function savePayload(): SavePlatformPartnerRequest {
|
||||
const types = [...form.types]
|
||||
return {
|
||||
partnerCode: form.partnerCode.trim(),
|
||||
partnerName: form.partnerName.trim(),
|
||||
partnerType: types[0],
|
||||
types,
|
||||
contactName: form.contactName.trim(),
|
||||
contactPhone: form.contactPhone.trim(),
|
||||
contactEmail: nullable(form.contactEmail),
|
||||
countryCode: form.countryCode.trim().toUpperCase(),
|
||||
province: nullable(form.province),
|
||||
city: form.city.trim(),
|
||||
district: nullable(form.district),
|
||||
addressLine: form.addressLine.trim(),
|
||||
postalCode: nullable(form.postalCode),
|
||||
status: form.status,
|
||||
remark: nullable(form.remark),
|
||||
}
|
||||
}
|
||||
|
||||
async function openDetail(row: PlatformPartnerResource) {
|
||||
detailOpen.value = true
|
||||
detailLoading.value = true
|
||||
detail.value = null
|
||||
try {
|
||||
detail.value = await getPlatformPartner(fixedTenantId, row.id)
|
||||
} catch (error) {
|
||||
const meta = getApiErrorDetails(error, '往来单位详情加载失败')
|
||||
ElMessage.error(meta.requestId ? `${meta.message}(requestId: ${meta.requestId})` : meta.message)
|
||||
detailOpen.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openImport() {
|
||||
importFile.value = null
|
||||
importResult.value = null
|
||||
importOpen.value = true
|
||||
}
|
||||
|
||||
function selectImportFile(uploadFile: UploadFile) {
|
||||
importFile.value = uploadFile.raw ?? null
|
||||
importResult.value = null
|
||||
}
|
||||
|
||||
function removeImportFile() {
|
||||
importFile.value = null
|
||||
}
|
||||
|
||||
async function downloadTemplate() {
|
||||
downloadingTemplate.value = true
|
||||
try {
|
||||
const blob = await downloadPlatformPartnerImportTemplate()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = '往来单位导入模板-v1.xlsx'
|
||||
link.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorDetails(error, '模板下载失败,请重试').message)
|
||||
} finally {
|
||||
downloadingTemplate.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitImport() {
|
||||
if (!importFile.value) {
|
||||
ElMessage.warning('请先选择 XLSX 文件')
|
||||
return
|
||||
}
|
||||
importing.value = true
|
||||
importResult.value = null
|
||||
try {
|
||||
importResult.value = await importPlatformPartners(fixedTenantId, importFile.value)
|
||||
if (importResult.value.success) {
|
||||
ElMessage.success(`成功导入 ${importResult.value.importedRows} 条往来单位`)
|
||||
await loadPartners()
|
||||
}
|
||||
} catch (error) {
|
||||
const meta = getApiErrorDetails(error, '往来单位导入失败,请重试')
|
||||
ElMessage.error(meta.requestId ? `${meta.message}(requestId: ${meta.requestId})` : meta.message)
|
||||
} finally {
|
||||
importing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function downloadImportErrors() {
|
||||
if (!importResult.value?.errors.length) return
|
||||
const escapeCsv = (value: string | number) => `"${String(value).replaceAll('"', '""')}"`
|
||||
const rows = [
|
||||
['行号', '字段', '原因'],
|
||||
...importResult.value.errors.map((error) => [error.row || '-', error.field, error.message]),
|
||||
]
|
||||
const csv = rows.map((row) => row.map(escapeCsv).join(',')).join('\r\n')
|
||||
const url = URL.createObjectURL(new Blob(['\ufeff', csv], { type: 'text/csv;charset=utf-8' }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = `${importResult.value.fileName.replace(/\.xlsx$/i, '')}-错误报告.csv`
|
||||
link.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
async function savePartner() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
saving.value = true
|
||||
try {
|
||||
const payload = savePayload()
|
||||
if (form.id) {
|
||||
await updatePlatformPartner(fixedTenantId, form.id, payload)
|
||||
ElMessage.success('往来单位已更新')
|
||||
} else {
|
||||
await createPlatformPartner(fixedTenantId, payload)
|
||||
ElMessage.success('往来单位已新增')
|
||||
}
|
||||
editorOpen.value = false
|
||||
await loadPartners()
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '往来单位保存失败,请重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(row: PlatformPartnerResource) {
|
||||
const nextStatus: PlatformPartnerStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
||||
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`${action}后${nextStatus === 'ACTIVE' ? '可继续用于新业务' : '不再用于新业务,历史数据不受影响'}。`,
|
||||
`${action}“${row.partnerName}”`,
|
||||
{ type: nextStatus === 'ACTIVE' ? 'success' : 'warning', confirmButtonText: action, cancelButtonText: '取消' },
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const id = String(row.id)
|
||||
statusLoadingIds.value = new Set(statusLoadingIds.value).add(id)
|
||||
try {
|
||||
await changePlatformPartnerStatus(fixedTenantId, row.id, nextStatus)
|
||||
ElMessage.success(`往来单位已${action}`)
|
||||
await loadPartners()
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, `往来单位${action}失败,请重试`)
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
const next = new Set(statusLoadingIds.value)
|
||||
next.delete(id)
|
||||
statusLoadingIds.value = next
|
||||
}
|
||||
}
|
||||
|
||||
function formatUpdatedAt(value?: string | null) {
|
||||
return value ? value.replace('T', ' ').slice(0, 16) : '-'
|
||||
}
|
||||
|
||||
watch([page, pageSize], () => { void loadPartners() })
|
||||
|
||||
onMounted(loadPartners)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page partners-page">
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="往来单位筛选" :fields="queryFields" @search="searchPartners" />
|
||||
|
||||
<section v-if="loadError" class="surface-panel partners-error" role="alert">
|
||||
<div>
|
||||
<strong>往来单位列表暂时无法加载</strong>
|
||||
<p>{{ loadError.message }}</p>
|
||||
<ApiErrorMeta :details="loadError" />
|
||||
</div>
|
||||
<el-button type="primary" :loading="loading" @click="loadPartners">重新加载</el-button>
|
||||
</section>
|
||||
|
||||
<section v-else class="surface-panel table-panel" :aria-busy="loading">
|
||||
<div class="partners-table-header">
|
||||
<div class="partners-table-heading">
|
||||
<h2>往来单位列表</h2>
|
||||
<span>共 {{ total }} 个往来单位</span>
|
||||
</div>
|
||||
<div class="partners-primary-actions">
|
||||
<el-button v-if="access.can('platform:counterparty:import')" :disabled="loading" @click="openImport"><Upload :size="16" />批量导入</el-button>
|
||||
<el-button v-if="access.can('platform:counterparty:create')" type="primary" :disabled="loading" @click="openCreate"><Plus :size="16" />新增往来单位</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<DataTable
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:data="rows"
|
||||
:columns="partnerColumns"
|
||||
:loading="loading"
|
||||
:total="total"
|
||||
:page-sizes="[20, 50, 100]"
|
||||
aria-label="往来单位列表"
|
||||
row-key="id"
|
||||
empty-text="暂无符合条件的往来单位"
|
||||
>
|
||||
<template #actions="{ row }">
|
||||
<div class="table-actions">
|
||||
<el-button link type="primary" @click="openDetail(row as PlatformPartnerResource)"><Eye :size="15" />详情</el-button>
|
||||
<el-button v-if="access.can('platform:counterparty:edit')" link type="primary" @click="openEdit(row as PlatformPartnerResource)"><Pencil :size="15" />编辑</el-button>
|
||||
<el-button v-if="access.can('platform:counterparty:status')" link :type="(row as PlatformPartnerResource).status === 'ACTIVE' ? 'danger' : 'success'" :loading="statusLoadingIds.has(String((row as PlatformPartnerResource).id))" @click="toggleStatus(row as PlatformPartnerResource)"><Power :size="15" />{{ (row as PlatformPartnerResource).status === 'ACTIVE' ? '停用' : '启用' }}</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<template #partner="{ row }"><div class="partner-cell"><span><Building2 :size="18" /></span><div><strong>{{ (row as PlatformPartnerResource).partnerName }}</strong><small>{{ (row as PlatformPartnerResource).partnerCode }}</small></div></div></template>
|
||||
<template #type="{ row }"><div class="partner-types"><el-tag v-for="type in (row as PlatformPartnerResource).types" :key="type" effect="plain">{{ partnerTypeLabel(type) }}</el-tag></div></template>
|
||||
<template #contact="{ row }"><strong>{{ (row as PlatformPartnerResource).contactName }}</strong><span class="partner-subline">{{ (row as PlatformPartnerResource).contactPhone }}</span><span v-if="(row as PlatformPartnerResource).contactEmail" class="partner-subline">{{ (row as PlatformPartnerResource).contactEmail }}</span></template>
|
||||
<template #address="{ row }"><div class="partner-address"><MapPin :size="15" /><span>{{ [(row as PlatformPartnerResource).province, (row as PlatformPartnerResource).city, (row as PlatformPartnerResource).district, (row as PlatformPartnerResource).addressLine].filter(Boolean).join(' ') }}</span></div></template>
|
||||
<template #status="{ row }"><el-tag :type="(row as PlatformPartnerResource).status === 'ACTIVE' ? 'success' : 'info'" effect="light">{{ (row as PlatformPartnerResource).status === 'ACTIVE' ? '启用' : '停用' }}</el-tag></template>
|
||||
<template #pagination-left />
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="editorLabel" size="680px" class="business-drawer editor-drawer" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="drawer-form" :disabled="saving">
|
||||
<div class="form-section"><h3>单位信息</h3><div class="form-grid two-cols">
|
||||
<el-form-item label="单位编码" prop="partnerCode" required><el-input v-model="form.partnerCode" placeholder="如:CUS-001" maxlength="50" /></el-form-item>
|
||||
<el-form-item label="单位名称" prop="partnerName" required><el-input v-model="form.partnerName" placeholder="请输入工商登记或常用单位名称" maxlength="128" /></el-form-item>
|
||||
<el-form-item label="单位类型" prop="types" required><el-select v-model="form.types" multiple collapse-tags collapse-tags-tooltip placeholder="请选择一个或多个单位类型"><el-option v-for="option in typeOptions" :key="option.value" :label="option.label" :value="option.value" /></el-select></el-form-item>
|
||||
<el-form-item label="状态" prop="status" required><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="联系人" prop="contactName" required><el-input v-model="form.contactName" placeholder="请输入主要联系人姓名" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="联系电话" prop="contactPhone" required><el-input v-model="form.contactPhone" placeholder="请输入手机号或固定电话" maxlength="32" /></el-form-item>
|
||||
<el-form-item label="联系邮箱" prop="contactEmail"><el-input v-model="form.contactEmail" placeholder="如:contact@example.com" maxlength="128" /></el-form-item>
|
||||
</div></div>
|
||||
<div class="form-section"><h3>地址信息</h3><div class="form-grid two-cols">
|
||||
<el-form-item label="国家二字码" prop="countryCode" required><el-input v-model="form.countryCode" placeholder="如:CN" maxlength="2" @input="form.countryCode = String($event).toUpperCase()" /></el-form-item>
|
||||
<el-form-item label="省 / 州" prop="province"><el-input v-model="form.province" placeholder="如:广东省" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="城市" prop="city" required><el-input v-model="form.city" placeholder="如:深圳市" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="区 / 县" prop="district"><el-input v-model="form.district" placeholder="如:宝安区" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="邮政编码" prop="postalCode"><el-input v-model="form.postalCode" placeholder="如:518000" maxlength="20" /></el-form-item>
|
||||
</div><el-form-item label="详细地址" prop="addressLine" required><el-input v-model="form.addressLine" type="textarea" :rows="3" placeholder="请输入街道、园区、楼栋及门牌信息" maxlength="255" show-word-limit /></el-form-item></div>
|
||||
<div class="form-section"><h3>其他信息</h3><el-form-item label="备注" prop="remark"><el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内部说明(选填)" maxlength="500" show-word-limit /></el-form-item></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button type="primary" :loading="saving" @click="savePartner">保存往来单位</el-button></div></template>
|
||||
</el-drawer>
|
||||
|
||||
<el-drawer v-model="detailOpen" title="往来单位详情" size="680px" class="business-drawer detail-drawer">
|
||||
<div v-loading="detailLoading" class="partner-detail">
|
||||
<template v-if="detail">
|
||||
<section><h3>单位信息</h3><dl class="detail-grid">
|
||||
<div><dt>单位编码</dt><dd>{{ detail.partnerCode }}</dd></div>
|
||||
<div><dt>单位名称</dt><dd>{{ detail.partnerName }}</dd></div>
|
||||
<div><dt>状态</dt><dd><el-tag :type="detail.status === 'ACTIVE' ? 'success' : 'info'">{{ detail.status === 'ACTIVE' ? '启用' : '停用' }}</el-tag></dd></div>
|
||||
<div><dt>单位类型</dt><dd class="partner-types"><el-tag v-for="type in detail.types" :key="type" effect="plain">{{ partnerTypeLabel(type) }}</el-tag></dd></div>
|
||||
</dl></section>
|
||||
<section><h3>联系与地址</h3><dl class="detail-grid">
|
||||
<div><dt>联系人</dt><dd>{{ detail.contactName }}</dd></div><div><dt>联系电话</dt><dd>{{ detail.contactPhone }}</dd></div>
|
||||
<div><dt>联系邮箱</dt><dd>{{ detail.contactEmail || '-' }}</dd></div><div><dt>邮政编码</dt><dd>{{ detail.postalCode || '-' }}</dd></div>
|
||||
<div class="detail-span"><dt>详细地址</dt><dd>{{ [detail.countryCode, detail.province, detail.city, detail.district, detail.addressLine].filter(Boolean).join(' ') }}</dd></div>
|
||||
</dl></section>
|
||||
<section><h3>其他信息</h3><dl class="detail-grid">
|
||||
<div><dt>数据范围</dt><dd>{{ detail.dataScopeId }}</dd></div><div><dt>更新时间</dt><dd>{{ formatUpdatedAt(detail.updatedAt) }}</dd></div>
|
||||
<div class="detail-span"><dt>备注</dt><dd>{{ detail.remark || '-' }}</dd></div>
|
||||
</dl></section>
|
||||
</template>
|
||||
</div>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog v-model="importOpen" title="批量导入往来单位" width="min(720px, calc(100vw - 32px))" :close-on-click-modal="!importing" :close-on-press-escape="!importing">
|
||||
<div class="import-content">
|
||||
<div class="import-guide"><strong>使用标准模板导入</strong><p>仅新增档案,最多 1000 行。服务端会整批校验;任一行有误时不会写入任何数据。</p><el-button :loading="downloadingTemplate" @click="downloadTemplate"><Download :size="16" />下载 XLSX 模板</el-button></div>
|
||||
<el-upload accept=".xlsx" :auto-upload="false" :limit="1" :on-change="selectImportFile" :on-remove="removeImportFile">
|
||||
<el-button><Upload :size="16" />选择 XLSX 文件</el-button>
|
||||
<template #tip><div class="el-upload__tip">文件不得超过 5MB,请勿修改模板版本或表头。</div></template>
|
||||
</el-upload>
|
||||
<div v-if="importResult" :class="['import-result', importResult.success ? 'is-success' : 'is-error']" role="status">
|
||||
<div class="import-result-heading"><strong>{{ importResult.success ? `已成功导入 ${importResult.importedRows} 条记录` : `发现 ${importResult.errors.length} 个问题,未写入数据` }}</strong><el-button v-if="importResult.errors.length" size="small" @click="downloadImportErrors"><Download :size="15" />下载错误报告</el-button></div>
|
||||
<el-table v-if="importResult.errors.length" :data="importResult.errors" max-height="260" size="small">
|
||||
<el-table-column prop="row" label="行号" width="70"><template #default="{ row }">{{ row.row || '-' }}</template></el-table-column>
|
||||
<el-table-column prop="field" label="字段" width="120" /><el-table-column prop="message" label="原因" min-width="240" />
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer><el-button :disabled="importing" @click="importOpen = false">关闭</el-button><el-button type="primary" :loading="importing" :disabled="!importFile" @click="submitImport">开始导入</el-button></template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.partners-error { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 16px; padding: 18px 20px; border-color: #fecdca; background: #fffafa; }
|
||||
.partners-error strong { color: #7a271a; font-size: 13px; }
|
||||
.partners-error p { margin: 4px 0 0; color: #b54708; font-size: 12px; overflow-wrap: anywhere; }
|
||||
.partners-table-header { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 18px; border-bottom: 1px solid var(--cc-border); }
|
||||
.partners-table-heading { display: flex; min-width: 0; align-items: baseline; gap: 10px; }
|
||||
.partners-table-heading h2 { margin: 0; color: var(--cc-text); font-size: 16px; line-height: 1.4; }
|
||||
.partners-table-heading span { color: var(--cc-muted); font-size: 12px; white-space: nowrap; }
|
||||
.partners-primary-actions, .partner-types { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.partner-cell { display: flex; align-items: center; gap: 10px; }
|
||||
.partner-cell > span { display: grid; width: 34px; height: 34px; flex: 0 0 34px; place-items: center; border-radius: 7px; background: #eef3fa; color: var(--cc-primary); }
|
||||
.partner-cell > div { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
|
||||
.partner-cell strong { overflow-wrap: anywhere; }
|
||||
.partner-cell small, .partner-subline { display: block; color: var(--cc-muted); font-size: 11px; line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.partner-address { display: flex; align-items: flex-start; gap: 7px; line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.partner-address svg { flex: 0 0 15px; margin-top: 3px; color: var(--cc-muted); }
|
||||
.partner-detail { min-height: 180px; }
|
||||
.partner-detail section + section { margin-top: 24px; }
|
||||
.partner-detail h3 { margin: 0 0 12px; color: var(--cc-text); font-size: 15px; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1px; margin: 0; overflow: hidden; border: 1px solid var(--cc-border); border-radius: 8px; background: var(--cc-border); }
|
||||
.detail-grid > div { min-width: 0; padding: 12px 14px; background: #fff; }
|
||||
.detail-grid .detail-span { grid-column: 1 / -1; }
|
||||
.detail-grid dt { margin-bottom: 5px; color: var(--cc-muted); font-size: 12px; }
|
||||
.detail-grid dd { margin: 0; color: var(--cc-text); line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.import-content { display: grid; gap: 18px; }
|
||||
.import-guide { padding: 16px; border: 1px solid #d8e2f0; border-radius: 8px; background: #f8fbff; }
|
||||
.import-guide p { margin: 6px 0 14px; color: var(--cc-muted); font-size: 13px; line-height: 1.6; }
|
||||
.import-result { display: grid; gap: 12px; padding: 14px; border: 1px solid; border-radius: 8px; }
|
||||
.import-result-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.import-result.is-success { border-color: #a6f4c5; background: #f6fef9; color: #067647; }
|
||||
.import-result.is-error { border-color: #fecdca; background: #fffafa; color: #b42318; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.partners-error { align-items: stretch; flex-direction: column; }
|
||||
.partners-error .el-button { min-height: 44px; }
|
||||
.partners-table-header { align-items: stretch; flex-direction: column; }
|
||||
.partners-table-header .el-button { width: 100%; min-height: 40px; }
|
||||
.partners-primary-actions { flex-direction: column; }
|
||||
.detail-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.detail-grid .detail-span { grid-column: auto; }
|
||||
.import-result-heading { align-items: stretch; flex-direction: column; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,100 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
changePlatformExpressCompanyStatus,
|
||||
createPlatformExpressCompany,
|
||||
downloadPlatformExpressCompanyImportTemplate,
|
||||
getPlatformExpressCompany,
|
||||
importPlatformExpressCompanies,
|
||||
listPlatformExpressCompanies,
|
||||
updatePlatformExpressCompany,
|
||||
type SavePlatformExpressCompanyRequest,
|
||||
} from './platformExpressCompanies'
|
||||
|
||||
vi.mock('@/shared/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
const payload: SavePlatformExpressCompanyRequest = {
|
||||
companyCode: 'SF',
|
||||
companyName: '顺丰速运',
|
||||
servicePhone: '95338',
|
||||
website: 'https://www.sf-express.com',
|
||||
trackingUrlTemplate: 'https://example.com/track/{trackingNo}',
|
||||
status: 'ACTIVE',
|
||||
remark: null,
|
||||
}
|
||||
|
||||
describe('platform express company API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(http.patch).mockReset()
|
||||
})
|
||||
|
||||
it('uses the implemented list and detail contracts', async () => {
|
||||
const page = { records: [], page: '1', size: '20', total: '0', pages: '0' }
|
||||
vi.mocked(http.get)
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: page })
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: { id: '19001' } })
|
||||
|
||||
await expect(listPlatformExpressCompanies(10001, 2, 20, ' 顺丰 ', 'ACTIVE')).resolves.toEqual({
|
||||
records: [],
|
||||
page: 1,
|
||||
size: 20,
|
||||
total: 0,
|
||||
pages: 0,
|
||||
})
|
||||
await expect(getPlatformExpressCompany(10001, '19001')).resolves.toEqual({ id: '19001' })
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/express-companies', {
|
||||
params: { tenantId: 10001, page: 2, size: 20, keyword: '顺丰', status: 'ACTIVE' },
|
||||
})
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/express-companies/19001', {
|
||||
params: { tenantId: 10001 },
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the implemented create, update, and status contracts', async () => {
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: '19001' })
|
||||
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()
|
||||
|
||||
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.patch).toHaveBeenCalledWith(
|
||||
'/platform/v1/express-companies/19001/status',
|
||||
{ status: 'INACTIVE' },
|
||||
{ params: { tenantId: 10001 } },
|
||||
)
|
||||
})
|
||||
|
||||
it('downloads the standard template as a blob', async () => {
|
||||
const template = new Blob(['xlsx'], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
|
||||
vi.mocked(http.get).mockResolvedValue(template)
|
||||
|
||||
await expect(downloadPlatformExpressCompanyImportTemplate()).resolves.toBe(template)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/express-companies/import-template', { responseType: 'blob' })
|
||||
})
|
||||
|
||||
it('uploads the selected XLSX file as multipart form data', async () => {
|
||||
const result = { fileName: 'express.xlsx', totalRows: 2, importedRows: 2, success: true, errors: [] }
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: result })
|
||||
const file = new File(['xlsx'], 'express.xlsx', {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
})
|
||||
|
||||
await expect(importPlatformExpressCompanies(10001, 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 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
|
||||
export type PlatformExpressCompanyStatus = 'ACTIVE' | 'INACTIVE'
|
||||
|
||||
export interface PlatformExpressCompanyResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
companyCode: string
|
||||
companyName: string
|
||||
servicePhone: string | null
|
||||
website: string | null
|
||||
trackingUrlTemplate: string | null
|
||||
status: PlatformExpressCompanyStatus
|
||||
remark: string | null
|
||||
createdAt?: string | null
|
||||
updatedAt?: string | null
|
||||
}
|
||||
|
||||
export interface PlatformExpressCompanyPage {
|
||||
records: PlatformExpressCompanyResource[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
export interface SavePlatformExpressCompanyRequest {
|
||||
companyCode: string
|
||||
companyName: string
|
||||
servicePhone: string | null
|
||||
website: string | null
|
||||
trackingUrlTemplate: string | null
|
||||
status: PlatformExpressCompanyStatus
|
||||
remark: string | null
|
||||
}
|
||||
|
||||
export interface PlatformExpressCompanyImportError {
|
||||
row: number
|
||||
field: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface PlatformExpressCompanyImportResult {
|
||||
fileName: string
|
||||
totalRows: number
|
||||
importedRows: number
|
||||
success: boolean
|
||||
errors: PlatformExpressCompanyImportError[]
|
||||
}
|
||||
|
||||
const basePath = '/platform/v1/express-companies'
|
||||
|
||||
export async function listPlatformExpressCompanies(
|
||||
tenantId: number,
|
||||
page = 1,
|
||||
size = 20,
|
||||
keyword = '',
|
||||
status: PlatformExpressCompanyStatus | '' = '',
|
||||
) {
|
||||
const response = await http.get<ApiEnvelope<PlatformExpressCompanyPage>, ApiEnvelope<PlatformExpressCompanyPage>>(basePath, {
|
||||
params: {
|
||||
tenantId,
|
||||
page,
|
||||
size,
|
||||
keyword: keyword.trim() || undefined,
|
||||
status: status || undefined,
|
||||
},
|
||||
})
|
||||
const result = unwrapApiResponse(response)
|
||||
return {
|
||||
...result,
|
||||
page: Number(result.page),
|
||||
size: Number(result.size),
|
||||
total: Number(result.total),
|
||||
pages: Number(result.pages),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPlatformExpressCompany(tenantId: number, id: number | string) {
|
||||
const response = await http.get<ApiEnvelope<PlatformExpressCompanyResource>, ApiEnvelope<PlatformExpressCompanyResource>>(
|
||||
`${basePath}/${id}`,
|
||||
{ params: { tenantId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function createPlatformExpressCompany(tenantId: number, payload: SavePlatformExpressCompanyRequest) {
|
||||
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function updatePlatformExpressCompany(
|
||||
tenantId: number,
|
||||
id: number | string,
|
||||
payload: SavePlatformExpressCompanyRequest,
|
||||
) {
|
||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${id}`, payload, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function changePlatformExpressCompanyStatus(
|
||||
tenantId: number,
|
||||
id: number | string,
|
||||
status: PlatformExpressCompanyStatus,
|
||||
) {
|
||||
const response = await http.patch<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${id}/status`, { status }, {
|
||||
params: { tenantId },
|
||||
})
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export async function downloadPlatformExpressCompanyImportTemplate() {
|
||||
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
|
||||
}
|
||||
|
||||
export async function importPlatformExpressCompanies(tenantId: number, file: File) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
const response = await http.post<ApiEnvelope<PlatformExpressCompanyImportResult>, ApiEnvelope<PlatformExpressCompanyImportResult>>(
|
||||
`${basePath}/import`,
|
||||
formData,
|
||||
{ params: { tenantId } },
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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 { listPlatformExpressCompanies, type PlatformExpressCompanyResource } from '@/modules/master-data/express-companies/api/platformExpressCompanies'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import ExpressCompaniesView from './ExpressCompaniesView.vue'
|
||||
|
||||
vi.mock('@/modules/master-data/express-companies/api/platformExpressCompanies', () => ({
|
||||
listPlatformExpressCompanies: vi.fn(),
|
||||
createPlatformExpressCompany: vi.fn(),
|
||||
updatePlatformExpressCompany: vi.fn(),
|
||||
changePlatformExpressCompanyStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
const company: PlatformExpressCompanyResource = {
|
||||
id: '19001',
|
||||
tenantId: 10001,
|
||||
companyCode: 'SF',
|
||||
companyName: '顺丰速运',
|
||||
servicePhone: '95338',
|
||||
website: 'https://www.sf-express.com',
|
||||
trackingUrlTemplate: 'https://example.com/track/{trackingNo}',
|
||||
status: 'ACTIVE',
|
||||
remark: '测试数据',
|
||||
updatedAt: '2026-07-31T10:20:00',
|
||||
}
|
||||
|
||||
async function mountView() {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:express:list', 'platform:express:create', 'platform:express:edit', 'platform:express:status']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
const wrapper = mount(ExpressCompaniesView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia, ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
afterAll(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('ExpressCompaniesView query and table migration', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
document.body.innerHTML = ''
|
||||
vi.mocked(listPlatformExpressCompanies).mockReset().mockResolvedValue({
|
||||
records: [company], page: 1, size: 20, total: 1, pages: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('renders the shared toolbar and data table without a summary strip', async () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.find('.query-toolbar').exists()).toBe(true)
|
||||
expect(wrapper.find('.data-table').exists()).toBe(true)
|
||||
expect(wrapper.text()).toContain('顺丰速运')
|
||||
expect(wrapper.find('.metric-strip').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('does not request with edited filters until search is submitted', async () => {
|
||||
const wrapper = await mountView()
|
||||
await wrapper.find('input[placeholder="快递公司名称或编码"]').setValue('顺丰')
|
||||
await flushPromises()
|
||||
expect(listPlatformExpressCompanies).toHaveBeenCalledTimes(1)
|
||||
|
||||
const searchButton = wrapper.findAll('button').find((button) => button.text().trim() === '查询')
|
||||
await searchButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(10001, 1, 20, '顺丰', '')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,560 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Download, ExternalLink, FileSpreadsheet, Pencil, Plus, Power, Truck, Upload } from '@lucide/vue'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import {
|
||||
changePlatformExpressCompanyStatus,
|
||||
createPlatformExpressCompany,
|
||||
downloadPlatformExpressCompanyImportTemplate,
|
||||
getPlatformExpressCompany,
|
||||
importPlatformExpressCompanies,
|
||||
listPlatformExpressCompanies,
|
||||
updatePlatformExpressCompany,
|
||||
type PlatformExpressCompanyImportResult,
|
||||
type PlatformExpressCompanyResource,
|
||||
type PlatformExpressCompanyStatus,
|
||||
type SavePlatformExpressCompanyRequest,
|
||||
} from '@/modules/master-data/express-companies/api/platformExpressCompanies'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
|
||||
const fixedTenantId = 10001
|
||||
const access = useAccessPreviewStore()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const editorOpen = ref(false)
|
||||
const importOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const fileInputRef = ref<HTMLInputElement>()
|
||||
const rows = ref<PlatformExpressCompanyResource[]>([])
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const total = ref(0)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const statusLoadingIds = ref(new Set<string>())
|
||||
const editLoadingIds = ref(new Set<string>())
|
||||
const downloadingTemplate = ref(false)
|
||||
const importing = ref(false)
|
||||
const importFile = ref<File | null>(null)
|
||||
const importResult = ref<PlatformExpressCompanyImportResult | null>(null)
|
||||
const importError = ref<ApiErrorDetails | null>(null)
|
||||
type ExpressCompanyFilters = QueryModel & {
|
||||
keyword: string
|
||||
status: PlatformExpressCompanyStatus | ''
|
||||
}
|
||||
const filters = ref<ExpressCompanyFilters>({ keyword: '', status: '' })
|
||||
const appliedFilters = ref<ExpressCompanyFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '快递公司名称或编码', props: { maxlength: 128, 'aria-label': '快递公司关键词' } },
|
||||
{
|
||||
key: 'status',
|
||||
type: 'select',
|
||||
placeholder: '全部状态',
|
||||
props: { 'aria-label': '快递公司状态' },
|
||||
options: [
|
||||
{ label: '启用', value: 'ACTIVE' },
|
||||
{ label: '停用', value: 'INACTIVE' },
|
||||
],
|
||||
},
|
||||
]
|
||||
let loadSequence = 0
|
||||
|
||||
const emptyForm = (): SavePlatformExpressCompanyRequest & { id: string } => ({
|
||||
id: '',
|
||||
companyCode: '',
|
||||
companyName: '',
|
||||
servicePhone: null,
|
||||
website: null,
|
||||
trackingUrlTemplate: null,
|
||||
status: 'ACTIVE',
|
||||
remark: null,
|
||||
})
|
||||
const form = reactive(emptyForm())
|
||||
const rules: FormRules<typeof form> = {
|
||||
companyCode: [{ required: true, message: '请输入快递公司编码', trigger: 'blur' }],
|
||||
companyName: [{ required: true, message: '请输入快递公司名称', trigger: 'blur' }],
|
||||
website: [{ type: 'url', message: '请输入以 http:// 或 https:// 开头的完整网址', trigger: 'blur' }],
|
||||
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
|
||||
}
|
||||
const editorTitle = computed(() => form.id ? '编辑快递公司' : '新增快递公司')
|
||||
const editorPermission = computed(() => form.id ? 'platform:express:edit' : 'platform:express:create')
|
||||
const displayedImportErrors = computed(() => importResult.value?.errors.slice(0, 100) || [])
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'express-company-editor',
|
||||
label: editorTitle,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission: editorPermission,
|
||||
})
|
||||
|
||||
watch(
|
||||
() => access.can(editorPermission.value),
|
||||
(canWrite) => {
|
||||
if (canWrite || !editorOpen.value) return
|
||||
editorOpen.value = false
|
||||
Object.assign(form, emptyForm())
|
||||
},
|
||||
{ flush: 'sync' },
|
||||
)
|
||||
|
||||
function optionalText(value: string | null) {
|
||||
const trimmed = value?.trim()
|
||||
return trimmed || null
|
||||
}
|
||||
|
||||
function safeHttpUrl(value: string | null) {
|
||||
if (!value) return null
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return ['http:', 'https:'].includes(url.protocol) ? url.toString() : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function formatUpdatedAt(value?: string | null) {
|
||||
return value?.replace('T', ' ').slice(0, 16) || '—'
|
||||
}
|
||||
|
||||
const expressCompanyColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 170, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'company', label: '快递公司', minWidth: 210, slotName: 'company' },
|
||||
{ prop: 'servicePhone', label: '客服电话', minWidth: 130, formatter: (row: PlatformExpressCompanyResource) => row.servicePhone || '—' },
|
||||
{ key: 'website', label: '官方网站', minWidth: 210, slotName: 'website' },
|
||||
{ key: 'trackingUrlTemplate', label: '轨迹查询模板', minWidth: 260, slotName: 'trackingUrlTemplate' },
|
||||
{ key: 'remark', label: '备注', minWidth: 200, slotName: 'remark' },
|
||||
{ prop: 'updatedAt', label: '更新时间', minWidth: 150, formatter: (row: PlatformExpressCompanyResource) => formatUpdatedAt(row.updatedAt) },
|
||||
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
|
||||
]
|
||||
|
||||
async function loadExpressCompanies() {
|
||||
const sequence = ++loadSequence
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const result = await listPlatformExpressCompanies(
|
||||
fixedTenantId,
|
||||
page.value,
|
||||
pageSize.value,
|
||||
appliedFilters.value.keyword,
|
||||
appliedFilters.value.status,
|
||||
)
|
||||
if (sequence !== loadSequence) return
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch (error) {
|
||||
if (sequence !== loadSequence) return
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
loadError.value = getApiErrorDetails(error, '快递公司加载失败,请稍后重试')
|
||||
} finally {
|
||||
if (sequence === loadSequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function applyFilters(model: QueryModel) {
|
||||
appliedFilters.value = {
|
||||
keyword: String(model.keyword || ''),
|
||||
status: (model.status || '') as PlatformExpressCompanyStatus | '',
|
||||
}
|
||||
if (page.value === 1) {
|
||||
void loadExpressCompanies()
|
||||
return
|
||||
}
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, emptyForm())
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
void formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
function assignEditor(row: PlatformExpressCompanyResource) {
|
||||
Object.assign(form, {
|
||||
id: String(row.id),
|
||||
companyCode: row.companyCode,
|
||||
companyName: row.companyName,
|
||||
servicePhone: row.servicePhone,
|
||||
website: row.website,
|
||||
trackingUrlTemplate: row.trackingUrlTemplate,
|
||||
status: row.status,
|
||||
remark: row.remark,
|
||||
})
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
void formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
async function openEdit(row: PlatformExpressCompanyResource) {
|
||||
const id = String(row.id)
|
||||
const pending = new Set(editLoadingIds.value)
|
||||
pending.add(id)
|
||||
editLoadingIds.value = pending
|
||||
try {
|
||||
assignEditor(await getPlatformExpressCompany(fixedTenantId, row.id))
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '快递公司详情加载失败,请稍后重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
const next = new Set(editLoadingIds.value)
|
||||
next.delete(id)
|
||||
editLoadingIds.value = next
|
||||
}
|
||||
}
|
||||
|
||||
function openImport() {
|
||||
importFile.value = null
|
||||
importResult.value = null
|
||||
importError.value = null
|
||||
if (fileInputRef.value) fileInputRef.value.value = ''
|
||||
importOpen.value = true
|
||||
}
|
||||
|
||||
function saveBlob(blob: Blob, fileName: string) {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = fileName
|
||||
anchor.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
async function downloadImportTemplate() {
|
||||
downloadingTemplate.value = true
|
||||
try {
|
||||
const blob = await downloadPlatformExpressCompanyImportTemplate()
|
||||
saveBlob(blob, '快递公司批量导入模板-v1.xlsx')
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '导入模板下载失败,请稍后重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
downloadingTemplate.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function selectImportFile(event: Event) {
|
||||
const file = (event.target as HTMLInputElement).files?.[0] || null
|
||||
importResult.value = null
|
||||
importError.value = null
|
||||
if (!file) {
|
||||
importFile.value = null
|
||||
return
|
||||
}
|
||||
if (!file.name.toLowerCase().endsWith('.xlsx')) {
|
||||
importFile.value = null
|
||||
ElMessage.error('请选择 .xlsx 格式的标准模板文件')
|
||||
if (fileInputRef.value) fileInputRef.value.value = ''
|
||||
return
|
||||
}
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
importFile.value = null
|
||||
ElMessage.error('导入文件不能超过 5MB')
|
||||
if (fileInputRef.value) fileInputRef.value.value = ''
|
||||
return
|
||||
}
|
||||
importFile.value = file
|
||||
}
|
||||
|
||||
async function submitImport() {
|
||||
if (!importFile.value) {
|
||||
ElMessage.warning('请先选择填写完成的 XLSX 文件')
|
||||
return
|
||||
}
|
||||
importing.value = true
|
||||
importError.value = null
|
||||
importResult.value = null
|
||||
try {
|
||||
const result = await importPlatformExpressCompanies(fixedTenantId, importFile.value)
|
||||
importResult.value = result
|
||||
if (result.success) {
|
||||
ElMessage.success(`成功导入 ${result.importedRows} 家快递公司`)
|
||||
importFile.value = null
|
||||
if (fileInputRef.value) fileInputRef.value.value = ''
|
||||
await loadExpressCompanies()
|
||||
}
|
||||
} catch (error) {
|
||||
importError.value = getApiErrorDetails(error, '快递公司导入失败,请稍后重试')
|
||||
} finally {
|
||||
importing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function downloadImportErrors() {
|
||||
if (!importResult.value?.errors.length) return
|
||||
const csvCell = (value: string | number) => `"${String(value).replaceAll('"', '""')}"`
|
||||
const lines = [
|
||||
['行号', '字段', '错误原因'].map(csvCell).join(','),
|
||||
...importResult.value.errors.map((item) => [item.row || '文件', item.field, item.message].map(csvCell).join(',')),
|
||||
]
|
||||
saveBlob(new Blob([`\ufeff${lines.join('\r\n')}`], { type: 'text/csv;charset=utf-8' }), '快递公司导入错误报告.csv')
|
||||
}
|
||||
|
||||
function buildPayload(): SavePlatformExpressCompanyRequest {
|
||||
return {
|
||||
companyCode: form.companyCode.trim(),
|
||||
companyName: form.companyName.trim(),
|
||||
servicePhone: optionalText(form.servicePhone),
|
||||
website: optionalText(form.website),
|
||||
trackingUrlTemplate: optionalText(form.trackingUrlTemplate),
|
||||
status: form.status,
|
||||
remark: optionalText(form.remark),
|
||||
}
|
||||
}
|
||||
|
||||
async function saveExpressCompany() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
saving.value = true
|
||||
try {
|
||||
const payload = buildPayload()
|
||||
if (form.id) await updatePlatformExpressCompany(fixedTenantId, form.id, payload)
|
||||
else await createPlatformExpressCompany(fixedTenantId, payload)
|
||||
editorOpen.value = false
|
||||
ElMessage.success(form.id ? '快递公司资料已更新' : '快递公司已创建')
|
||||
await loadExpressCompanies()
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '快递公司保存失败,请检查后重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(row: PlatformExpressCompanyResource) {
|
||||
const nextStatus: PlatformExpressCompanyStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
||||
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确定${action}“${row.companyName}”吗?${nextStatus === 'INACTIVE' ? '停用后不会再作为可用快递公司。' : ''}`,
|
||||
`${action}快递公司`,
|
||||
{ type: nextStatus === 'ACTIVE' ? 'success' : 'warning', confirmButtonText: `确认${action}`, cancelButtonText: '取消' },
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const id = String(row.id)
|
||||
const pending = new Set(statusLoadingIds.value)
|
||||
pending.add(id)
|
||||
statusLoadingIds.value = pending
|
||||
try {
|
||||
await changePlatformExpressCompanyStatus(fixedTenantId, row.id, nextStatus)
|
||||
ElMessage.success(`已${action}${row.companyName}`)
|
||||
await loadExpressCompanies()
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, `${action}快递公司失败`)
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
const next = new Set(statusLoadingIds.value)
|
||||
next.delete(id)
|
||||
statusLoadingIds.value = next
|
||||
}
|
||||
}
|
||||
|
||||
watch([page, pageSize], () => { void loadExpressCompanies() })
|
||||
|
||||
onMounted(() => {
|
||||
void loadExpressCompanies()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page express-company-page">
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
|
||||
<template #title>快递公司加载失败</template>
|
||||
<p>{{ loadError.message }}</p>
|
||||
<ApiErrorMeta :details="loadError" />
|
||||
<el-button size="small" @click="loadExpressCompanies">重新查询</el-button>
|
||||
</el-alert>
|
||||
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="快递公司筛选" :fields="queryFields" @search="applyFilters" />
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<div class="panel-heading">
|
||||
<div>
|
||||
<h2>快递公司列表</h2>
|
||||
<p>共 {{ total }} 家快递公司</p>
|
||||
</div>
|
||||
<div class="panel-actions">
|
||||
<el-button v-if="access.can('platform:express:import')" @click="openImport"><Upload :size="16" />批量导入</el-button>
|
||||
<el-button v-if="access.can('platform:express:create')" type="primary" @click="openCreate"><Plus :size="16" />新增快递公司</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<DataTable
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:data="rows"
|
||||
:columns="expressCompanyColumns"
|
||||
:loading="loading"
|
||||
:total="total"
|
||||
:page-sizes="[20, 50, 100]"
|
||||
aria-label="快递公司列表"
|
||||
row-key="id"
|
||||
:empty-text="appliedFilters.keyword.trim() || appliedFilters.status ? '暂无符合筛选条件的快递公司' : '暂无快递公司档案'"
|
||||
>
|
||||
<template #actions="{ row }">
|
||||
<div v-if="access.can('platform:express:edit') || access.can('platform:express:status')" class="table-actions">
|
||||
<el-button
|
||||
v-if="access.can('platform:express:edit')"
|
||||
link
|
||||
type="primary"
|
||||
:loading="editLoadingIds.has(String((row as PlatformExpressCompanyResource).id))"
|
||||
@click="openEdit(row as PlatformExpressCompanyResource)"
|
||||
><Pencil :size="15" />编辑</el-button>
|
||||
<el-button
|
||||
v-if="access.can('platform:express:status')"
|
||||
link
|
||||
:type="(row as PlatformExpressCompanyResource).status === 'ACTIVE' ? 'danger' : 'success'"
|
||||
:loading="statusLoadingIds.has(String((row as PlatformExpressCompanyResource).id))"
|
||||
@click="toggleStatus(row as PlatformExpressCompanyResource)"
|
||||
><Power :size="15" />{{ (row as PlatformExpressCompanyResource).status === 'ACTIVE' ? '停用' : '启用' }}</el-button>
|
||||
</div>
|
||||
<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 #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>
|
||||
</template>
|
||||
<template #trackingUrlTemplate="{ row }"><code class="tracking-template">{{ (row as PlatformExpressCompanyResource).trackingUrlTemplate || '—' }}</code></template>
|
||||
<template #remark="{ row }"><span class="remark-cell">{{ (row as PlatformExpressCompanyResource).remark || '—' }}</span></template>
|
||||
<template #status="{ row }"><el-tag :type="(row as PlatformExpressCompanyResource).status === 'ACTIVE' ? 'success' : 'info'" effect="light">{{ (row as PlatformExpressCompanyResource).status === 'ACTIVE' ? '启用' : '停用' }}</el-tag></template>
|
||||
<template #empty>
|
||||
<el-empty v-if="!loading" :description="appliedFilters.keyword.trim() || appliedFilters.status ? '暂无符合筛选条件的快递公司' : '暂无快递公司档案'">
|
||||
<el-button v-if="!appliedFilters.keyword.trim() && !appliedFilters.status && access.can('platform:express:create')" type="primary" @click="openCreate"><Plus :size="16" />新增第一家快递公司</el-button>
|
||||
</el-empty>
|
||||
</template>
|
||||
<template #pagination-left="{ total: tableTotal }"><span>共 {{ tableTotal }} 家快递公司</span></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-dialog
|
||||
v-model="importOpen"
|
||||
title="批量导入快递公司"
|
||||
width="min(680px, calc(100vw - 32px))"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!importing"
|
||||
:show-close="!importing"
|
||||
class="import-dialog"
|
||||
>
|
||||
<div class="import-flow">
|
||||
<section class="import-step">
|
||||
<div class="step-heading"><span>1</span><div><strong>下载标准模板</strong><p>请勿修改模板版本或表头,仅填写模板中的数据行。</p></div></div>
|
||||
<el-button :loading="downloadingTemplate" @click="downloadImportTemplate"><Download :size="16" />下载模板</el-button>
|
||||
</section>
|
||||
<section class="import-step">
|
||||
<div class="step-heading"><span>2</span><div><strong>选择填写后的文件</strong><p>仅支持 .xlsx,最大 5MB、1000 行;本期只新增,不更新已有档案。</p></div></div>
|
||||
<label class="file-picker" :class="{ disabled: importing }">
|
||||
<input ref="fileInputRef" type="file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" :disabled="importing" @change="selectImportFile" />
|
||||
<FileSpreadsheet :size="20" />
|
||||
<span>{{ importFile?.name || '选择 XLSX 文件' }}</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<el-alert type="info" :closable="false" show-icon title="整批校验通过后才会写入;任一行有误时整批不写入。" />
|
||||
<el-alert v-if="importError" type="error" :closable="false" show-icon title="导入请求失败">
|
||||
<p>{{ importError.message }}</p>
|
||||
<ApiErrorMeta :details="importError" />
|
||||
</el-alert>
|
||||
<el-alert v-if="importResult?.success" type="success" :closable="false" show-icon :title="`导入完成:成功新增 ${importResult.importedRows} 家快递公司`" />
|
||||
|
||||
<section v-if="importResult && !importResult.success" class="import-errors" aria-live="polite">
|
||||
<div class="error-heading">
|
||||
<div><strong>校验未通过,未写入任何数据</strong><p>发现 {{ importResult.errors.length }} 项问题,请修正后重新上传。</p></div>
|
||||
<el-button size="small" @click="downloadImportErrors"><Download :size="14" />下载错误报告</el-button>
|
||||
</div>
|
||||
<div class="error-list">
|
||||
<div v-for="(item, index) in displayedImportErrors" :key="`${item.row}-${item.field}-${index}`" class="error-item">
|
||||
<span>{{ item.row > 0 ? `第 ${item.row} 行` : '文件' }}</span>
|
||||
<strong>{{ item.field }}</strong>
|
||||
<p>{{ item.message }}</p>
|
||||
</div>
|
||||
<p v-if="importResult.errors.length > displayedImportErrors.length" class="error-overflow-note">
|
||||
仅展示前 {{ displayedImportErrors.length }} 项,完整内容请下载错误报告。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button :disabled="importing" @click="importOpen = false">关闭</el-button>
|
||||
<el-button type="primary" :loading="importing" :disabled="!importFile" @click="submitImport"><Upload :size="16" />开始导入</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="editorTitle" size="580px" class="business-drawer editor-drawer" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="drawer-form" :disabled="saving">
|
||||
<div class="form-section">
|
||||
<h3>公司标识</h3>
|
||||
<div class="form-grid two-cols">
|
||||
<el-form-item label="快递公司编码" prop="companyCode" required><el-input v-model.trim="form.companyCode" maxlength="50" placeholder="例如 SF" /></el-form-item>
|
||||
<el-form-item label="快递公司名称" prop="companyName" required><el-input v-model.trim="form.companyName" maxlength="128" placeholder="例如 顺丰速运" /></el-form-item>
|
||||
</div>
|
||||
<el-form-item label="状态" prop="status" required><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 class="form-section">
|
||||
<h3>服务与查询</h3>
|
||||
<div class="form-grid two-cols">
|
||||
<el-form-item label="客服电话"><el-input v-model.trim="form.servicePhone" maxlength="32" placeholder="例如 95338" /></el-form-item>
|
||||
<el-form-item label="官方网站" prop="website"><el-input v-model.trim="form.website" maxlength="255" placeholder="https://www.example.com" /></el-form-item>
|
||||
</div>
|
||||
<el-form-item label="轨迹查询地址模板"><el-input v-model.trim="form.trackingUrlTemplate" maxlength="500" placeholder="https://example.com/track/{trackingNo}" /></el-form-item>
|
||||
<p class="form-help">可使用 <code>{trackingNo}</code> 作为快递单号占位符;一期不包含轨迹订阅和自动回传。</p>
|
||||
</div>
|
||||
<div class="form-section"><h3>备注</h3><el-form-item label="内部说明"><el-input v-model.trim="form.remark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入适用范围、服务限制或其他说明" /></el-form-item></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button type="primary" :loading="saving" @click="saveExpressCompany">保存快递公司</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.state-alert p { margin: 6px 0 0; line-height: 1.55; }
|
||||
.state-alert .el-button { margin-top: 10px; }
|
||||
.express-company-cell { display: flex; min-width: 0; align-items: center; gap: 10px; }
|
||||
.express-company-cell > span { display: grid; width: 34px; height: 34px; flex: 0 0 34px; place-items: center; border-radius: 7px; background: #eef3fa; color: var(--cc-primary); }
|
||||
.express-company-cell > div { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
|
||||
.express-company-cell strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.express-company-cell small { color: var(--cc-muted); font-size: 11px; }
|
||||
.external-link { display: inline-flex; align-items: center; gap: 5px; color: var(--cc-primary); font-size: 12px; text-decoration: none; }
|
||||
.external-link:hover { text-decoration: underline; }
|
||||
.tracking-template { display: block; max-width: 100%; color: #475467; font-family: "Cascadia Code", Consolas, monospace; font-size: 11px; overflow-wrap: anywhere; }
|
||||
.remark-cell { display: -webkit-box; overflow: hidden; line-height: 1.5; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
||||
.form-help code { color: #475467; font-family: "Cascadia Code", Consolas, monospace; }
|
||||
.panel-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
|
||||
.panel-actions .el-button { margin-left: 0; }
|
||||
.import-flow { display: grid; gap: 16px; }
|
||||
.import-step { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 16px; border: 1px solid var(--cc-border); border-radius: 8px; background: #fafbfc; }
|
||||
.step-heading { display: flex; min-width: 0; align-items: flex-start; gap: 12px; }
|
||||
.step-heading > span { display: grid; width: 24px; height: 24px; flex: 0 0 24px; place-items: center; border-radius: 50%; background: var(--cc-primary); color: #fff; font-size: 12px; font-weight: 700; }
|
||||
.step-heading strong, .error-heading strong { color: var(--cc-text); font-size: 14px; }
|
||||
.step-heading p, .error-heading p { margin: 4px 0 0; color: var(--cc-muted); font-size: 12px; line-height: 1.55; }
|
||||
.file-picker { display: inline-flex; min-width: 180px; max-width: 260px; align-items: center; justify-content: center; gap: 8px; padding: 9px 14px; border: 1px solid var(--cc-border); border-radius: 6px; background: #fff; color: var(--cc-primary); cursor: pointer; }
|
||||
.file-picker:hover { border-color: var(--cc-primary); }
|
||||
.file-picker:focus-within { outline: 2px solid color-mix(in srgb, var(--cc-primary) 28%, transparent); outline-offset: 2px; }
|
||||
.file-picker.disabled { cursor: not-allowed; opacity: .6; }
|
||||
.file-picker input { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }
|
||||
.file-picker span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.import-flow .el-alert p { margin: 5px 0 0; }
|
||||
.import-errors { overflow: hidden; border: 1px solid #f4c7c7; border-radius: 8px; }
|
||||
.error-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 16px; background: #fff5f5; }
|
||||
.error-list { max-height: 220px; overflow: auto; }
|
||||
.error-item { display: grid; grid-template-columns: 72px 130px minmax(0, 1fr); gap: 10px; padding: 10px 16px; border-top: 1px solid #f4dddd; font-size: 12px; }
|
||||
.error-item span { color: #b42318; font-weight: 600; }
|
||||
.error-item p { margin: 0; overflow-wrap: anywhere; }
|
||||
.error-overflow-note { margin: 0; padding: 10px 16px; border-top: 1px solid #f4dddd; color: var(--cc-muted); font-size: 12px; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.panel-actions, .panel-actions .el-button { width: 100%; }
|
||||
.import-step, .error-heading { align-items: stretch; flex-direction: column; }
|
||||
.file-picker, .import-step > .el-button { width: 100%; max-width: none; }
|
||||
.error-item { grid-template-columns: 64px minmax(0, 1fr); }
|
||||
.error-item p { grid-column: 1 / -1; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const masterDataRoutes = [
|
||||
{
|
||||
path: 'master-data/express-companies',
|
||||
name: 'express-companies',
|
||||
component: () => import('@/modules/master-data/express-companies/pages/ExpressCompaniesView.vue'),
|
||||
meta: { title: '快递公司', description: '查询平台可用的快递公司档案与公开联系信息', permission: 'platform:express:list' },
|
||||
},
|
||||
{
|
||||
path: 'master-data/counterparties',
|
||||
name: 'counterparties',
|
||||
component: () => import('@/modules/master-data/counterparties/pages/PartnersView.vue'),
|
||||
meta: { title: '往来单位', description: '维护客户、供应商及客户/供应商双重类型单位档案', permission: 'platform:counterparty:list' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,92 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
changePlatformWarehouseStatus,
|
||||
createPlatformWarehouse,
|
||||
getPlatformWarehouse,
|
||||
listPlatformWarehouses,
|
||||
updatePlatformWarehouse,
|
||||
type SavePlatformWarehouseRequest,
|
||||
} from './platformWarehouses'
|
||||
|
||||
vi.mock('@/shared/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: '200', message: 'success', data: page })
|
||||
.mockResolvedValueOnce({ code: '200', 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: '200', message: 'success', data: '19001' })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
vi.mocked(http.patch).mockResolvedValue({ code: '200', 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 '@/shared/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)
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
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 '@/modules/warehouses/api/platformWarehouses'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import WarehousesView from './WarehousesView.vue'
|
||||
|
||||
vi.mock('@/modules/warehouses/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() {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = ['platform:warehouse:list', 'platform:warehouse:create', 'platform:warehouse:edit', 'platform:warehouse:status']
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
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('automatically loads the fixed 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')
|
||||
expect(wrapper.text()).not.toContain('全部收货仓')
|
||||
expect(wrapper.find('.query-toolbar').exists()).toBe(true)
|
||||
expect(wrapper.find('.data-table').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('updates filters locally and only reloads after search', async () => {
|
||||
const wrapper = await mountView()
|
||||
const keywordInput = wrapper.find('input[placeholder="仓库名称、编码、城市或地址"]')
|
||||
|
||||
await keywordInput.setValue('义乌')
|
||||
await flushPromises()
|
||||
expect(listPlatformWarehouses).toHaveBeenCalledTimes(1)
|
||||
|
||||
const searchButton = wrapper.findAll('button').find((button) => button.text().trim() === '查询')
|
||||
expect(searchButton).toBeDefined()
|
||||
await searchButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformWarehouses).toHaveBeenCalledTimes(2)
|
||||
expect(wrapper.text()).toContain('测试环境收货仓')
|
||||
})
|
||||
|
||||
it('does not render a tenant selector during the single-tenant phase', async () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.find('[aria-label="目标租户 ID"]').exists()).toBe(false)
|
||||
expect(wrapper.text()).not.toContain('查询仓库')
|
||||
expect(wrapper.text()).toContain('租户 10001')
|
||||
})
|
||||
|
||||
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: '托盘仓储' }))
|
||||
})
|
||||
|
||||
it('shows field-level required errors and does not submit an empty warehouse', async () => {
|
||||
const wrapper = await mountView()
|
||||
const createButton = wrapper.findAll('button').find((button) => button.text().trim() === '新增仓库')
|
||||
expect(createButton).toBeDefined()
|
||||
await createButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(document.querySelector('input[placeholder="例如 广东省"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="请输入仓库联系人姓名"]')).not.toBeNull()
|
||||
expect(document.querySelector('textarea[placeholder="请输入街道、园区、楼栋及库位信息"]')).not.toBeNull()
|
||||
|
||||
await wrapper.find('input[placeholder="例如 CN-NB-01"]').trigger('blur')
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.find('#warehouse-code-error').text()).toBe('请输入仓库编码')
|
||||
|
||||
const saveButton = wrapper.findAll('button').find((button) => button.text().trim() === '保存仓库')
|
||||
expect(saveButton).toBeDefined()
|
||||
await saveButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(createPlatformWarehouse).not.toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain('请输入仓库编码')
|
||||
expect(wrapper.text()).toContain('请输入仓库名称')
|
||||
expect(wrapper.text()).toContain('请输入城市')
|
||||
expect(wrapper.text()).toContain('请输入详细地址')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,431 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { MapPin, Pencil, Plus, Power, Warehouse as WarehouseIcon } from '@lucide/vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { getApiErrorDetails, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import {
|
||||
changePlatformWarehouseStatus,
|
||||
createPlatformWarehouse,
|
||||
getPlatformWarehouse,
|
||||
listPlatformWarehouses,
|
||||
updatePlatformWarehouse,
|
||||
type PlatformWarehouseDetailResource,
|
||||
type PlatformWarehouseResource,
|
||||
type SavePlatformWarehouseRequest,
|
||||
} from '@/modules/warehouses/api/platformWarehouses'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import type { Warehouse } from '@/modules/warehouses/types'
|
||||
|
||||
const fixedTenantId = 10001
|
||||
const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const saving = ref(false)
|
||||
const loading = ref(false)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const loadedTenantId = ref<number | null>(null)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const detailWarningCount = ref(0)
|
||||
const statusLoadingIds = ref(new Set<string>())
|
||||
type WarehouseFilters = QueryModel & { keyword: string; status: Warehouse['status'] | '' }
|
||||
const filters = ref<WarehouseFilters>({ keyword: '', status: '' })
|
||||
const appliedFilters = ref<WarehouseFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '仓库名称、编码、城市或地址' },
|
||||
{
|
||||
key: 'status', type: 'select', placeholder: '全部状态', options: [
|
||||
{ label: '启用', value: 'ACTIVE' },
|
||||
{ label: '停用', value: 'INACTIVE' },
|
||||
],
|
||||
},
|
||||
]
|
||||
let loadSequence = 0
|
||||
|
||||
interface WarehouseRow extends Warehouse {
|
||||
detail: PlatformWarehouseDetailResource | null
|
||||
}
|
||||
|
||||
const rows = ref<WarehouseRow[]>([])
|
||||
const warehouseColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 180, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'warehouse', label: '仓库', minWidth: 200, slotName: 'warehouse' },
|
||||
{ key: 'city', label: '所在城市', minWidth: 130, slotName: 'city' },
|
||||
{ key: 'address', label: '收货地址', minWidth: 260, slotName: 'address' },
|
||||
{ key: 'contact', label: '联系人', minWidth: 150, slotName: 'contact' },
|
||||
{ prop: 'businessHours', label: '收货时间', minWidth: 190, formatter: (row: WarehouseRow) => row.businessHours || '-' },
|
||||
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
|
||||
]
|
||||
|
||||
const emptyForm = (): Omit<Warehouse, 'updatedAt'> => ({
|
||||
id: '', code: '', name: '', province: '', city: '', address: '', contactName: '', contactPhone: '',
|
||||
businessHours: '周一至周六 08:30-18:00', status: 'ACTIVE', remark: '',
|
||||
})
|
||||
const form = reactive(emptyForm())
|
||||
type WarehouseRequiredField = 'code' | 'name' | 'city' | 'address'
|
||||
const requiredFieldMessages: Record<WarehouseRequiredField, string> = {
|
||||
code: '请输入仓库编码',
|
||||
name: '请输入仓库名称',
|
||||
city: '请输入城市',
|
||||
address: '请输入详细地址',
|
||||
}
|
||||
const formErrors = reactive<Record<WarehouseRequiredField, string>>({ code: '', name: '', city: '', address: '' })
|
||||
const editorLabel = computed(() => form.id ? '编辑收货仓' : '新增收货仓')
|
||||
const editorPermission = computed(() => form.id ? 'platform:warehouse:edit' : 'platform:warehouse:create')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'warehouse-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission: editorPermission,
|
||||
})
|
||||
|
||||
const warehouseReady = computed(() => loadedTenantId.value === fixedTenantId && !loading.value)
|
||||
const filteredRows = computed(() => rows.value.filter((warehouse) => {
|
||||
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
||||
const matchesKeyword = !keyword || [warehouse.code, warehouse.name, warehouse.province, warehouse.city, warehouse.address]
|
||||
.some((value) => value.toLowerCase().includes(keyword))
|
||||
return matchesKeyword && (!appliedFilters.value.status || warehouse.status === appliedFilters.value.status)
|
||||
}))
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
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(
|
||||
() => access.can(editorPermission.value),
|
||||
(canWrite) => {
|
||||
if (canWrite || !editorOpen.value) return
|
||||
editorOpen.value = false
|
||||
Object.assign(form, emptyForm())
|
||||
},
|
||||
{ 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 queryWarehouses(model: QueryModel) {
|
||||
appliedFilters.value = {
|
||||
keyword: String(model.keyword || ''),
|
||||
status: (model.status || '') as Warehouse['status'] | '',
|
||||
}
|
||||
page.value = 1
|
||||
void loadWarehouses()
|
||||
}
|
||||
|
||||
function clearWarehouseFormErrors() {
|
||||
for (const field of Object.keys(formErrors) as WarehouseRequiredField[]) formErrors[field] = ''
|
||||
}
|
||||
|
||||
function clearFieldError(field: WarehouseRequiredField) {
|
||||
if (formErrors[field]) formErrors[field] = ''
|
||||
}
|
||||
|
||||
function validateRequiredField(field: WarehouseRequiredField) {
|
||||
formErrors[field] = form[field].trim() ? '' : requiredFieldMessages[field]
|
||||
return !formErrors[field]
|
||||
}
|
||||
|
||||
function validateWarehouseForm() {
|
||||
return (Object.keys(requiredFieldMessages) as WarehouseRequiredField[])
|
||||
.map(validateRequiredField)
|
||||
.every(Boolean)
|
||||
}
|
||||
|
||||
async function loadWarehouses() {
|
||||
const sequence = ++loadSequence
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const result = await listPlatformWarehouses(fixedTenantId, 1, 200)
|
||||
const details = await Promise.allSettled(
|
||||
result.records.map((warehouse) => getPlatformWarehouse(fixedTenantId, 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 = fixedTenantId
|
||||
page.value = 1
|
||||
} catch (error) {
|
||||
if (sequence !== loadSequence) return
|
||||
loadError.value = getApiErrorDetails(error, '仓库数据加载失败,请稍后重试')
|
||||
} finally {
|
||||
if (sequence === loadSequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function requireCurrentTenant() {
|
||||
if (!warehouseReady.value) {
|
||||
ElMessage.warning('仓库数据尚未加载完成,请稍后重试')
|
||||
return null
|
||||
}
|
||||
return fixedTenantId
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
if (!requireCurrentTenant()) return
|
||||
Object.assign(form, emptyForm())
|
||||
clearWarehouseFormErrors()
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
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 || '',
|
||||
})
|
||||
clearWarehouseFormErrors()
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
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 (!validateWarehouseForm()) return
|
||||
saving.value = true
|
||||
try {
|
||||
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(successMessage)
|
||||
await loadWarehouses()
|
||||
} catch (error) {
|
||||
const details = getApiErrorDetails(error, '仓库保存失败,请检查后重试')
|
||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(warehouse: WarehouseRow) {
|
||||
const tenantId = requireCurrentTenant()
|
||||
if (!tenantId) return
|
||||
const target = warehouse.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
||||
const targetText = target === 'ACTIVE' ? '启用' : '停用'
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
target === 'INACTIVE'
|
||||
? `停用“${warehouse.name}”后,客户新建头程订单时将无法选择该仓库。`
|
||||
: `确认重新启用“${warehouse.name}”供客户下单选择吗?`,
|
||||
`${targetText}收货仓`,
|
||||
{ confirmButtonText: `确认${targetText}`, cancelButtonText: '取消', type: target === 'INACTIVE' ? 'warning' : 'info' },
|
||||
)
|
||||
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
|
||||
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(() => {
|
||||
void loadWarehouses()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<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>
|
||||
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="仓库筛选" :fields="queryFields" @search="queryWarehouses" />
|
||||
|
||||
<section class="surface-panel table-panel" aria-live="polite">
|
||||
<div class="panel-heading">
|
||||
<div>
|
||||
<h2>平台收货仓</h2>
|
||||
<p>租户 {{ fixedTenantId }} · 共 {{ filteredRows.length }} 个收货仓</p>
|
||||
</div>
|
||||
<el-button
|
||||
v-if="access.can('platform:warehouse:create')"
|
||||
type="primary"
|
||||
:disabled="!warehouseReady"
|
||||
@click="openCreate"
|
||||
><Plus :size="16" />新增仓库</el-button>
|
||||
</div>
|
||||
<DataTable
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:data="pagedRows"
|
||||
:columns="warehouseColumns"
|
||||
:loading="loading"
|
||||
:total="filteredRows.length"
|
||||
:page-sizes="[10, 20, 50]"
|
||||
row-key="id"
|
||||
aria-label="平台收货仓列表"
|
||||
:empty-text="loadedTenantId ? '暂无符合筛选条件的仓库' : '仓库数据暂不可用,请重新加载'"
|
||||
>
|
||||
<template #actions="{ row }">
|
||||
<div v-if="access.can('platform:warehouse:edit') || access.can('platform:warehouse:status')" class="table-actions">
|
||||
<el-button v-if="access.can('platform:warehouse:edit')" link type="primary" :disabled="!warehouseReady" @click="openEdit(row as WarehouseRow)"><Pencil :size="15" />编辑</el-button>
|
||||
<el-button
|
||||
v-if="access.can('platform:warehouse:status')"
|
||||
link
|
||||
:type="(row as WarehouseRow).status === 'ACTIVE' ? 'danger' : 'success'"
|
||||
:disabled="!warehouseReady"
|
||||
: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>
|
||||
<template #warehouse="{ 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>
|
||||
<template #city="{ row }">{{ [(row as WarehouseRow).province, (row as WarehouseRow).city].filter(Boolean).join(' · ') || '-' }}</template>
|
||||
<template #address="{ row }"><div class="warehouse-address"><MapPin :size="15" />{{ (row as WarehouseRow).address || '详情暂未加载' }}</div></template>
|
||||
<template #contact="{ row }"><strong>{{ (row as WarehouseRow).contactName || '-' }}</strong><span class="warehouse-subline">{{ (row as WarehouseRow).contactPhone || '-' }}</span></template>
|
||||
<template #status="{ row }"><el-tag :type="(row as WarehouseRow).status === 'ACTIVE' ? 'success' : 'info'" effect="light">{{ (row as WarehouseRow).status === 'ACTIVE' ? '启用' : '停用' }}</el-tag></template>
|
||||
<template #pagination-left>共 {{ filteredRows.length }} 个收货仓</template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="editorLabel" size="620px" class="business-drawer editor-drawer" :close-on-click-modal="false">
|
||||
<el-form :model="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 :class="{ 'has-field-error': formErrors.code }"><el-input v-model="form.code" maxlength="50" placeholder="例如 CN-NB-01" :aria-invalid="Boolean(formErrors.code)" :aria-describedby="formErrors.code ? 'warehouse-code-error' : undefined" @input="clearFieldError('code')" @blur="validateRequiredField('code')" /><p v-if="formErrors.code" id="warehouse-code-error" class="field-error" role="alert">{{ formErrors.code }}</p></el-form-item><el-form-item label="仓库名称" required :class="{ 'has-field-error': formErrors.name }"><el-input v-model="form.name" maxlength="120" placeholder="请输入客户下单时显示的名称" :aria-invalid="Boolean(formErrors.name)" :aria-describedby="formErrors.name ? 'warehouse-name-error' : undefined" @input="clearFieldError('name')" @blur="validateRequiredField('name')" /><p v-if="formErrors.name" id="warehouse-name-error" class="field-error" role="alert">{{ formErrors.name }}</p></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" placeholder="例如 广东省" /></el-form-item><el-form-item label="城市" required :class="{ 'has-field-error': formErrors.city }"><el-input v-model="form.city" maxlength="100" placeholder="例如 深圳市" :aria-invalid="Boolean(formErrors.city)" :aria-describedby="formErrors.city ? 'warehouse-city-error' : undefined" @input="clearFieldError('city')" @blur="validateRequiredField('city')" /><p v-if="formErrors.city" id="warehouse-city-error" class="field-error" role="alert">{{ formErrors.city }}</p></el-form-item><el-form-item label="联系人"><el-input v-model="form.contactName" maxlength="64" placeholder="请输入仓库联系人姓名" /></el-form-item><el-form-item label="联系电话"><el-input v-model="form.contactPhone" maxlength="32" placeholder="请输入手机号或固定电话" /></el-form-item><el-form-item label="收货时间"><el-input v-model="form.businessHours" maxlength="500" placeholder="例如 周一至周六 08:30-18:00" /></el-form-item></div><el-form-item label="详细地址" required :class="{ 'has-field-error': formErrors.address }"><el-input v-model="form.address" maxlength="255" type="textarea" :rows="3" placeholder="请输入街道、园区、楼栋及库位信息" :aria-invalid="Boolean(formErrors.address)" :aria-describedby="formErrors.address ? 'warehouse-address-error' : undefined" @input="clearFieldError('address')" @blur="validateRequiredField('address')" /><p v-if="formErrors.address" id="warehouse-address-error" class="field-error" role="alert">{{ formErrors.address }}</p></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 placeholder="例如 预约要求、进仓指引或其他注意事项" /></el-form-item></div>
|
||||
</el-form>
|
||||
<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>
|
||||
.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; overflow-wrap: anywhere; }
|
||||
.warehouse-address svg { flex: 0 0 15px; margin-top: 2px; color: var(--cc-muted); }
|
||||
.field-error { width: 100%; margin: 6px 0 0; color: var(--el-color-danger); font-size: 12px; line-height: 1.35; overflow-wrap: anywhere; }
|
||||
:deep(.has-field-error .el-input__wrapper) { box-shadow: 0 0 0 1px var(--el-color-danger) inset; }
|
||||
:deep(.has-field-error .el-textarea__inner) { box-shadow: 0 0 0 1px var(--el-color-danger) inset; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.panel-heading .el-button { width: 100%; }
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const warehouseRoutes = [
|
||||
{
|
||||
path: 'warehouses',
|
||||
name: 'warehouses',
|
||||
component: () => import('@/modules/warehouses/pages/WarehousesView.vue'),
|
||||
meta: { title: '仓库管理', description: '维护客户头程下单可选择的平台收货仓', permission: 'platform:warehouse:list' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,3 @@
|
||||
import type { PlatformReceivingWarehouse } from '@chongchong/shared'
|
||||
|
||||
export type Warehouse = PlatformReceivingWarehouse
|
||||
Reference in New Issue
Block a user