优化
This commit is contained in:
@@ -38,7 +38,7 @@
|
|||||||
- 当前登录和部分数据仍可能是模拟实现。接入 `services/api` 时删除对应模拟路径,不允许让生产逻辑静默回退到假数据。
|
- 当前登录和部分数据仍可能是模拟实现。接入 `services/api` 时删除对应模拟路径,不允许让生产逻辑静默回退到假数据。
|
||||||
- 删除、停用、改权限等高风险操作必须有明确确认、处理中、成功和失败反馈;失败时保留用户上下文,避免误以为已生效。
|
- 删除、停用、改权限等高风险操作必须有明确确认、处理中、成功和失败反馈;失败时保留用户上下文,避免误以为已生效。
|
||||||
- 日志、提示和示例数据不得包含真实账号、令牌、客户隐私或生产数据。
|
- 日志、提示和示例数据不得包含真实账号、令牌、客户隐私或生产数据。
|
||||||
- 一期 Admin 头程订单仅服务唯一已知租户,前端固定使用 `tenantId=10001` 并且不展示租户选择或录入控件;接口仍保留租户参数以保持后续多租户扩展口。多租户选择、切换和权限范围尚未实现,后续迭代开始前不得自行放开或从本地存储推断租户。
|
- Admin 维护企业所属仓库、往来单位、快递公司等主数据时,必须通过平台企业列表显式选择目标企业;不得从本地存储推断租户。默认可优先选择历史租户 `10001`(不存在时选择列表第一项),企业雪花 ID 必须按字符串透传,切换企业时不得保留上一企业的编辑、详情或导入上下文。
|
||||||
|
|
||||||
## UI 与交互
|
## UI 与交互
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ VITE_API_BASE_URL=/api
|
|||||||
API_PROXY_TARGET=http://8.163.30.128:9000
|
API_PROXY_TARGET=http://8.163.30.128:9000
|
||||||
```
|
```
|
||||||
|
|
||||||
认证请求使用 `/api/auth/**`,平台 IAM 请求使用 `/api/platform/v1/iam/**`。登录后从 JWT 读取平台身份和授权快照,再与 IAM 返回的启用权限资源取交集。企业审核调用 `/reviews`,打开审核详情后按租户调用 `/tenants/{tenantId}/qualifications`;营业执照通过 `/api/platform/v1/files/qualifications/{tenantId}/{fileName}` 携带平台 Token 临时读取,关闭预览后释放本地对象地址。审核通过新企业并由后端创建管理员时,页面必须展示不可通过遮罩、Esc 或关闭按钮跳过的一次性凭据弹窗,运营人员确认保存后才清除账号密码。平台角色查询、新增、编辑、启停、删除和权限全量保存均已按 `RbacController` 接入真实 `/roles` 契约,角色返回的 `permissionIds` 用于授权回显;系统内置角色及仍被成员使用的角色继续由服务端保护。权限资源查询和新增调用 `/permissions`,尚未提供的权限编辑、删除和启停不会模拟成功。一期真实权限资源只创建 `MENU` 与 `BUTTON`,不创建 `PAGE` 或 `API` 类型。其余业务页面需在对应服务契约确认后逐项替换,生产逻辑不得静默回退到模拟数据。
|
认证请求使用 `/api/auth/**`,平台 IAM 请求使用 `/api/platform/v1/iam/**`。登录后从 JWT 读取平台身份和授权快照,再与 IAM 返回的启用权限资源取交集。企业审核调用 `/reviews`,打开审核详情后按租户调用 `/tenants/{tenantId}/qualifications`;营业执照通过 `/api/platform/v1/files/qualifications/{tenantId}/{fileName}` 携带平台 Token 临时读取,关闭预览后释放本地对象地址。客户端自主注册企业审核通过后继续使用注册账号作为管理员,不展示新凭据;Admin 代建企业并由后端创建管理员时,页面必须展示不可通过遮罩、Esc 或关闭按钮跳过的一次性凭据弹窗,运营人员确认保存后才清除账号密码。平台角色查询、新增、编辑、启停、删除和权限全量保存均已按 `RbacController` 接入真实 `/roles` 契约,角色返回的 `permissionIds` 用于授权回显;系统内置角色及仍被成员使用的角色继续由服务端保护。权限资源查询和新增调用 `/permissions`,尚未提供的权限编辑、删除和启停不会模拟成功。一期真实权限资源只创建 `MENU` 与 `BUTTON`,不创建 `PAGE` 或 `API` 类型。其余业务页面需在对应服务契约确认后逐项替换,生产逻辑不得静默回退到模拟数据。
|
||||||
|
|
||||||
仓库管理已接入真实平台 Warehouse API,支持按租户筛选、详情、新增、编辑和启停,并在更新时保留后端返回的地址、能力和截单时间等完整字段。停用仓库保留历史数据,但不再提供给客户新建头程订单选择;订单详情使用下单时保存的仓库编码、名称和地址快照,仓库主数据后续修改不改变历史展示。本阶段不包含 FBA/海外目的仓、库存、库位或出入库作业。
|
仓库管理已接入真实平台 Warehouse API,支持按租户筛选、详情、新增、编辑和启停,并在更新时保留后端返回的地址、能力和截单时间等完整字段。停用仓库保留历史数据,但不再提供给客户新建头程订单选择;订单详情使用下单时保存的仓库编码、名称和地址快照,仓库主数据后续修改不改变历史展示。本阶段不包含 FBA/海外目的仓、库存、库位或出入库作业。
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
import { createPlatformExportTask } from '@/modules/downloads'
|
import { createPlatformExportTask } from '@/modules/downloads'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
import { useAuthStore } from '@/core/auth/auth'
|
||||||
|
import QueryToolbar from '@/shared/components/QueryToolbar.vue'
|
||||||
import CustomersView from './CustomersView.vue'
|
import CustomersView from './CustomersView.vue'
|
||||||
|
|
||||||
vi.mock('@/modules/iam', () => ({
|
vi.mock('@/modules/iam', () => ({
|
||||||
@@ -47,7 +48,7 @@ class ResizeObserverStub implements ResizeObserver {
|
|||||||
|
|
||||||
const fullTenant: PlatformTenantResource = {
|
const fullTenant: PlatformTenantResource = {
|
||||||
id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'PROFILE_REQUIRED',
|
id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'PROFILE_REQUIRED',
|
||||||
legalName: '柏悦物流有限公司', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
legalName: '柏悦物流有限公司', legalRepresentative: '张三', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
||||||
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com',
|
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com',
|
||||||
servicePackage: '基础版', contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30,
|
servicePackage: '基础版', contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30,
|
||||||
enterpriseType: '有限责任公司', establishedDate: '2020-01-01', registeredCapital: 1000,
|
enterpriseType: '有限责任公司', establishedDate: '2020-01-01', registeredCapital: 1000,
|
||||||
@@ -83,7 +84,7 @@ describe('CustomersView', () => {
|
|||||||
setActivePinia(pinia)
|
setActivePinia(pinia)
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
auth.token = 'token'
|
auth.token = 'token'
|
||||||
auth.permissions = ['platform:customer:list', 'platform:customer:view', 'platform:customer:edit', 'platform:customer:export']
|
auth.permissions = ['platform:customer:list', 'platform:customer:view', 'platform:customer:edit', 'platform:customer:export', 'platform:download:list']
|
||||||
useAccessPreviewStore().initializeAfterLogin()
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
vi.mocked(listPlatformTenants).mockResolvedValue({
|
vi.mocked(listPlatformTenants).mockResolvedValue({
|
||||||
records: [{ ...fullTenant, contactPhone: '138****8000', contactEmail: 'o***@example.com' }],
|
records: [{ ...fullTenant, contactPhone: '138****8000', contactEmail: 'o***@example.com' }],
|
||||||
@@ -132,6 +133,33 @@ describe('CustomersView', () => {
|
|||||||
expect(preview?.src).toBe('blob:qualification-preview')
|
expect(preview?.src).toBe('blob:qualification-preview')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('does not count rejected or superseded history as a current qualification when resubmitting', async () => {
|
||||||
|
const rejectedTenant = { ...fullTenant, status: 'REJECTED' }
|
||||||
|
vi.mocked(listPlatformTenants).mockResolvedValue({ records: [rejectedTenant], page: 1, size: 10, total: 1, pages: 1 })
|
||||||
|
vi.mocked(getPlatformTenant).mockResolvedValue(rejectedTenant)
|
||||||
|
vi.mocked(listTenantQualifications).mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'qualification-old', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
||||||
|
certificateNo: fullTenant.unifiedSocialCreditCode, documentUrl: '/files/old-license.png',
|
||||||
|
status: 'SUPERSEDED', reviewComment: '已替换', validTo: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'qualification-rejected', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
||||||
|
certificateNo: fullTenant.unifiedSocialCreditCode, documentUrl: '/files/rejected-license.png',
|
||||||
|
status: 'REJECTED', reviewComment: '请重新上传', validTo: null,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
tableButtonByText('编辑')?.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(document.querySelector('.qualification-label [aria-label="已上传"]')).toBeNull()
|
||||||
|
expect(document.querySelector('.qualification-file-name')?.textContent).toContain('未选择文件')
|
||||||
|
expect(downloadTenantQualification).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
it('shows uploaded qualifications in customer detail and opens the full preview', async () => {
|
it('shows uploaded qualifications in customer detail and opens the full preview', async () => {
|
||||||
vi.mocked(listTenantQualifications).mockResolvedValue([{
|
vi.mocked(listTenantQualifications).mockResolvedValue([{
|
||||||
id: 'qualification-1', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
id: 'qualification-1', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
||||||
@@ -154,6 +182,52 @@ describe('CustomersView', () => {
|
|||||||
expect(document.querySelector('.qualification-preview img[alt="license.png预览"]')).not.toBeNull()
|
expect(document.querySelector('.qualification-preview img[alt="license.png预览"]')).not.toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('does not let an older customer detail response overwrite a newer one', async () => {
|
||||||
|
const secondTenant = {
|
||||||
|
...fullTenant, id: '9', tenantCode: 'TEN9', tenantName: '第二家客户', legalName: '第二家客户有限公司',
|
||||||
|
}
|
||||||
|
vi.mocked(listPlatformTenants).mockResolvedValue({
|
||||||
|
records: [fullTenant, secondTenant], page: 1, size: 10, total: 2, pages: 1,
|
||||||
|
})
|
||||||
|
let resolveFirst!: (value: PlatformTenantResource) => void
|
||||||
|
let resolveSecond!: (value: PlatformTenantResource) => void
|
||||||
|
vi.mocked(getPlatformTenant)
|
||||||
|
.mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
|
||||||
|
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
|
||||||
|
|
||||||
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
const detailButtons = [...document.querySelectorAll<HTMLButtonElement>('.el-table__body button')]
|
||||||
|
.filter((button) => button.textContent?.trim() === '详情')
|
||||||
|
detailButtons[0]?.click()
|
||||||
|
detailButtons[1]?.click()
|
||||||
|
|
||||||
|
resolveSecond(secondTenant)
|
||||||
|
await flushPromises()
|
||||||
|
expect(document.querySelector('.customer-detail')?.textContent).toContain('第二家客户有限公司')
|
||||||
|
|
||||||
|
resolveFirst(fullTenant)
|
||||||
|
await flushPromises()
|
||||||
|
const detailText = document.querySelector('.customer-detail')?.textContent
|
||||||
|
expect(detailText).toContain('第二家客户有限公司')
|
||||||
|
expect(detailText).not.toContain('柏悦物流有限公司')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('labels replaced qualification history without presenting it as pending review', async () => {
|
||||||
|
vi.mocked(listTenantQualifications).mockResolvedValue([{
|
||||||
|
id: 'qualification-old', tenantId: fullTenant.id, qualificationType: 'BUSINESS_LICENSE',
|
||||||
|
certificateNo: fullTenant.unifiedSocialCreditCode, documentUrl: '/files/old-license.pdf',
|
||||||
|
status: 'SUPERSEDED', reviewComment: '已替换', validTo: null,
|
||||||
|
}])
|
||||||
|
|
||||||
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
tableButtonByText('详情')?.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(document.querySelector('.detail-qualification-meta .el-tag')?.textContent).toContain('已替换')
|
||||||
|
})
|
||||||
|
|
||||||
it('saves customer data and selected qualifications with one action', async () => {
|
it('saves customer data and selected qualifications with one action', async () => {
|
||||||
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
@@ -183,9 +257,12 @@ describe('CustomersView', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('submits the current filters to the backend export service without loading every customer page', async () => {
|
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] } })
|
const wrapper = mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
|
wrapper.findComponent(QueryToolbar).vm.$emit('update:modelValue', { keyword: ' Acme ', status: 'ACTIVE' })
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
|
||||||
const exportButton = [...document.querySelectorAll<HTMLButtonElement>('button')]
|
const exportButton = [...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
.find((button) => button.textContent?.trim() === '导出Excel')
|
.find((button) => button.textContent?.trim() === '导出Excel')
|
||||||
exportButton?.click()
|
exportButton?.click()
|
||||||
@@ -193,11 +270,35 @@ describe('CustomersView', () => {
|
|||||||
|
|
||||||
expect(createPlatformExportTask).toHaveBeenCalledWith({
|
expect(createPlatformExportTask).toHaveBeenCalledWith({
|
||||||
exportType: 'CUSTOMER_LIST', format: 'XLSX', taskName: '客户列表',
|
exportType: 'CUSTOMER_LIST', format: 'XLSX', taskName: '客户列表',
|
||||||
parameters: { keyword: undefined, status: undefined },
|
parameters: { keyword: 'Acme', status: 'ACTIVE' },
|
||||||
})
|
})
|
||||||
expect(listPlatformTenants).toHaveBeenCalledTimes(1)
|
expect(listPlatformTenants).toHaveBeenCalledTimes(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('hides customer export when the stable export permission is absent', async () => {
|
||||||
|
const auth = useAuthStore()
|
||||||
|
auth.permissions = ['platform:customer:list', 'platform:customer:view']
|
||||||
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect([...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.some((button) => button.textContent?.trim() === '导出Excel')).toBe(false)
|
||||||
|
expect(createPlatformExportTask).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not create an unrecoverable export for a role without download-center access', async () => {
|
||||||
|
const auth = useAuthStore()
|
||||||
|
auth.permissions = ['platform:customer:list', 'platform:customer:export']
|
||||||
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect([...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.some((button) => button.textContent?.trim() === '导出Excel')).toBe(false)
|
||||||
|
expect(createPlatformExportTask).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
it('approves a pending enterprise directly from the customer list', async () => {
|
it('approves a pending enterprise directly from the customer list', async () => {
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
auth.permissions = [...auth.permissions, 'platform:customer:review', 'platform:customer:approve']
|
auth.permissions = [...auth.permissions, 'platform:customer:review', 'platform:customer:approve']
|
||||||
@@ -228,6 +329,35 @@ describe('CustomersView', () => {
|
|||||||
expect(document.body.textContent).toContain('Temporary#2026')
|
expect(document.body.textContent).toContain('Temporary#2026')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keeps the client registration account as administrator after approval', async () => {
|
||||||
|
const auth = useAuthStore()
|
||||||
|
auth.permissions = [...auth.permissions, 'platform:customer:review', 'platform:customer:approve']
|
||||||
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
|
vi.mocked(listPlatformTenants).mockResolvedValue({
|
||||||
|
records: [{ ...fullTenant, status: 'PENDING' }], page: 1, size: 10, total: 1, pages: 1,
|
||||||
|
})
|
||||||
|
vi.mocked(listEnterpriseReviews).mockResolvedValue([pendingReview])
|
||||||
|
vi.mocked(approveEnterpriseReview).mockResolvedValue({
|
||||||
|
tenantId: fullTenant.id,
|
||||||
|
administratorCreated: false,
|
||||||
|
administratorUsername: null,
|
||||||
|
temporaryPassword: null,
|
||||||
|
})
|
||||||
|
|
||||||
|
mount(CustomersView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
tableButtonByText('通过')?.click()
|
||||||
|
await flushPromises()
|
||||||
|
;[...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find((button) => button.textContent?.trim() === '确认通过')?.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(approveEnterpriseReview).toHaveBeenCalledWith(pendingReview.id, '企业资料与必填资质完整、清晰,审核通过')
|
||||||
|
expect(rejectEnterpriseReview).not.toHaveBeenCalled()
|
||||||
|
expect(document.body.textContent).toContain('注册账号继续作为企业管理员')
|
||||||
|
expect(document.body.textContent).not.toContain('请立即保存以下一次性凭证')
|
||||||
|
})
|
||||||
|
|
||||||
it('keeps review-only roles on the merged customer page without calling the customer list endpoint', async () => {
|
it('keeps review-only roles on the merged customer page without calling the customer list endpoint', async () => {
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
auth.permissions = ['platform:customer:review', 'platform:customer:approve']
|
auth.permissions = ['platform:customer:review', 'platform:customer:approve']
|
||||||
|
|||||||
@@ -105,7 +105,7 @@ const queryFields: QueryField[] = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
const emptyForm = (): CreatePlatformTenantRequest => ({
|
const emptyForm = (): CreatePlatformTenantRequest => ({
|
||||||
tenantName: '', legalName: '', unifiedSocialCreditCode: '', contactName: '', contactPhone: '',
|
tenantName: '', legalName: '', legalRepresentative: '', unifiedSocialCreditCode: '', contactName: '', contactPhone: '',
|
||||||
contactEmail: '', contactWechat: '', servicePackage: '基础版', salesOwnerName: '', paymentTermDays: 0,
|
contactEmail: '', contactWechat: '', servicePackage: '基础版', salesOwnerName: '', paymentTermDays: 0,
|
||||||
enterpriseType: '', establishedDate: null, registeredCapital: null, registeredCapitalCurrency: 'CNY',
|
enterpriseType: '', establishedDate: null, registeredCapital: null, registeredCapitalCurrency: 'CNY',
|
||||||
registeredAddress: '', internalRemark: '',
|
registeredAddress: '', internalRemark: '',
|
||||||
@@ -114,6 +114,7 @@ const form = ref(emptyForm())
|
|||||||
const rules: FormRules = {
|
const rules: FormRules = {
|
||||||
tenantName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
|
tenantName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
|
||||||
legalName: [{ required: true, message: '请输入营业执照上的企业名称', trigger: 'blur' }],
|
legalName: [{ required: true, message: '请输入营业执照上的企业名称', trigger: 'blur' }],
|
||||||
|
legalRepresentative: [{ required: true, message: '请输入法定代表人姓名', trigger: 'blur' }],
|
||||||
unifiedSocialCreditCode: [
|
unifiedSocialCreditCode: [
|
||||||
{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
|
{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
|
||||||
{ pattern: /^[0-9A-Z]{18}$/, message: '请输入 18 位大写字母或数字', trigger: 'blur' },
|
{ pattern: /^[0-9A-Z]{18}$/, message: '请输入 18 位大写字母或数字', trigger: 'blur' },
|
||||||
@@ -174,6 +175,8 @@ const customerColumns: DataTableColumn[] = [
|
|||||||
|
|
||||||
let loadSequence = 0
|
let loadSequence = 0
|
||||||
let reviewLoadSequence = 0
|
let reviewLoadSequence = 0
|
||||||
|
let editorLoadSequence = 0
|
||||||
|
let detailLoadSequence = 0
|
||||||
const editorTitle = computed(() => editingId.value ? '编辑客户' : '新增客户')
|
const editorTitle = computed(() => editingId.value ? '编辑客户' : '新增客户')
|
||||||
const canUploadQualifications = computed(() => !editorStatus.value || ['PROFILE_REQUIRED', 'REJECTED'].includes(editorStatus.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 canSubmitReview = computed(() => Boolean(editingId.value) && ['PROFILE_REQUIRED', 'REJECTED'].includes(editorStatus.value || ''))
|
||||||
@@ -191,6 +194,13 @@ function statusMeta(status: PlatformTenantStatus) {
|
|||||||
return { label: '已停用', type: 'info' as const }
|
return { label: '已停用', type: 'info' as const }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function qualificationStatusMeta(status: PlatformTenantQualification['status']) {
|
||||||
|
if (status === 'APPROVED') return { label: '已通过', type: 'success' as const }
|
||||||
|
if (status === 'REJECTED') return { label: '已驳回', type: 'danger' as const }
|
||||||
|
if (status === 'SUPERSEDED') return { label: '已替换', type: 'info' as const }
|
||||||
|
return { label: '待审核', type: 'warning' as const }
|
||||||
|
}
|
||||||
|
|
||||||
async function loadPendingReviews() {
|
async function loadPendingReviews() {
|
||||||
const sequence = ++reviewLoadSequence
|
const sequence = ++reviewLoadSequence
|
||||||
if (!access.can('platform:customer:review')) {
|
if (!access.can('platform:customer:review')) {
|
||||||
@@ -227,6 +237,7 @@ function reviewToCustomer(review: EnterpriseReview): PlatformTenantResource {
|
|||||||
tenantName: review.tenantName?.trim() || `待审核企业(${tenantId})`,
|
tenantName: review.tenantName?.trim() || `待审核企业(${tenantId})`,
|
||||||
status: 'PENDING',
|
status: 'PENDING',
|
||||||
legalName: null,
|
legalName: null,
|
||||||
|
legalRepresentative: null,
|
||||||
unifiedSocialCreditCode: null,
|
unifiedSocialCreditCode: null,
|
||||||
contactName: review.contactName ?? null,
|
contactName: review.contactName ?? null,
|
||||||
contactPhone: review.contactPhone ?? null,
|
contactPhone: review.contactPhone ?? null,
|
||||||
@@ -308,12 +319,13 @@ function resetEditor() {
|
|||||||
form.value = emptyForm(); qualifications.value = newQualificationDrafts(); qualificationLoadError.value = ''; savedFormSnapshot.value = ''
|
form.value = emptyForm(); qualifications.value = newQualificationDrafts(); qualificationLoadError.value = ''; savedFormSnapshot.value = ''
|
||||||
}
|
}
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
|
editorLoadSequence += 1
|
||||||
editingId.value = null; editorStatus.value = null; resetEditor(); editorOpen.value = true
|
editingId.value = null; editorStatus.value = null; resetEditor(); editorOpen.value = true
|
||||||
nextTick(() => formRef.value?.clearValidate())
|
nextTick(() => formRef.value?.clearValidate())
|
||||||
}
|
}
|
||||||
function mapTenantToForm(row: PlatformTenantResource): CreatePlatformTenantRequest {
|
function mapTenantToForm(row: PlatformTenantResource): CreatePlatformTenantRequest {
|
||||||
return {
|
return {
|
||||||
tenantName: row.tenantName, legalName: row.legalName || '', unifiedSocialCreditCode: row.unifiedSocialCreditCode || '',
|
tenantName: row.tenantName, legalName: row.legalName || '', legalRepresentative: row.legalRepresentative || '', unifiedSocialCreditCode: row.unifiedSocialCreditCode || '',
|
||||||
contactName: row.contactName || '', contactPhone: row.contactPhone || '', contactEmail: row.contactEmail || '',
|
contactName: row.contactName || '', contactPhone: row.contactPhone || '', contactEmail: row.contactEmail || '',
|
||||||
contactWechat: row.contactWechat || '', servicePackage: row.servicePackage || '基础版', salesOwnerName: row.salesOwnerName || '',
|
contactWechat: row.contactWechat || '', servicePackage: row.servicePackage || '基础版', salesOwnerName: row.salesOwnerName || '',
|
||||||
paymentTermDays: Number(row.paymentTermDays ?? 0), enterpriseType: row.enterpriseType || '', establishedDate: row.establishedDate || null,
|
paymentTermDays: Number(row.paymentTermDays ?? 0), enterpriseType: row.enterpriseType || '', establishedDate: row.establishedDate || null,
|
||||||
@@ -322,12 +334,16 @@ function mapTenantToForm(row: PlatformTenantResource): CreatePlatformTenantReque
|
|||||||
internalRemark: row.internalRemark || '',
|
internalRemark: row.internalRemark || '',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function loadEditorQualifications(tenantId: number | string) {
|
async function loadEditorQualifications(tenantId: number | string, sequence = editorLoadSequence) {
|
||||||
qualificationLoadError.value = ''
|
qualificationLoadError.value = ''
|
||||||
try {
|
try {
|
||||||
const records = await listTenantQualifications(tenantId)
|
const records = await listTenantQualifications(tenantId)
|
||||||
|
if (sequence !== editorLoadSequence || !editorOpen.value || editingId.value !== String(tenantId)) return
|
||||||
|
const acceptedStatus = ['ACTIVE', 'DISABLED'].includes(editorStatus.value || '') ? 'APPROVED' : 'PENDING'
|
||||||
for (const draft of qualifications.value) {
|
for (const draft of qualifications.value) {
|
||||||
const item = [...records].reverse().find((record) => record.qualificationType === draft.type && record.status !== 'REJECTED')
|
const item = [...records].reverse().find((record) => (
|
||||||
|
record.qualificationType === draft.type && record.status === acceptedStatus
|
||||||
|
))
|
||||||
if (item) {
|
if (item) {
|
||||||
draft.uploaded = true
|
draft.uploaded = true
|
||||||
draft.validTo = item.validTo || ''
|
draft.validTo = item.validTo || ''
|
||||||
@@ -341,21 +357,23 @@ async function loadEditorQualifications(tenantId: number | string) {
|
|||||||
} catch (error) { qualificationLoadError.value = getApiErrorMessage(error, '资质信息加载失败,可稍后重试') }
|
} catch (error) { qualificationLoadError.value = getApiErrorMessage(error, '资质信息加载失败,可稍后重试') }
|
||||||
}
|
}
|
||||||
async function openEdit(row: PlatformTenantResource) {
|
async function openEdit(row: PlatformTenantResource) {
|
||||||
editingId.value = String(row.id); editorStatus.value = row.status; resetEditor(); form.value = mapTenantToForm(row)
|
const id = String(row.id)
|
||||||
|
const sequence = ++editorLoadSequence
|
||||||
|
editingId.value = id; editorStatus.value = row.status; resetEditor(); form.value = mapTenantToForm(row)
|
||||||
editorOpen.value = true; editorLoading.value = true
|
editorOpen.value = true; editorLoading.value = true
|
||||||
try {
|
try {
|
||||||
const tenant = await getPlatformTenant(row.id)
|
const tenant = await getPlatformTenant(row.id)
|
||||||
if (editingId.value !== String(row.id)) return
|
if (sequence !== editorLoadSequence || editingId.value !== id || !editorOpen.value) return
|
||||||
editorStatus.value = tenant.status
|
editorStatus.value = tenant.status
|
||||||
form.value = mapTenantToForm(tenant)
|
form.value = mapTenantToForm(tenant)
|
||||||
savedFormSnapshot.value = JSON.stringify(form.value)
|
savedFormSnapshot.value = JSON.stringify(form.value)
|
||||||
await loadEditorQualifications(row.id)
|
await loadEditorQualifications(row.id, sequence)
|
||||||
await nextTick(() => formRef.value?.clearValidate())
|
await nextTick(() => formRef.value?.clearValidate())
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (editingId.value === String(row.id)) editorOpen.value = false
|
if (sequence === editorLoadSequence && editingId.value === id) editorOpen.value = false
|
||||||
ElMessage.error(getApiErrorMessage(error, '客户完整资料加载失败,请稍后重试'))
|
ElMessage.error(getApiErrorMessage(error, '客户完整资料加载失败,请稍后重试'))
|
||||||
} finally {
|
} finally {
|
||||||
if (editingId.value === String(row.id)) editorLoading.value = false
|
if (sequence === editorLoadSequence && editingId.value === id) editorLoading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -367,7 +385,7 @@ function selectQualificationFile(event: Event, draft: QualificationDraft) {
|
|||||||
const extensionValid = /\.(pdf|jpe?g|png)$/i.test(file.name)
|
const extensionValid = /\.(pdf|jpe?g|png)$/i.test(file.name)
|
||||||
const mimeValid = ['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)
|
const mimeValid = ['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)
|
||||||
if (!extensionValid || !mimeValid) { draft.error = '仅支持 PDF、JPG、PNG 文件'; input.value = ''; return }
|
if (!extensionValid || !mimeValid) { draft.error = '仅支持 PDF、JPG、PNG 文件'; input.value = ''; return }
|
||||||
if (file.size > 10 * 1024 * 1024) { draft.error = '单个文件不能超过 10MB'; input.value = ''; return }
|
if (file.size > 5 * 1024 * 1024) { draft.error = '单个文件不能超过 5MB'; input.value = ''; return }
|
||||||
draft.file = file
|
draft.file = file
|
||||||
draft.previewKind = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
draft.previewKind = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf') ? 'pdf' : 'image'
|
||||||
draft.previewUrl = URL.createObjectURL(file)
|
draft.previewUrl = URL.createObjectURL(file)
|
||||||
@@ -545,10 +563,13 @@ async function submitReview() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function showDetail(row: PlatformTenantResource) {
|
async function showDetail(row: PlatformTenantResource) {
|
||||||
|
const sequence = ++detailLoadSequence
|
||||||
|
const rowId = String(row.id)
|
||||||
clearDetailQualificationPreviews()
|
clearDetailQualificationPreviews()
|
||||||
detail.value = row; detailQualifications.value = []; detailOpen.value = true; detailLoading.value = true
|
detail.value = row; detailQualifications.value = []; detailOpen.value = true; detailLoading.value = true
|
||||||
try {
|
try {
|
||||||
const [tenant, records] = await Promise.all([getPlatformTenant(row.id), listTenantQualifications(row.id)])
|
const [tenant, records] = await Promise.all([getPlatformTenant(row.id), listTenantQualifications(row.id)])
|
||||||
|
if (sequence !== detailLoadSequence || !detailOpen.value || String(detail.value?.id) !== rowId) return
|
||||||
detail.value = tenant
|
detail.value = tenant
|
||||||
detailQualifications.value = records
|
detailQualifications.value = records
|
||||||
detailQualificationPreviews.value = Object.fromEntries(records.map((item) => {
|
detailQualificationPreviews.value = Object.fromEntries(records.map((item) => {
|
||||||
@@ -558,8 +579,11 @@ async function showDetail(row: PlatformTenantResource) {
|
|||||||
for (const item of records) {
|
for (const item of records) {
|
||||||
if (detailQualificationPreviews.value[String(item.id)]?.kind === 'image') void loadDetailQualificationPreview(item, false)
|
if (detailQualificationPreviews.value[String(item.id)]?.kind === 'image') void loadDetailQualificationPreview(item, false)
|
||||||
}
|
}
|
||||||
} catch (error) { ElMessage.error(getApiErrorMessage(error, '客户详情加载失败')) }
|
} catch (error) {
|
||||||
finally { detailLoading.value = false }
|
if (sequence === detailLoadSequence) ElMessage.error(getApiErrorMessage(error, '客户详情加载失败'))
|
||||||
|
} finally {
|
||||||
|
if (sequence === detailLoadSequence) detailLoading.value = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
async function toggleStatus(row: PlatformTenantResource) {
|
async function toggleStatus(row: PlatformTenantResource) {
|
||||||
const next = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'; const verb = next === 'ACTIVE' ? '启用' : '停用'
|
const next = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'; const verb = next === 'ACTIVE' ? '启用' : '停用'
|
||||||
@@ -601,7 +625,12 @@ async function submitDecision() {
|
|||||||
}
|
}
|
||||||
decisionOpen.value = false
|
decisionOpen.value = false
|
||||||
detailOpen.value = false
|
detailOpen.value = false
|
||||||
ElMessage.success(decision.type === 'approve' ? '企业资料已审核通过' : '企业资料已驳回')
|
const successMessage = decision.type === 'reject'
|
||||||
|
? '企业资料已驳回'
|
||||||
|
: approved?.administratorCreated
|
||||||
|
? '企业资料已审核通过,管理员账号已创建'
|
||||||
|
: '企业资料已审核通过,注册账号继续作为企业管理员'
|
||||||
|
ElMessage.success(successMessage)
|
||||||
if (approved?.administratorCreated) {
|
if (approved?.administratorCreated) {
|
||||||
approvalResult.value = approved
|
approvalResult.value = approved
|
||||||
approvalResultOpen.value = true
|
approvalResultOpen.value = true
|
||||||
@@ -637,8 +666,18 @@ async function exportCustomers() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
watch([page, pageSize], () => { void loadCustomers() })
|
watch([page, pageSize], () => { void loadCustomers() })
|
||||||
watch(editorOpen, (open) => { if (!open) clearQualificationPreviews() })
|
watch(editorOpen, (open) => {
|
||||||
watch(detailOpen, (open) => { if (!open) clearDetailQualificationPreviews() })
|
if (!open) {
|
||||||
|
editorLoadSequence += 1
|
||||||
|
clearQualificationPreviews()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
watch(detailOpen, (open) => {
|
||||||
|
if (!open) {
|
||||||
|
detailLoadSequence += 1
|
||||||
|
clearDetailQualificationPreviews()
|
||||||
|
}
|
||||||
|
})
|
||||||
watch(
|
watch(
|
||||||
() => [access.can('platform:customer:approve'), access.can('platform:customer:reject')],
|
() => [access.can('platform:customer:approve'), access.can('platform:customer:reject')],
|
||||||
([canApprove, canReject]) => {
|
([canApprove, canReject]) => {
|
||||||
@@ -655,7 +694,7 @@ onMounted(loadCustomers)
|
|||||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="客户筛选" :fields="queryFields" @search="applyFilters" />
|
<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-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">
|
<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>
|
<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') && access.can('platform:download:list')" :loading="exportSubmitting" :disabled="loading || exportSubmitting" @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>
|
||||||
<div v-if="reviewLoadError" class="review-sync-error" role="alert"><div><ShieldX :size="17" /><span>{{ reviewLoadError.message }}</span></div><el-button link type="primary" @click="reloadPendingReviews">重新加载待审核客户</el-button></div>
|
<div v-if="reviewLoadError" class="review-sync-error" role="alert"><div><ShieldX :size="17" /><span>{{ reviewLoadError.message }}</span></div><el-button link type="primary" @click="reloadPendingReviews">重新加载待审核客户</el-button></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="暂无符合筛选条件的客户">
|
<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="pendingReviewByTenantId.has(String((row as PlatformTenantResource).id)) && access.can('platform:customer:approve')" link type="success" :disabled="reviewSubmitting" @click="openDecision(row as PlatformTenantResource, 'approve')"><ShieldCheck :size="15" />通过</el-button><el-button v-if="pendingReviewByTenantId.has(String((row as PlatformTenantResource).id)) && access.can('platform:customer:reject')" link type="danger" :disabled="reviewSubmitting" @click="openDecision(row as PlatformTenantResource, 'reject')"><ShieldX :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 #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="pendingReviewByTenantId.has(String((row as PlatformTenantResource).id)) && access.can('platform:customer:approve')" link type="success" :disabled="reviewSubmitting" @click="openDecision(row as PlatformTenantResource, 'approve')"><ShieldCheck :size="15" />通过</el-button><el-button v-if="pendingReviewByTenantId.has(String((row as PlatformTenantResource).id)) && access.can('platform:customer:reject')" link type="danger" :disabled="reviewSubmitting" @click="openDecision(row as PlatformTenantResource, 'reject')"><ShieldX :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>
|
||||||
@@ -670,6 +709,7 @@ onMounted(loadCustomers)
|
|||||||
<div class="form-section"><h3>基础资料</h3><div class="form-grid two-cols">
|
<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="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="legalName" required><el-input v-model="form.legalName" placeholder="请输入营业执照上的企业名称" maxlength="128" /></el-form-item>
|
||||||
|
<el-form-item label="法定代表人" prop="legalRepresentative" required><el-input v-model="form.legalRepresentative" placeholder="请输入法定代表人姓名" maxlength="64" /></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="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="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="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>
|
||||||
@@ -703,7 +743,7 @@ onMounted(loadCustomers)
|
|||||||
<div role="cell"><el-date-picker v-model="draft.validTo" type="date" value-format="YYYY-MM-DD" placeholder="请选择有效期" :disabled="!canUploadQualifications || draft.uploaded" /></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>
|
||||||
</div>
|
</div>
|
||||||
<p class="qualification-hint">支持 PDF、JPG、PNG,单个文件不超过 10MB;<span>*</span> 为提交审核必填项。</p>
|
<p class="qualification-hint">支持 PDF、JPG、PNG,单个文件不超过 5MB;<span>*</span> 为提交审核必填项。</p>
|
||||||
</div>
|
</div>
|
||||||
</el-form>
|
</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>
|
<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>
|
||||||
@@ -740,6 +780,8 @@ onMounted(loadCustomers)
|
|||||||
<section class="customer-detail-section" aria-labelledby="customer-profile-heading">
|
<section class="customer-detail-section" aria-labelledby="customer-profile-heading">
|
||||||
<h4 id="customer-profile-heading">企业资料</h4>
|
<h4 id="customer-profile-heading">企业资料</h4>
|
||||||
<dl class="customer-detail-grid">
|
<dl class="customer-detail-grid">
|
||||||
|
<div class="customer-detail-item is-wide"><dt>营业执照企业名称</dt><dd>{{ displayText(detail.legalName) }}</dd></div>
|
||||||
|
<div class="customer-detail-item"><dt>法定代表人</dt><dd>{{ displayText(detail.legalRepresentative) }}</dd></div>
|
||||||
<div class="customer-detail-item is-wide"><dt>统一社会信用代码</dt><dd>{{ displayText(detail.unifiedSocialCreditCode) }}</dd></div>
|
<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.contactName) }}</dd></div>
|
||||||
<div class="customer-detail-item"><dt>联系电话</dt><dd>{{ displayText(detail.contactPhone) }}</dd></div>
|
<div class="customer-detail-item"><dt>联系电话</dt><dd>{{ displayText(detail.contactPhone) }}</dd></div>
|
||||||
@@ -763,7 +805,7 @@ onMounted(loadCustomers)
|
|||||||
<small v-if="detailQualificationPreviews[String(item.id)]?.kind === 'pdf'">PDF</small>
|
<small v-if="detailQualificationPreviews[String(item.id)]?.kind === 'pdf'">PDF</small>
|
||||||
</span>
|
</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-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>
|
<span class="detail-qualification-meta"><el-tag :type="qualificationStatusMeta(item.status).type" size="small" effect="light">{{ qualificationStatusMeta(item.status).label }}</el-tag><span><Eye :size="14" />{{ detailQualificationPreviews[String(item.id)]?.loading ? '读取中' : (detailQualificationPreviews[String(item.id)]?.failed ? '重试' : '查看') }}</span></span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="detail-empty-qualification"><FileCheck2 :size="20" /><span>暂未上传资质文件</span></div>
|
<div v-else class="detail-empty-qualification"><FileCheck2 :size="20" /><span>暂未上传资质文件</span></div>
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { http } from '@/shared/api/http'
|
import { ApiResponseError, http } from '@/shared/api/http'
|
||||||
import {
|
import {
|
||||||
createPlatformExportTask,
|
createPlatformExportTask,
|
||||||
downloadPlatformExportTask,
|
downloadPlatformExportTask,
|
||||||
|
getPlatformExportTask,
|
||||||
listPlatformExportTasks,
|
listPlatformExportTasks,
|
||||||
retryPlatformExportTask,
|
retryPlatformExportTask,
|
||||||
} from './platformExportTasks'
|
} from './platformExportTasks'
|
||||||
@@ -24,18 +25,97 @@ describe('platformExportTasks', () => {
|
|||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks', payload)
|
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks', payload)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('lists, downloads, and retries export tasks through File service', async () => {
|
it('lists, reads, downloads, and retries export tasks through File service', async () => {
|
||||||
const page = { records: [], page: '1', size: '20', total: '0', pages: '0' }
|
const page = { records: [], page: '1', size: '20', total: '0', pages: '0' }
|
||||||
|
const task = { id: '9', status: 'SUCCEEDED' }
|
||||||
const blob = new Blob(['xlsx'])
|
const blob = new Blob(['xlsx'])
|
||||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', message: 'success', data: page }).mockResolvedValueOnce(blob)
|
vi.mocked(http.get)
|
||||||
|
.mockResolvedValueOnce({ code: '200', message: 'success', data: page })
|
||||||
|
.mockResolvedValueOnce({ code: '200', message: 'success', data: task })
|
||||||
|
.mockResolvedValueOnce(blob)
|
||||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '9', status: 'PENDING' } })
|
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(listPlatformExportTasks({ page: 1, size: 20, status: 'FAILED' })).resolves.toEqual({ records: [], page: 1, size: 20, total: 0, pages: 0 })
|
||||||
|
await expect(getPlatformExportTask('9')).resolves.toEqual(task)
|
||||||
await expect(downloadPlatformExportTask('9')).resolves.toBe(blob)
|
await expect(downloadPlatformExportTask('9')).resolves.toBe(blob)
|
||||||
await expect(retryPlatformExportTask('9')).resolves.toMatchObject({ id: '9', status: 'PENDING' })
|
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(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.get).toHaveBeenNthCalledWith(2, '/platform/v1/files/export-tasks/9')
|
||||||
|
expect(http.get).toHaveBeenNthCalledWith(3, '/platform/v1/files/export-tasks/9/download', { responseType: 'blob', timeout: 600_000 })
|
||||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks/9/retry', {})
|
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks/9/retry', {})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('parses a Blob error envelope and preserves backend trace metadata', async () => {
|
||||||
|
vi.mocked(http.get).mockRejectedValue({
|
||||||
|
isAxiosError: true,
|
||||||
|
response: {
|
||||||
|
status: 410,
|
||||||
|
data: new Blob([JSON.stringify({
|
||||||
|
code: 'FILE_EXPIRED', message: '导出文件已过期', data: null,
|
||||||
|
requestId: 'request-download-1', traceId: 'trace-download-1',
|
||||||
|
})], { type: 'application/json' }),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const error = await downloadPlatformExportTask('9').catch((reason: unknown) => reason)
|
||||||
|
expect(error).toBeInstanceOf(ApiResponseError)
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
message: '导出文件已过期', code: 'FILE_EXPIRED', status: 410,
|
||||||
|
requestId: 'request-download-1', traceId: 'trace-download-1',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects an HTTP 200 business-error Blob instead of saving it as XLSX', async () => {
|
||||||
|
vi.mocked(http.get).mockResolvedValue(new Blob([JSON.stringify({
|
||||||
|
code: 'FILE_EXPIRED', message: '导出文件已过期', data: null,
|
||||||
|
requestId: 'request-download-200', traceId: 'trace-download-200',
|
||||||
|
})], { type: 'application/json;charset=UTF-8' }))
|
||||||
|
|
||||||
|
const error = await downloadPlatformExportTask('9').catch((reason: unknown) => reason)
|
||||||
|
expect(error).toBeInstanceOf(ApiResponseError)
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
message: '导出文件已过期', code: 'FILE_EXPIRED', status: 200,
|
||||||
|
requestId: 'request-download-200', traceId: 'trace-download-200',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects malformed JSON download responses instead of saving them as XLSX', async () => {
|
||||||
|
vi.mocked(http.get).mockResolvedValue(new Blob(['{not-json'], { type: 'application/json' }))
|
||||||
|
|
||||||
|
const error = await downloadPlatformExportTask('9').catch((reason: unknown) => reason)
|
||||||
|
expect(error).toBeInstanceOf(ApiResponseError)
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
message: '下载接口返回了无法识别的 JSON 响应',
|
||||||
|
code: 'INVALID_DOWNLOAD_RESPONSE',
|
||||||
|
status: 200,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects valid JSON values that are not API envelopes', async () => {
|
||||||
|
vi.mocked(http.get).mockResolvedValue(new Blob(['null'], { type: 'application/json' }))
|
||||||
|
|
||||||
|
const error = await downloadPlatformExportTask('9').catch((reason: unknown) => reason)
|
||||||
|
expect(error).toBeInstanceOf(ApiResponseError)
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
message: '下载接口返回了无法识别的 JSON 响应',
|
||||||
|
code: 'INVALID_DOWNLOAD_RESPONSE',
|
||||||
|
status: 200,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects oversized JSON download responses without parsing or saving them', async () => {
|
||||||
|
vi.mocked(http.get).mockResolvedValue(new Blob(
|
||||||
|
['x'.repeat(1024 * 1024 + 1)],
|
||||||
|
{ type: 'application/problem+json' },
|
||||||
|
))
|
||||||
|
|
||||||
|
const error = await downloadPlatformExportTask('9').catch((reason: unknown) => reason)
|
||||||
|
expect(error).toBeInstanceOf(ApiResponseError)
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
message: '下载接口返回了超出限制的 JSON 响应',
|
||||||
|
code: 'INVALID_DOWNLOAD_RESPONSE',
|
||||||
|
status: 200,
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
import axios from 'axios'
|
||||||
|
import { ApiResponseError, http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||||
|
|
||||||
export type ExportTaskStatus = 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'EXPIRED'
|
export type ExportTaskStatus = 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'EXPIRED'
|
||||||
export type ExportTaskType = 'CUSTOMER_LIST' | string
|
export type ExportTaskType = 'CUSTOMER_LIST' | string
|
||||||
@@ -49,6 +50,45 @@ export interface CreatePlatformExportTaskRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const basePath = '/platform/v1/files/export-tasks'
|
const basePath = '/platform/v1/files/export-tasks'
|
||||||
|
const downloadTimeoutMs = 10 * 60 * 1000
|
||||||
|
const maxErrorEnvelopeBytes = 1024 * 1024
|
||||||
|
|
||||||
|
async function parseDownloadErrorBlob(blob: Blob, status?: number): Promise<ApiResponseError | null> {
|
||||||
|
if (!blob.type.toLowerCase().includes('json')) return null
|
||||||
|
|
||||||
|
if (blob.size > maxErrorEnvelopeBytes) {
|
||||||
|
return new ApiResponseError(
|
||||||
|
'下载接口返回了超出限制的 JSON 响应',
|
||||||
|
'INVALID_DOWNLOAD_RESPONSE',
|
||||||
|
status,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(await blob.text()) as Partial<ApiEnvelope<unknown>>
|
||||||
|
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
||||||
|
return new ApiResponseError(
|
||||||
|
'下载接口返回了无法识别的 JSON 响应',
|
||||||
|
'INVALID_DOWNLOAD_RESPONSE',
|
||||||
|
status,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return new ApiResponseError(
|
||||||
|
payload.code === '200' ? '下载接口未返回文件内容' : payload.message || '文件下载失败',
|
||||||
|
payload.code === '200' ? 'INVALID_DOWNLOAD_RESPONSE' : payload.code || (status ? `HTTP_${status}` : 'DOWNLOAD_FAILED'),
|
||||||
|
status,
|
||||||
|
payload.data,
|
||||||
|
payload.requestId,
|
||||||
|
payload.traceId,
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
return new ApiResponseError(
|
||||||
|
'下载接口返回了无法识别的 JSON 响应',
|
||||||
|
'INVALID_DOWNLOAD_RESPONSE',
|
||||||
|
status,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function createPlatformExportTask(payload: CreatePlatformExportTaskRequest) {
|
export async function createPlatformExportTask(payload: CreatePlatformExportTaskRequest) {
|
||||||
const response = await http.post<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(basePath, payload)
|
const response = await http.post<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(basePath, payload)
|
||||||
@@ -69,8 +109,30 @@ export async function listPlatformExportTasks(query: PlatformExportTaskQuery) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function downloadPlatformExportTask(taskId: string) {
|
export async function getPlatformExportTask(taskId: string) {
|
||||||
return http.get<Blob, Blob>(`${basePath}/${encodeURIComponent(taskId)}/download`, { responseType: 'blob' })
|
const response = await http.get<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(
|
||||||
|
`${basePath}/${encodeURIComponent(taskId)}`,
|
||||||
|
)
|
||||||
|
return unwrapApiResponse(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadPlatformExportTask(taskId: string) {
|
||||||
|
try {
|
||||||
|
const blob = await http.get<Blob, Blob>(`${basePath}/${encodeURIComponent(taskId)}/download`, {
|
||||||
|
responseType: 'blob',
|
||||||
|
// 导出文件上限 50 MB,不能继承普通接口的 15 秒超时,也不能无限等待半断开的连接。
|
||||||
|
timeout: downloadTimeoutMs,
|
||||||
|
})
|
||||||
|
const responseError = await parseDownloadErrorBlob(blob, 200)
|
||||||
|
if (responseError) throw responseError
|
||||||
|
return blob
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError(error) && error.response?.data instanceof Blob) {
|
||||||
|
const responseError = await parseDownloadErrorBlob(error.response.data, error.response.status)
|
||||||
|
if (responseError) throw responseError
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function retryPlatformExportTask(taskId: string) {
|
export async function retryPlatformExportTask(taskId: string) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import {
|
import {
|
||||||
downloadPlatformExportTask,
|
downloadPlatformExportTask,
|
||||||
|
getPlatformExportTask,
|
||||||
listPlatformExportTasks,
|
listPlatformExportTasks,
|
||||||
retryPlatformExportTask,
|
retryPlatformExportTask,
|
||||||
type PlatformExportTask,
|
type PlatformExportTask,
|
||||||
@@ -14,6 +15,7 @@ import DownloadCenterView from './DownloadCenterView.vue'
|
|||||||
|
|
||||||
vi.mock('@/modules/downloads/api/platformExportTasks', () => ({
|
vi.mock('@/modules/downloads/api/platformExportTasks', () => ({
|
||||||
downloadPlatformExportTask: vi.fn(),
|
downloadPlatformExportTask: vi.fn(),
|
||||||
|
getPlatformExportTask: vi.fn(),
|
||||||
listPlatformExportTasks: vi.fn(),
|
listPlatformExportTasks: vi.fn(),
|
||||||
retryPlatformExportTask: vi.fn(),
|
retryPlatformExportTask: vi.fn(),
|
||||||
}))
|
}))
|
||||||
@@ -38,6 +40,7 @@ afterEach(() => vi.useRealTimers())
|
|||||||
describe('DownloadCenterView', () => {
|
describe('DownloadCenterView', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
document.body.innerHTML = ''
|
||||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||||
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:export') })
|
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:export') })
|
||||||
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
|
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
|
||||||
@@ -50,6 +53,7 @@ describe('DownloadCenterView', () => {
|
|||||||
useAccessPreviewStore().initializeAfterLogin()
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [task], page: 1, size: 20, total: 1, pages: 1 })
|
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [task], page: 1, size: 20, total: 1, pages: 1 })
|
||||||
vi.mocked(downloadPlatformExportTask).mockResolvedValue(new Blob(['xlsx']))
|
vi.mocked(downloadPlatformExportTask).mockResolvedValue(new Blob(['xlsx']))
|
||||||
|
vi.mocked(getPlatformExportTask).mockResolvedValue(task)
|
||||||
vi.mocked(retryPlatformExportTask).mockResolvedValue({ ...task, status: 'PENDING' })
|
vi.mocked(retryPlatformExportTask).mockResolvedValue({ ...task, status: 'PENDING' })
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -70,6 +74,11 @@ describe('DownloadCenterView', () => {
|
|||||||
|
|
||||||
expect(downloadPlatformExportTask).toHaveBeenCalledWith('9')
|
expect(downloadPlatformExportTask).toHaveBeenCalledWith('9')
|
||||||
expect(URL.createObjectURL).toHaveBeenCalled()
|
expect(URL.createObjectURL).toHaveBeenCalled()
|
||||||
|
expect(HTMLAnchorElement.prototype.click).toHaveBeenCalledOnce()
|
||||||
|
const clickedAnchor = vi.mocked(HTMLAnchorElement.prototype.click).mock.instances[0] as HTMLAnchorElement
|
||||||
|
expect(clickedAnchor.download).toBe('客户列表.xlsx')
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, 0))
|
||||||
|
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:export')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('shows retry only for failed tasks with the source export permission', async () => {
|
it('shows retry only for failed tasks with the source export permission', async () => {
|
||||||
@@ -89,6 +98,83 @@ describe('DownloadCenterView', () => {
|
|||||||
expect(retryPlatformExportTask).toHaveBeenCalledWith('9')
|
expect(retryPlatformExportTask).toHaveBeenCalledWith('9')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('loads a fresh task detail from the backend', async () => {
|
||||||
|
const wrapper = mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [createPinia(), ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const button = [...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find((item) => item.textContent?.trim() === '详情')
|
||||||
|
button?.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(getPlatformExportTask).toHaveBeenCalledWith('9')
|
||||||
|
expect(document.body.textContent).toContain('任务详情 · EXP9')
|
||||||
|
expect(document.body.textContent).toContain('客户列表.xlsx')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders an actionable list error and can recover', async () => {
|
||||||
|
vi.mocked(listPlatformExportTasks)
|
||||||
|
.mockRejectedValueOnce(new Error('network down'))
|
||||||
|
.mockResolvedValueOnce({ records: [task], page: 1, size: 20, total: 1, pages: 1 })
|
||||||
|
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [createPinia(), ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(document.querySelector('[role="alert"]')?.textContent).toContain('下载任务暂时无法加载')
|
||||||
|
const reload = [...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find((item) => item.textContent?.trim() === '重新加载')
|
||||||
|
reload?.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(listPlatformExportTasks).toHaveBeenCalledTimes(2)
|
||||||
|
expect(document.body.textContent).toContain('共 1 个任务')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows a clear empty state and hides retry without the source export permission', async () => {
|
||||||
|
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [], page: 1, size: 20, total: 0, pages: 0 })
|
||||||
|
const pinia = setActivePinia(createPinia())
|
||||||
|
const auth = useAuthStore()
|
||||||
|
auth.token = 'token'
|
||||||
|
auth.permissions = ['platform:download:list']
|
||||||
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
|
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(document.body.textContent).toContain('暂无符合筛选条件的下载任务')
|
||||||
|
expect([...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.some((item) => item.textContent?.trim() === '重试')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not expose customer retry without the customer 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']
|
||||||
|
useAccessPreviewStore().initializeAfterLogin()
|
||||||
|
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(document.body.textContent).toContain('IAM timeout')
|
||||||
|
expect([...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.some((item) => item.textContent?.trim() === '重试')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('announces the initial loading state while the task request is pending', async () => {
|
||||||
|
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] } })
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
|
||||||
|
expect(wrapper.find('.table-panel').attributes('aria-busy')).toBe('true')
|
||||||
|
resolveRequest({ records: [], page: 1, size: 20, total: 0, pages: 0 })
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('.table-panel').attributes('aria-busy')).toBe('false')
|
||||||
|
})
|
||||||
|
|
||||||
it('does not schedule another refresh after an in-flight load finishes on an unmounted page', async () => {
|
it('does not schedule another refresh after an in-flight load finishes on an unmounted page', async () => {
|
||||||
vi.useFakeTimers()
|
vi.useFakeTimers()
|
||||||
let resolveRequest!: (value: { records: PlatformExportTask[]; page: number; size: number; total: number; pages: number }) => void
|
let resolveRequest!: (value: { records: PlatformExportTask[]; page: number; size: number; total: number; pages: number }) => void
|
||||||
@@ -102,4 +188,42 @@ describe('DownloadCenterView', () => {
|
|||||||
|
|
||||||
expect(listPlatformExportTasks).toHaveBeenCalledTimes(1)
|
expect(listPlatformExportTasks).toHaveBeenCalledTimes(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keeps the last successful task list and continues polling after a background refresh failure', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.mocked(listPlatformExportTasks)
|
||||||
|
.mockResolvedValueOnce({ records: [{ ...task, status: 'RUNNING', processedRows: 3 }], page: 1, size: 20, total: 1, pages: 1 })
|
||||||
|
.mockRejectedValueOnce(new Error('temporary network failure'))
|
||||||
|
.mockResolvedValueOnce({ records: [{ ...task, status: 'SUCCEEDED', processedRows: 12 }], page: 1, size: 20, total: 1, pages: 1 })
|
||||||
|
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [createPinia(), ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(5000)
|
||||||
|
await flushPromises()
|
||||||
|
expect(document.body.textContent).toContain('自动刷新暂时失败')
|
||||||
|
expect(document.body.textContent).toContain('客户列表')
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(5000)
|
||||||
|
await flushPromises()
|
||||||
|
expect(listPlatformExportTasks).toHaveBeenCalledTimes(3)
|
||||||
|
expect(document.body.textContent).not.toContain('自动刷新暂时失败')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates an open task detail from the latest polling result', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.mocked(listPlatformExportTasks)
|
||||||
|
.mockResolvedValueOnce({ records: [{ ...task, status: 'RUNNING', processedRows: 3 }], page: 1, size: 20, total: 1, pages: 1 })
|
||||||
|
.mockResolvedValueOnce({ records: [{ ...task, status: 'SUCCEEDED', processedRows: 12 }], page: 1, size: 20, total: 1, pages: 1 })
|
||||||
|
vi.mocked(getPlatformExportTask).mockResolvedValue({ ...task, status: 'RUNNING', processedRows: 3 })
|
||||||
|
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [createPinia(), ElementPlus] } })
|
||||||
|
await flushPromises()
|
||||||
|
;[...document.querySelectorAll<HTMLButtonElement>('button')]
|
||||||
|
.find((item) => item.textContent?.trim() === '详情')?.click()
|
||||||
|
await flushPromises()
|
||||||
|
expect(document.body.textContent).toContain('3 / 12 行')
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(5000)
|
||||||
|
await flushPromises()
|
||||||
|
expect(document.body.textContent).toContain('12 / 12 行')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import { Download, RefreshCw, RotateCcw } from '@lucide/vue'
|
import { Download, Eye, RefreshCw, RotateCcw } from '@lucide/vue'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||||
import {
|
import {
|
||||||
downloadPlatformExportTask,
|
downloadPlatformExportTask,
|
||||||
|
getPlatformExportTask,
|
||||||
listPlatformExportTasks,
|
listPlatformExportTasks,
|
||||||
retryPlatformExportTask,
|
retryPlatformExportTask,
|
||||||
type ExportTaskStatus,
|
type ExportTaskStatus,
|
||||||
type PlatformExportTask,
|
type PlatformExportTask,
|
||||||
} from '@/modules/downloads/api/platformExportTasks'
|
} from '@/modules/downloads/api/platformExportTasks'
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||||
|
import AppDrawer from '@/shared/components/AppDrawer.vue'
|
||||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
@@ -28,10 +30,17 @@ const loading = ref(false)
|
|||||||
const downloadingId = ref('')
|
const downloadingId = ref('')
|
||||||
const retryingId = ref('')
|
const retryingId = ref('')
|
||||||
const loadError = ref<ApiErrorDetails | null>(null)
|
const loadError = ref<ApiErrorDetails | null>(null)
|
||||||
|
const syncWarning = ref<ApiErrorDetails | null>(null)
|
||||||
|
const detailOpen = ref(false)
|
||||||
|
const detailLoading = ref(false)
|
||||||
|
const detailError = ref<ApiErrorDetails | null>(null)
|
||||||
|
const detailTask = ref<PlatformExportTask | null>(null)
|
||||||
const result = ref({ records: [] as PlatformExportTask[], total: 0, pages: 0 })
|
const result = ref({ records: [] as PlatformExportTask[], total: 0, pages: 0 })
|
||||||
const filters = ref<DownloadFilters>({ exportType: '', status: '', requestedRange: [] })
|
const filters = ref<DownloadFilters>({ exportType: '', status: '', requestedRange: [] })
|
||||||
let refreshTimer: number | undefined
|
let refreshTimer: number | undefined
|
||||||
let disposed = false
|
let disposed = false
|
||||||
|
let loadRequestId = 0
|
||||||
|
let detailRequestId = 0
|
||||||
|
|
||||||
const queryFields: QueryField[] = [
|
const queryFields: QueryField[] = [
|
||||||
{ key: 'exportType', type: 'select', placeholder: '全部任务类型', options: [
|
{ key: 'exportType', type: 'select', placeholder: '全部任务类型', options: [
|
||||||
@@ -46,7 +55,7 @@ const queryFields: QueryField[] = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
const columns: DataTableColumn[] = [
|
const columns: DataTableColumn[] = [
|
||||||
{ key: 'actions', label: '操作', width: 150, fixed: 'left', slotName: 'actions' },
|
{ key: 'actions', label: '操作', width: 210, fixed: 'left', slotName: 'actions' },
|
||||||
{ prop: 'taskName', label: '任务名称', minWidth: 180, showOverflowTooltip: true },
|
{ prop: 'taskName', label: '任务名称', minWidth: 180, showOverflowTooltip: true },
|
||||||
{ key: 'type', label: '任务类型', width: 120, slotName: 'type' },
|
{ key: 'type', label: '任务类型', width: 120, slotName: 'type' },
|
||||||
{ key: 'status', label: '状态', width: 110, slotName: 'status' },
|
{ key: 'status', label: '状态', width: 110, slotName: 'status' },
|
||||||
@@ -68,13 +77,14 @@ function clearRefreshTimer() {
|
|||||||
|
|
||||||
function scheduleRefresh() {
|
function scheduleRefresh() {
|
||||||
clearRefreshTimer()
|
clearRefreshTimer()
|
||||||
if (!disposed && hasActiveTasks.value && !loadError.value) refreshTimer = window.setTimeout(() => { void loadTasks(true) }, 5000)
|
if (!disposed && hasActiveTasks.value) refreshTimer = window.setTimeout(() => { void loadTasks(true) }, 5000)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadTasks(background = false) {
|
async function loadTasks(background = false) {
|
||||||
|
const requestId = ++loadRequestId
|
||||||
clearRefreshTimer()
|
clearRefreshTimer()
|
||||||
if (!background) loading.value = true
|
if (!background) loading.value = true
|
||||||
loadError.value = null
|
if (!background) loadError.value = null
|
||||||
try {
|
try {
|
||||||
const range = filters.value.requestedRange
|
const range = filters.value.requestedRange
|
||||||
const response = await listPlatformExportTasks({
|
const response = await listPlatformExportTasks({
|
||||||
@@ -85,12 +95,24 @@ async function loadTasks(background = false) {
|
|||||||
requestedFrom: range?.[0] || undefined,
|
requestedFrom: range?.[0] || undefined,
|
||||||
requestedTo: range?.[1] || undefined,
|
requestedTo: range?.[1] || undefined,
|
||||||
})
|
})
|
||||||
|
if (disposed || requestId !== loadRequestId) return
|
||||||
result.value = { records: response.records, total: response.total, pages: response.pages }
|
result.value = { records: response.records, total: response.total, pages: response.pages }
|
||||||
|
loadError.value = null
|
||||||
|
syncWarning.value = null
|
||||||
|
if (detailOpen.value && detailTask.value) {
|
||||||
|
const freshDetail = response.records.find((task) => task.id === detailTask.value?.id)
|
||||||
|
if (freshDetail) detailTask.value = freshDetail
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
loadError.value = getApiErrorDetails(error, '下载任务加载失败')
|
if (disposed || requestId !== loadRequestId) return
|
||||||
|
const details = getApiErrorDetails(error, '下载任务加载失败')
|
||||||
|
if (background && result.value.records.length > 0) syncWarning.value = details
|
||||||
|
else loadError.value = details
|
||||||
} finally {
|
} finally {
|
||||||
if (!background) loading.value = false
|
if (!disposed && requestId === loadRequestId) {
|
||||||
scheduleRefresh()
|
if (!background) loading.value = false
|
||||||
|
scheduleRefresh()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,20 +121,53 @@ function applyFilters() {
|
|||||||
else page.value = 1
|
else page.value = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openDetail(task: PlatformExportTask) {
|
||||||
|
if (!task?.id) return
|
||||||
|
const requestId = ++detailRequestId
|
||||||
|
detailTask.value = task
|
||||||
|
detailError.value = null
|
||||||
|
detailOpen.value = true
|
||||||
|
detailLoading.value = true
|
||||||
|
try {
|
||||||
|
const response = await getPlatformExportTask(task.id)
|
||||||
|
if (disposed || requestId !== detailRequestId) return
|
||||||
|
detailTask.value = response
|
||||||
|
} catch (error) {
|
||||||
|
if (disposed || requestId !== detailRequestId) return
|
||||||
|
detailError.value = getApiErrorDetails(error, '下载任务详情加载失败')
|
||||||
|
} finally {
|
||||||
|
if (!disposed && requestId === detailRequestId) detailLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeDetail() {
|
||||||
|
detailRequestId += 1
|
||||||
|
detailTask.value = null
|
||||||
|
detailError.value = null
|
||||||
|
detailLoading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
async function downloadTask(task: PlatformExportTask) {
|
async function downloadTask(task: PlatformExportTask) {
|
||||||
downloadingId.value = task.id
|
downloadingId.value = task.id
|
||||||
try {
|
try {
|
||||||
const blob = await downloadPlatformExportTask(task.id)
|
const blob = await downloadPlatformExportTask(task.id)
|
||||||
const url = URL.createObjectURL(blob)
|
const url = URL.createObjectURL(blob)
|
||||||
const anchor = document.createElement('a')
|
const anchor = document.createElement('a')
|
||||||
anchor.href = url
|
try {
|
||||||
anchor.download = safeFileName(task.fileName || `${task.taskName}.xlsx`)
|
anchor.href = url
|
||||||
document.body.append(anchor)
|
anchor.download = safeFileName(task.fileName || `${task.taskName}.xlsx`)
|
||||||
anchor.click()
|
document.body.append(anchor)
|
||||||
anchor.remove()
|
anchor.click()
|
||||||
URL.revokeObjectURL(url)
|
} finally {
|
||||||
|
anchor.remove()
|
||||||
|
window.setTimeout(() => URL.revokeObjectURL(url), 0)
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ElMessage.error(getApiErrorMessage(error, '文件下载失败,请刷新任务状态后重试'))
|
const details = getApiErrorDetails(error, '文件下载失败,请刷新任务状态后重试')
|
||||||
|
const trace = [details.code, details.requestId && `requestId: ${details.requestId}`, details.traceId && `traceId: ${details.traceId}`]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(',')
|
||||||
|
ElMessage.error(trace ? `${details.message}(${trace})` : details.message)
|
||||||
} finally {
|
} finally {
|
||||||
downloadingId.value = ''
|
downloadingId.value = ''
|
||||||
}
|
}
|
||||||
@@ -146,7 +201,7 @@ function statusMeta(status: ExportTaskStatus) {
|
|||||||
FAILED: { label: '失败', type: 'danger' as const },
|
FAILED: { label: '失败', type: 'danger' as const },
|
||||||
EXPIRED: { label: '已过期', type: 'info' as const },
|
EXPIRED: { label: '已过期', type: 'info' as const },
|
||||||
}
|
}
|
||||||
return values[status]
|
return values[status] ?? { label: status || '未知状态', type: 'info' as const }
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(value: string | null) {
|
function formatDate(value: string | null) {
|
||||||
@@ -170,6 +225,8 @@ watch([page, pageSize], () => { void loadTasks() })
|
|||||||
onMounted(loadTasks)
|
onMounted(loadTasks)
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
disposed = true
|
disposed = true
|
||||||
|
loadRequestId += 1
|
||||||
|
detailRequestId += 1
|
||||||
clearRefreshTimer()
|
clearRefreshTimer()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
@@ -188,11 +245,15 @@ onBeforeUnmount(() => {
|
|||||||
<div><h2>下载任务</h2><span>共 {{ result.total }} 个任务</span></div>
|
<div><h2>下载任务</h2><span>共 {{ result.total }} 个任务</span></div>
|
||||||
<el-button :loading="loading" @click="loadTasks()"><RefreshCw :size="16" />刷新</el-button>
|
<el-button :loading="loading" @click="loadTasks()"><RefreshCw :size="16" />刷新</el-button>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="syncWarning" class="download-sync-warning" role="status">
|
||||||
|
<span>自动刷新暂时失败,正在保留当前任务并继续重试:{{ syncWarning.message }}</span>
|
||||||
|
<ApiErrorMeta :details="syncWarning" />
|
||||||
|
</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="下载任务列表">
|
<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">
|
<template #actions="{ row }"><div class="table-actions">
|
||||||
|
<el-button v-if="(row as PlatformExportTask)?.id" link type="primary" @click="openDetail(row as PlatformExportTask)"><Eye :size="15" />详情</el-button>
|
||||||
<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="(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>
|
<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>
|
</div></template>
|
||||||
<template #type="{ row }">{{ typeLabel((row as PlatformExportTask).exportType) }}</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 #status="{ row }"><el-tag :type="statusMeta((row as PlatformExportTask).status).type" effect="light">{{ statusMeta((row as PlatformExportTask).status).label }}</el-tag></template>
|
||||||
@@ -204,6 +265,47 @@ onBeforeUnmount(() => {
|
|||||||
<template #failure="{ row }"><span class="failure-cell" :class="{ 'failure-message': Boolean((row as PlatformExportTask).failureMessage) }">{{ (row as PlatformExportTask).failureMessage || '—' }}</span></template>
|
<template #failure="{ row }"><span class="failure-cell" :class="{ 'failure-message': Boolean((row as PlatformExportTask).failureMessage) }">{{ (row as PlatformExportTask).failureMessage || '—' }}</span></template>
|
||||||
</DataTable>
|
</DataTable>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<AppDrawer
|
||||||
|
v-model="detailOpen"
|
||||||
|
:title="detailTask ? `任务详情 · ${detailTask.taskNo}` : '任务详情'"
|
||||||
|
size="min(620px, 94vw)"
|
||||||
|
:loading="detailLoading"
|
||||||
|
:show-footer="false"
|
||||||
|
destroy-on-close
|
||||||
|
@closed="closeDetail"
|
||||||
|
>
|
||||||
|
<section v-if="detailError" class="detail-load-error" role="alert">
|
||||||
|
<strong>任务详情暂时无法加载</strong>
|
||||||
|
<p>{{ detailError.message }}</p>
|
||||||
|
<ApiErrorMeta :details="detailError" />
|
||||||
|
<el-button type="primary" @click="detailTask && openDetail(detailTask)">重新加载</el-button>
|
||||||
|
</section>
|
||||||
|
<div v-else-if="detailTask" class="task-detail">
|
||||||
|
<div class="task-detail-summary">
|
||||||
|
<div>
|
||||||
|
<h3>{{ detailTask.taskName }}</h3>
|
||||||
|
<p>{{ typeLabel(detailTask.exportType) }} · {{ detailTask.format }}</p>
|
||||||
|
</div>
|
||||||
|
<el-tag :type="statusMeta(detailTask.status).type" effect="light">{{ statusMeta(detailTask.status).label }}</el-tag>
|
||||||
|
</div>
|
||||||
|
<dl class="task-detail-grid">
|
||||||
|
<div><dt>任务编号</dt><dd>{{ detailTask.taskNo }}</dd></div>
|
||||||
|
<div><dt>申请人</dt><dd>{{ detailTask.requestedUsername || detailTask.requestedBy }}</dd></div>
|
||||||
|
<div><dt>申请时间</dt><dd>{{ formatDate(detailTask.requestedAt) }}</dd></div>
|
||||||
|
<div><dt>开始时间</dt><dd>{{ formatDate(detailTask.startedAt) }}</dd></div>
|
||||||
|
<div><dt>完成时间</dt><dd>{{ formatDate(detailTask.completedAt) }}</dd></div>
|
||||||
|
<div><dt>过期时间</dt><dd>{{ formatDate(detailTask.expiresAt) }}</dd></div>
|
||||||
|
<div><dt>处理数据</dt><dd>{{ detailTask.processedRows }}<template v-if="detailTask.totalRows !== null"> / {{ detailTask.totalRows }}</template> 行</dd></div>
|
||||||
|
<div><dt>文件大小</dt><dd>{{ formatSize(detailTask.sizeBytes) || '—' }}</dd></div>
|
||||||
|
<div class="is-wide"><dt>文件名称</dt><dd>{{ detailTask.fileName || '—' }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
<section v-if="detailTask.failureMessage" class="task-failure" role="status">
|
||||||
|
<strong>失败原因</strong>
|
||||||
|
<p>{{ detailTask.failureMessage }}</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</AppDrawer>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -216,14 +318,38 @@ onBeforeUnmount(() => {
|
|||||||
.download-table-header { min-height: 64px; padding: 12px 18px; border-bottom: 1px solid var(--cc-border); }
|
.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 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; }
|
.download-table-header span { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 12px; }
|
||||||
|
.download-sync-warning { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 18px; border-bottom: 1px solid #fedf89; background: #fffaeb; color: #93370d; font-size: 12px; }
|
||||||
.table-actions { display: flex; min-height: 32px; align-items: center; gap: 8px; }
|
.table-actions { display: flex; min-height: 32px; align-items: center; gap: 8px; }
|
||||||
.table-actions :deep(.el-button + .el-button) { margin-left: 0; }
|
.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-cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.failure-message { color: var(--cc-danger); }
|
.failure-message { color: var(--cc-danger); }
|
||||||
|
.detail-load-error { display: flex; min-height: 220px; align-items: flex-start; justify-content: center; flex-direction: column; }
|
||||||
|
.detail-load-error strong { color: var(--cc-danger); font-size: 15px; }
|
||||||
|
.detail-load-error p { margin: 6px 0; color: var(--cc-text); font-size: 13px; }
|
||||||
|
.detail-load-error :deep(.el-button) { margin-top: 16px; }
|
||||||
|
.task-detail { min-width: 0; }
|
||||||
|
.task-detail-summary { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 18px; border-bottom: 1px solid var(--cc-border); }
|
||||||
|
.task-detail-summary h3 { margin: 0; overflow-wrap: anywhere; color: var(--cc-text); font-size: 17px; }
|
||||||
|
.task-detail-summary p { margin: 6px 0 0; color: var(--cc-muted); font-size: 12px; }
|
||||||
|
.task-detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); margin: 0; }
|
||||||
|
.task-detail-grid > div { min-width: 0; padding: 16px 14px; border-bottom: 1px solid var(--cc-border); }
|
||||||
|
.task-detail-grid > div:nth-child(odd):not(.is-wide) { border-right: 1px solid var(--cc-border); }
|
||||||
|
.task-detail-grid .is-wide { grid-column: 1 / -1; }
|
||||||
|
.task-detail-grid dt { margin-bottom: 6px; color: var(--cc-muted); font-size: 12px; }
|
||||||
|
.task-detail-grid dd { margin: 0; overflow-wrap: anywhere; color: var(--cc-text); font-size: 13px; line-height: 1.5; }
|
||||||
|
.task-failure { margin-top: 18px; padding: 14px; border: 1px solid color-mix(in srgb, var(--cc-danger) 24%, var(--cc-border)); border-radius: 8px; background: color-mix(in srgb, var(--cc-danger) 5%, #fff); }
|
||||||
|
.task-failure strong { color: var(--cc-danger); font-size: 13px; }
|
||||||
|
.task-failure p { margin: 6px 0 0; overflow-wrap: anywhere; color: var(--cc-text); font-size: 13px; line-height: 1.6; }
|
||||||
small { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 11px; }
|
small { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 11px; }
|
||||||
@media (max-width: 720px) {
|
@media (max-width: 720px) {
|
||||||
.download-error, .download-table-header { align-items: stretch; flex-direction: column; }
|
.download-error, .download-table-header, .download-sync-warning { align-items: stretch; flex-direction: column; }
|
||||||
.download-table-header :deep(.el-button) { min-height: 40px; }
|
.download-table-header :deep(.el-button), .table-actions :deep(.el-button) { min-height: 44px; }
|
||||||
|
.table-actions :deep(.el-button) { padding-right: 8px; padding-left: 8px; }
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.task-detail-summary { flex-direction: column; }
|
||||||
|
.task-detail-grid { grid-template-columns: 1fr; }
|
||||||
|
.task-detail-grid > div:nth-child(odd):not(.is-wide) { border-right: 0; }
|
||||||
|
.task-detail-grid .is-wide { grid-column: 1; }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -266,7 +266,7 @@ describe('platform IAM roles', () => {
|
|||||||
it('creates, updates, and changes customer status with the platform tenant contract', async () => {
|
it('creates, updates, and changes customer status with the platform tenant contract', async () => {
|
||||||
const tenant = { id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'ACTIVE' }
|
const tenant = { id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'ACTIVE' }
|
||||||
const create = {
|
const create = {
|
||||||
tenantName: '柏悦物流', legalName: '柏悦物流有限公司', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
tenantName: '柏悦物流', legalName: '柏悦物流有限公司', legalRepresentative: '张三', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
||||||
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com', servicePackage: '标准版',
|
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com', servicePackage: '标准版',
|
||||||
contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30, enterpriseType: '有限责任公司',
|
contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30, enterpriseType: '有限责任公司',
|
||||||
establishedDate: '2020-01-01', registeredCapital: 1000, registeredCapitalCurrency: 'CNY',
|
establishedDate: '2020-01-01', registeredCapital: 1000, registeredCapitalCurrency: 'CNY',
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ export interface PlatformTenantResource {
|
|||||||
tenantName: string
|
tenantName: string
|
||||||
status: PlatformTenantStatus
|
status: PlatformTenantStatus
|
||||||
legalName: string | null
|
legalName: string | null
|
||||||
|
legalRepresentative: string | null
|
||||||
unifiedSocialCreditCode: string | null
|
unifiedSocialCreditCode: string | null
|
||||||
contactName: string | null
|
contactName: string | null
|
||||||
contactPhone: string | null
|
contactPhone: string | null
|
||||||
@@ -51,6 +52,7 @@ export interface PlatformTenantResource {
|
|||||||
export interface CreatePlatformTenantRequest {
|
export interface CreatePlatformTenantRequest {
|
||||||
tenantName: string
|
tenantName: string
|
||||||
legalName: string
|
legalName: string
|
||||||
|
legalRepresentative: string
|
||||||
unifiedSocialCreditCode: string
|
unifiedSocialCreditCode: string
|
||||||
contactName: string
|
contactName: string
|
||||||
contactPhone: string
|
contactPhone: string
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { RefreshCw } from '@lucide/vue'
|
||||||
|
import { listPlatformTenants, type PlatformTenantResource } from '../api/platformIam'
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<{
|
||||||
|
modelValue: string
|
||||||
|
disabled?: boolean
|
||||||
|
label?: string
|
||||||
|
}>(), {
|
||||||
|
disabled: false,
|
||||||
|
label: '目标企业',
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [value: string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const tenants = ref<PlatformTenantResource[]>([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
|
||||||
|
const selectedValue = computed({
|
||||||
|
get: () => props.modelValue,
|
||||||
|
set: (value: string) => emit('update:modelValue', value),
|
||||||
|
})
|
||||||
|
|
||||||
|
const statusLabels: Record<string, string> = {
|
||||||
|
PROFILE_REQUIRED: '待完善',
|
||||||
|
PENDING: '待审核',
|
||||||
|
ACTIVE: '启用',
|
||||||
|
REJECTED: '已驳回',
|
||||||
|
DISABLED: '已停用',
|
||||||
|
INACTIVE: '已停用',
|
||||||
|
}
|
||||||
|
|
||||||
|
function tenantLabel(tenant: PlatformTenantResource) {
|
||||||
|
const status = statusLabels[tenant.status] || tenant.status
|
||||||
|
return `${tenant.tenantName}(${tenant.id} · ${status})`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTenants() {
|
||||||
|
loading.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
const result = await listPlatformTenants({ page: 1, size: 200 })
|
||||||
|
tenants.value = result.records
|
||||||
|
if (!props.modelValue && result.records.length) {
|
||||||
|
const preferred = result.records.find((tenant) => String(tenant.id) === '10001') || result.records[0]
|
||||||
|
emit('update:modelValue', String(preferred.id))
|
||||||
|
}
|
||||||
|
} catch (reason) {
|
||||||
|
error.value = reason instanceof Error ? reason.message : '企业列表加载失败,请重试'
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => void loadTenants())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="platform-tenant-selector">
|
||||||
|
<div class="platform-tenant-selector-label"><span>{{ label }}</span><span v-if="loading">加载中…</span></div>
|
||||||
|
<el-select
|
||||||
|
v-model="selectedValue"
|
||||||
|
class="platform-tenant-selector-input"
|
||||||
|
filterable
|
||||||
|
:disabled="disabled || loading || tenants.length === 0"
|
||||||
|
:placeholder="loading ? '正在加载企业' : '请选择目标企业'"
|
||||||
|
aria-label="目标企业"
|
||||||
|
>
|
||||||
|
<el-option v-for="tenant in tenants" :key="String(tenant.id)" :label="tenantLabel(tenant)" :value="String(tenant.id)" />
|
||||||
|
</el-select>
|
||||||
|
<div v-if="error" class="platform-tenant-selector-error" role="alert">
|
||||||
|
<span>{{ error }}</span>
|
||||||
|
<el-button link type="primary" :disabled="loading" @click="loadTenants"><RefreshCw :size="14" />重新加载</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.platform-tenant-selector { display: grid; min-width: min(100%, 360px); gap: 6px; }
|
||||||
|
.platform-tenant-selector-label { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--cc-muted); font-size: 12px; }
|
||||||
|
.platform-tenant-selector-label span:last-child { color: var(--cc-primary); font-size: 11px; }
|
||||||
|
.platform-tenant-selector-input { width: 100%; }
|
||||||
|
.platform-tenant-selector-error { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--el-color-danger); font-size: 12px; line-height: 1.5; }
|
||||||
|
.platform-tenant-selector-error :deep(.el-button) { flex: 0 0 auto; }
|
||||||
|
</style>
|
||||||
@@ -1 +1,2 @@
|
|||||||
export * from './api/platformIam'
|
export * from './api/platformIam'
|
||||||
|
export { default as PlatformTenantSelector } from './components/PlatformTenantSelector.vue'
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ function normalizePartner(resource: PlatformPartnerResource): PlatformPartnerRes
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listPlatformPartners(tenantId: number, query: PlatformPartnerQuery) {
|
export async function listPlatformPartners(tenantId: number | string, query: PlatformPartnerQuery) {
|
||||||
const response = await http.get<ApiEnvelope<PlatformPartnerPagePayload>, ApiEnvelope<PlatformPartnerPagePayload>>(basePath, {
|
const response = await http.get<ApiEnvelope<PlatformPartnerPagePayload>, ApiEnvelope<PlatformPartnerPagePayload>>(basePath, {
|
||||||
params: { tenantId, ...query },
|
params: { tenantId, ...query },
|
||||||
})
|
})
|
||||||
@@ -111,7 +111,7 @@ export async function listPlatformPartners(tenantId: number, query: PlatformPart
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPlatformPartner(tenantId: number, partnerId: number | string) {
|
export async function getPlatformPartner(tenantId: number | string, partnerId: number | string) {
|
||||||
const response = await http.get<ApiEnvelope<PlatformPartnerResource>, ApiEnvelope<PlatformPartnerResource>>(
|
const response = await http.get<ApiEnvelope<PlatformPartnerResource>, ApiEnvelope<PlatformPartnerResource>>(
|
||||||
`${basePath}/${partnerId}`,
|
`${basePath}/${partnerId}`,
|
||||||
{ params: { tenantId } },
|
{ params: { tenantId } },
|
||||||
@@ -123,7 +123,7 @@ export async function downloadPlatformPartnerImportTemplate() {
|
|||||||
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
|
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function importPlatformPartners(tenantId: number, file: File) {
|
export async function importPlatformPartners(tenantId: number | string, file: File) {
|
||||||
const form = new FormData()
|
const form = new FormData()
|
||||||
form.append('file', file)
|
form.append('file', file)
|
||||||
const response = await http.post<ApiEnvelope<PlatformPartnerImportResult>, ApiEnvelope<PlatformPartnerImportResult>>(
|
const response = await http.post<ApiEnvelope<PlatformPartnerImportResult>, ApiEnvelope<PlatformPartnerImportResult>>(
|
||||||
@@ -134,7 +134,7 @@ export async function importPlatformPartners(tenantId: number, file: File) {
|
|||||||
return unwrapApiResponse(response)
|
return unwrapApiResponse(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createPlatformPartner(tenantId: number, payload: SavePlatformPartnerRequest) {
|
export async function createPlatformPartner(tenantId: number | string, payload: SavePlatformPartnerRequest) {
|
||||||
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
|
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
|
||||||
params: { tenantId },
|
params: { tenantId },
|
||||||
})
|
})
|
||||||
@@ -142,7 +142,7 @@ export async function createPlatformPartner(tenantId: number, payload: SavePlatf
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function updatePlatformPartner(
|
export async function updatePlatformPartner(
|
||||||
tenantId: number,
|
tenantId: number | string,
|
||||||
partnerId: number | string,
|
partnerId: number | string,
|
||||||
payload: SavePlatformPartnerRequest,
|
payload: SavePlatformPartnerRequest,
|
||||||
) {
|
) {
|
||||||
@@ -153,7 +153,7 @@ export async function updatePlatformPartner(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function changePlatformPartnerStatus(
|
export async function changePlatformPartnerStatus(
|
||||||
tenantId: number,
|
tenantId: number | string,
|
||||||
partnerId: number | string,
|
partnerId: number | string,
|
||||||
status: PlatformPartnerStatus,
|
status: PlatformPartnerStatus,
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import {
|
|||||||
} from '@/modules/master-data/counterparties/api/platformPartners'
|
} from '@/modules/master-data/counterparties/api/platformPartners'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
import { useAuthStore } from '@/core/auth/auth'
|
||||||
|
import { listPlatformTenants, type PlatformTenantResource } from '../../../iam/api/platformIam'
|
||||||
|
import PlatformTenantSelector from '../../../iam/components/PlatformTenantSelector.vue'
|
||||||
import PartnersView from './PartnersView.vue'
|
import PartnersView from './PartnersView.vue'
|
||||||
|
|
||||||
vi.mock('@/modules/master-data/counterparties/api/platformPartners', () => ({
|
vi.mock('@/modules/master-data/counterparties/api/platformPartners', () => ({
|
||||||
@@ -20,6 +22,8 @@ vi.mock('@/modules/master-data/counterparties/api/platformPartners', () => ({
|
|||||||
changePlatformPartnerStatus: vi.fn(),
|
changePlatformPartnerStatus: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../../iam/api/platformIam', () => ({ listPlatformTenants: vi.fn() }))
|
||||||
|
|
||||||
class ResizeObserverStub implements ResizeObserver {
|
class ResizeObserverStub implements ResizeObserver {
|
||||||
observe() {}
|
observe() {}
|
||||||
unobserve() {}
|
unobserve() {}
|
||||||
@@ -60,6 +64,16 @@ const partner: PlatformPartnerResource = {
|
|||||||
updatedAt: '2026-07-30T22:45:00',
|
updatedAt: '2026-07-30T22:45:00',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tenant = (id: number | string, tenantName: string): PlatformTenantResource => ({
|
||||||
|
id, tenantCode: String(id), tenantName, status: 'ACTIVE', legalName: tenantName,
|
||||||
|
legalRepresentative: null, unifiedSocialCreditCode: null, contactName: null,
|
||||||
|
contactPhone: null, contactEmail: null, servicePackage: null, contactWechat: null,
|
||||||
|
salesOwnerName: null, paymentTermDays: null, enterpriseType: null, establishedDate: null,
|
||||||
|
registeredCapital: null, registeredCapitalCurrency: null, registeredAddress: null,
|
||||||
|
internalRemark: null, createdAt: null, approvedAt: null,
|
||||||
|
})
|
||||||
|
const snowflakeTenantId = '9223372036854775806'
|
||||||
|
|
||||||
async function mountView() {
|
async function mountView() {
|
||||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||||
@@ -89,6 +103,9 @@ describe('PartnersView real API integration', () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||||
document.body.innerHTML = ''
|
document.body.innerHTML = ''
|
||||||
|
vi.mocked(listPlatformTenants).mockReset().mockResolvedValue({
|
||||||
|
records: [tenant(10001, '默认企业'), tenant(snowflakeTenantId, '雪花企业')], page: 1, size: 200, total: 2, pages: 1,
|
||||||
|
})
|
||||||
vi.mocked(listPlatformPartners).mockReset().mockResolvedValue({
|
vi.mocked(listPlatformPartners).mockReset().mockResolvedValue({
|
||||||
records: [partner], page: 1, size: 20, total: 1, pages: 1,
|
records: [partner], page: 1, size: 20, total: 1, pages: 1,
|
||||||
})
|
})
|
||||||
@@ -111,6 +128,17 @@ describe('PartnersView real API integration', () => {
|
|||||||
expect(wrapper.find('.table-panel').exists()).toBe(true)
|
expect(wrapper.find('.table-panel').exists()).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('preserves a snowflake tenant id as a string when switching enterprises', async () => {
|
||||||
|
const wrapper = await mountView()
|
||||||
|
|
||||||
|
wrapper.findComponent(PlatformTenantSelector).vm.$emit('update:modelValue', snowflakeTenantId)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(listPlatformPartners).toHaveBeenLastCalledWith(snowflakeTenantId, {
|
||||||
|
page: 1, size: 20, keyword: undefined, type: undefined, status: undefined,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('updates filters locally and only requests after search', async () => {
|
it('updates filters locally and only requests after search', async () => {
|
||||||
const wrapper = await mountView()
|
const wrapper = await mountView()
|
||||||
const keywordInput = wrapper.find('input[placeholder="单位名称、编码、联系人或电话"]')
|
const keywordInput = wrapper.find('input[placeholder="单位名称、编码、联系人或电话"]')
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
import { computed, reactive, ref, watch } from 'vue'
|
||||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
|
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 { Building2, Download, Eye, MapPin, Pencil, Plus, Power, Upload } from '@lucide/vue'
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||||
@@ -23,8 +23,8 @@ import {
|
|||||||
type SavePlatformPartnerRequest,
|
type SavePlatformPartnerRequest,
|
||||||
} from '@/modules/master-data/counterparties/api/platformPartners'
|
} from '@/modules/master-data/counterparties/api/platformPartners'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
|
import { PlatformTenantSelector } from '@/modules/iam'
|
||||||
|
|
||||||
const fixedTenantId = 10001
|
|
||||||
const pageSize = ref(20)
|
const pageSize = ref(20)
|
||||||
const access = useAccessPreviewStore()
|
const access = useAccessPreviewStore()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
@@ -42,8 +42,11 @@ const formRef = ref<FormInstance>()
|
|||||||
const rows = ref<PlatformPartnerResource[]>([])
|
const rows = ref<PlatformPartnerResource[]>([])
|
||||||
const page = ref(1)
|
const page = ref(1)
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
|
const selectedTenantId = ref('')
|
||||||
|
const loadedTenantId = ref<string | null>(null)
|
||||||
const loadError = ref<ApiErrorDetails | null>(null)
|
const loadError = ref<ApiErrorDetails | null>(null)
|
||||||
const statusLoadingIds = ref(new Set<string>())
|
const statusLoadingIds = ref(new Set<string>())
|
||||||
|
let loadSequence = 0
|
||||||
|
|
||||||
type PartnerFilters = QueryModel & {
|
type PartnerFilters = QueryModel & {
|
||||||
keyword: string
|
keyword: string
|
||||||
@@ -116,6 +119,17 @@ const { captureBaseline } = useUnsavedWorkRegistration({
|
|||||||
requiredPermission: editorPermission,
|
requiredPermission: editorPermission,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const tenantReady = computed(() => Boolean(selectedTenantId.value)
|
||||||
|
&& loadedTenantId.value === selectedTenantId.value
|
||||||
|
&& !loading.value)
|
||||||
|
const tenantSwitchDisabled = computed(() => editorOpen.value
|
||||||
|
|| detailOpen.value
|
||||||
|
|| importOpen.value
|
||||||
|
|| saving.value
|
||||||
|
|| detailLoading.value
|
||||||
|
|| importing.value
|
||||||
|
|| statusLoadingIds.value.size > 0)
|
||||||
|
|
||||||
const rules: FormRules<PartnerForm> = {
|
const rules: FormRules<PartnerForm> = {
|
||||||
partnerCode: [{ required: true, whitespace: true, message: '请输入往来单位编码', trigger: 'blur' }],
|
partnerCode: [{ required: true, whitespace: true, message: '请输入往来单位编码', trigger: 'blur' }],
|
||||||
partnerName: [{ required: true, whitespace: true, message: '请输入往来单位名称', trigger: 'blur' }],
|
partnerName: [{ required: true, whitespace: true, message: '请输入往来单位名称', trigger: 'blur' }],
|
||||||
@@ -174,17 +188,37 @@ function queryParams() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPartners() {
|
function apiTenantId(value: string) {
|
||||||
|
const numeric = Number(value)
|
||||||
|
return Number.isSafeInteger(numeric) ? numeric : value
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireCurrentTenant() {
|
||||||
|
if (!tenantReady.value) {
|
||||||
|
ElMessage.warning('往来单位数据尚未加载完成,请稍后重试')
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return apiTenantId(selectedTenantId.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPartners(tenantId = selectedTenantId.value) {
|
||||||
|
if (!tenantId) return
|
||||||
|
const sequence = ++loadSequence
|
||||||
loading.value = true
|
loading.value = true
|
||||||
loadError.value = null
|
loadError.value = null
|
||||||
try {
|
try {
|
||||||
const result = await listPlatformPartners(fixedTenantId, queryParams())
|
const result = await listPlatformPartners(apiTenantId(tenantId), queryParams())
|
||||||
|
if (sequence !== loadSequence) return
|
||||||
rows.value = result.records
|
rows.value = result.records
|
||||||
total.value = result.total
|
total.value = result.total
|
||||||
|
loadedTenantId.value = tenantId
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (sequence !== loadSequence) return
|
||||||
|
rows.value = []
|
||||||
|
total.value = 0
|
||||||
loadError.value = getApiErrorDetails(error, '往来单位加载失败,请稍后重试')
|
loadError.value = getApiErrorDetails(error, '往来单位加载失败,请稍后重试')
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
if (sequence === loadSequence) loading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,6 +236,7 @@ function searchPartners(model: QueryModel) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
|
if (!requireCurrentTenant()) return
|
||||||
Object.assign(form, emptyForm())
|
Object.assign(form, emptyForm())
|
||||||
captureBaseline()
|
captureBaseline()
|
||||||
editorOpen.value = true
|
editorOpen.value = true
|
||||||
@@ -213,6 +248,7 @@ function nullable(value: string | null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openEdit(row: PlatformPartnerResource) {
|
function openEdit(row: PlatformPartnerResource) {
|
||||||
|
if (!requireCurrentTenant()) return
|
||||||
Object.assign(form, {
|
Object.assign(form, {
|
||||||
id: String(row.id),
|
id: String(row.id),
|
||||||
partnerCode: row.partnerCode,
|
partnerCode: row.partnerCode,
|
||||||
@@ -258,11 +294,13 @@ function savePayload(): SavePlatformPartnerRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openDetail(row: PlatformPartnerResource) {
|
async function openDetail(row: PlatformPartnerResource) {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
detailOpen.value = true
|
detailOpen.value = true
|
||||||
detailLoading.value = true
|
detailLoading.value = true
|
||||||
detail.value = null
|
detail.value = null
|
||||||
try {
|
try {
|
||||||
detail.value = await getPlatformPartner(fixedTenantId, row.id)
|
detail.value = await getPlatformPartner(tenantId, row.id)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const meta = getApiErrorDetails(error, '往来单位详情加载失败')
|
const meta = getApiErrorDetails(error, '往来单位详情加载失败')
|
||||||
ElMessage.error(meta.requestId ? `${meta.message}(requestId: ${meta.requestId})` : meta.message)
|
ElMessage.error(meta.requestId ? `${meta.message}(requestId: ${meta.requestId})` : meta.message)
|
||||||
@@ -305,6 +343,8 @@ async function downloadTemplate() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submitImport() {
|
async function submitImport() {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
if (!importFile.value) {
|
if (!importFile.value) {
|
||||||
ElMessage.warning('请先选择 XLSX 文件')
|
ElMessage.warning('请先选择 XLSX 文件')
|
||||||
return
|
return
|
||||||
@@ -312,7 +352,7 @@ async function submitImport() {
|
|||||||
importing.value = true
|
importing.value = true
|
||||||
importResult.value = null
|
importResult.value = null
|
||||||
try {
|
try {
|
||||||
importResult.value = await importPlatformPartners(fixedTenantId, importFile.value)
|
importResult.value = await importPlatformPartners(tenantId, importFile.value)
|
||||||
if (importResult.value.success) {
|
if (importResult.value.success) {
|
||||||
ElMessage.success(`成功导入 ${importResult.value.importedRows} 条往来单位`)
|
ElMessage.success(`成功导入 ${importResult.value.importedRows} 条往来单位`)
|
||||||
await loadPartners()
|
await loadPartners()
|
||||||
@@ -342,16 +382,18 @@ function downloadImportErrors() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function savePartner() {
|
async function savePartner() {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
const valid = await formRef.value?.validate().catch(() => false)
|
const valid = await formRef.value?.validate().catch(() => false)
|
||||||
if (!valid) return
|
if (!valid) return
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const payload = savePayload()
|
const payload = savePayload()
|
||||||
if (form.id) {
|
if (form.id) {
|
||||||
await updatePlatformPartner(fixedTenantId, form.id, payload)
|
await updatePlatformPartner(tenantId, form.id, payload)
|
||||||
ElMessage.success('往来单位已更新')
|
ElMessage.success('往来单位已更新')
|
||||||
} else {
|
} else {
|
||||||
await createPlatformPartner(fixedTenantId, payload)
|
await createPlatformPartner(tenantId, payload)
|
||||||
ElMessage.success('往来单位已新增')
|
ElMessage.success('往来单位已新增')
|
||||||
}
|
}
|
||||||
editorOpen.value = false
|
editorOpen.value = false
|
||||||
@@ -365,6 +407,8 @@ async function savePartner() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function toggleStatus(row: PlatformPartnerResource) {
|
async function toggleStatus(row: PlatformPartnerResource) {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
const nextStatus: PlatformPartnerStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
const nextStatus: PlatformPartnerStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
||||||
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
|
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
|
||||||
try {
|
try {
|
||||||
@@ -379,7 +423,7 @@ async function toggleStatus(row: PlatformPartnerResource) {
|
|||||||
const id = String(row.id)
|
const id = String(row.id)
|
||||||
statusLoadingIds.value = new Set(statusLoadingIds.value).add(id)
|
statusLoadingIds.value = new Set(statusLoadingIds.value).add(id)
|
||||||
try {
|
try {
|
||||||
await changePlatformPartnerStatus(fixedTenantId, row.id, nextStatus)
|
await changePlatformPartnerStatus(tenantId, row.id, nextStatus)
|
||||||
ElMessage.success(`往来单位已${action}`)
|
ElMessage.success(`往来单位已${action}`)
|
||||||
await loadPartners()
|
await loadPartners()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -397,12 +441,24 @@ function formatUpdatedAt(value?: string | null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
watch([page, pageSize], () => { void loadPartners() })
|
watch([page, pageSize], () => { void loadPartners() })
|
||||||
|
watch(selectedTenantId, (tenantId) => {
|
||||||
onMounted(loadPartners)
|
editorOpen.value = false
|
||||||
|
detailOpen.value = false
|
||||||
|
importOpen.value = false
|
||||||
|
detail.value = null
|
||||||
|
importFile.value = null
|
||||||
|
importResult.value = null
|
||||||
|
rows.value = []
|
||||||
|
total.value = 0
|
||||||
|
loadedTenantId.value = null
|
||||||
|
page.value = 1
|
||||||
|
void loadPartners(tenantId)
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="business-page partners-page">
|
<div class="business-page partners-page">
|
||||||
|
<PlatformTenantSelector v-model="selectedTenantId" :disabled="tenantSwitchDisabled" />
|
||||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="往来单位筛选" :fields="queryFields" @search="searchPartners" />
|
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="往来单位筛选" :fields="queryFields" @search="searchPartners" />
|
||||||
|
|
||||||
<section v-if="loadError" class="surface-panel partners-error" role="alert">
|
<section v-if="loadError" class="surface-panel partners-error" role="alert">
|
||||||
@@ -411,18 +467,18 @@ onMounted(loadPartners)
|
|||||||
<p>{{ loadError.message }}</p>
|
<p>{{ loadError.message }}</p>
|
||||||
<ApiErrorMeta :details="loadError" />
|
<ApiErrorMeta :details="loadError" />
|
||||||
</div>
|
</div>
|
||||||
<el-button type="primary" :loading="loading" @click="loadPartners">重新加载</el-button>
|
<el-button type="primary" :loading="loading" @click="loadPartners()">重新加载</el-button>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section v-else class="surface-panel table-panel" :aria-busy="loading">
|
<section v-else class="surface-panel table-panel" :aria-busy="loading">
|
||||||
<div class="partners-table-header">
|
<div class="partners-table-header">
|
||||||
<div class="partners-table-heading">
|
<div class="partners-table-heading">
|
||||||
<h2>往来单位列表</h2>
|
<h2>往来单位列表</h2>
|
||||||
<span>共 {{ total }} 个往来单位</span>
|
<span>租户 {{ selectedTenantId || '—' }} · 共 {{ total }} 个往来单位</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="partners-primary-actions">
|
<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:import')" :disabled="loading || !tenantReady" @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>
|
<el-button v-if="access.can('platform:counterparty:create')" type="primary" :disabled="loading || !tenantReady" @click="openCreate"><Plus :size="16" />新增往来单位</el-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DataTable
|
<DataTable
|
||||||
@@ -440,8 +496,8 @@ onMounted(loadPartners)
|
|||||||
<template #actions="{ row }">
|
<template #actions="{ row }">
|
||||||
<div class="table-actions">
|
<div class="table-actions">
|
||||||
<el-button link type="primary" @click="openDetail(row as PlatformPartnerResource)"><Eye :size="15" />详情</el-button>
|
<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:edit')" link type="primary" :disabled="!tenantReady" @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>
|
<el-button v-if="access.can('platform:counterparty:status')" link :disabled="!tenantReady" :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>
|
</div>
|
||||||
</template>
|
</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 #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>
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ export interface PlatformExpressCompanyImportResult {
|
|||||||
const basePath = '/platform/v1/express-companies'
|
const basePath = '/platform/v1/express-companies'
|
||||||
|
|
||||||
export async function listPlatformExpressCompanies(
|
export async function listPlatformExpressCompanies(
|
||||||
tenantId: number,
|
tenantId: number | string,
|
||||||
page = 1,
|
page = 1,
|
||||||
size = 20,
|
size = 20,
|
||||||
keyword = '',
|
keyword = '',
|
||||||
@@ -76,7 +76,7 @@ export async function listPlatformExpressCompanies(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPlatformExpressCompany(tenantId: number, id: number | string) {
|
export async function getPlatformExpressCompany(tenantId: number | string, id: number | string) {
|
||||||
const response = await http.get<ApiEnvelope<PlatformExpressCompanyResource>, ApiEnvelope<PlatformExpressCompanyResource>>(
|
const response = await http.get<ApiEnvelope<PlatformExpressCompanyResource>, ApiEnvelope<PlatformExpressCompanyResource>>(
|
||||||
`${basePath}/${id}`,
|
`${basePath}/${id}`,
|
||||||
{ params: { tenantId } },
|
{ params: { tenantId } },
|
||||||
@@ -84,7 +84,7 @@ export async function getPlatformExpressCompany(tenantId: number, id: number | s
|
|||||||
return unwrapApiResponse(response)
|
return unwrapApiResponse(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createPlatformExpressCompany(tenantId: number, payload: SavePlatformExpressCompanyRequest) {
|
export async function createPlatformExpressCompany(tenantId: number | string, payload: SavePlatformExpressCompanyRequest) {
|
||||||
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
|
const response = await http.post<ApiEnvelope<number | string>, ApiEnvelope<number | string>>(basePath, payload, {
|
||||||
params: { tenantId },
|
params: { tenantId },
|
||||||
})
|
})
|
||||||
@@ -92,7 +92,7 @@ export async function createPlatformExpressCompany(tenantId: number, payload: Sa
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function updatePlatformExpressCompany(
|
export async function updatePlatformExpressCompany(
|
||||||
tenantId: number,
|
tenantId: number | string,
|
||||||
id: number | string,
|
id: number | string,
|
||||||
payload: SavePlatformExpressCompanyRequest,
|
payload: SavePlatformExpressCompanyRequest,
|
||||||
) {
|
) {
|
||||||
@@ -103,7 +103,7 @@ export async function updatePlatformExpressCompany(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function changePlatformExpressCompanyStatus(
|
export async function changePlatformExpressCompanyStatus(
|
||||||
tenantId: number,
|
tenantId: number | string,
|
||||||
id: number | string,
|
id: number | string,
|
||||||
status: PlatformExpressCompanyStatus,
|
status: PlatformExpressCompanyStatus,
|
||||||
) {
|
) {
|
||||||
@@ -117,7 +117,7 @@ export async function downloadPlatformExpressCompanyImportTemplate() {
|
|||||||
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
|
return http.get<Blob, Blob>(`${basePath}/import-template`, { responseType: 'blob' })
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function importPlatformExpressCompanies(tenantId: number, file: File) {
|
export async function importPlatformExpressCompanies(tenantId: number | string, file: File) {
|
||||||
const formData = new FormData()
|
const formData = new FormData()
|
||||||
formData.append('file', file)
|
formData.append('file', file)
|
||||||
const response = await http.post<ApiEnvelope<PlatformExpressCompanyImportResult>, ApiEnvelope<PlatformExpressCompanyImportResult>>(
|
const response = await http.post<ApiEnvelope<PlatformExpressCompanyImportResult>, ApiEnvelope<PlatformExpressCompanyImportResult>>(
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vites
|
|||||||
import { listPlatformExpressCompanies, type PlatformExpressCompanyResource } from '@/modules/master-data/express-companies/api/platformExpressCompanies'
|
import { listPlatformExpressCompanies, type PlatformExpressCompanyResource } from '@/modules/master-data/express-companies/api/platformExpressCompanies'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
import { useAuthStore } from '@/core/auth/auth'
|
||||||
|
import { listPlatformTenants, type PlatformTenantResource } from '../../../iam/api/platformIam'
|
||||||
|
import PlatformTenantSelector from '../../../iam/components/PlatformTenantSelector.vue'
|
||||||
import ExpressCompaniesView from './ExpressCompaniesView.vue'
|
import ExpressCompaniesView from './ExpressCompaniesView.vue'
|
||||||
|
|
||||||
vi.mock('@/modules/master-data/express-companies/api/platformExpressCompanies', () => ({
|
vi.mock('@/modules/master-data/express-companies/api/platformExpressCompanies', () => ({
|
||||||
@@ -14,6 +16,8 @@ vi.mock('@/modules/master-data/express-companies/api/platformExpressCompanies',
|
|||||||
changePlatformExpressCompanyStatus: vi.fn(),
|
changePlatformExpressCompanyStatus: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../../iam/api/platformIam', () => ({ listPlatformTenants: vi.fn() }))
|
||||||
|
|
||||||
class ResizeObserverStub implements ResizeObserver {
|
class ResizeObserverStub implements ResizeObserver {
|
||||||
observe() {}
|
observe() {}
|
||||||
unobserve() {}
|
unobserve() {}
|
||||||
@@ -45,6 +49,16 @@ const company: PlatformExpressCompanyResource = {
|
|||||||
updatedAt: '2026-07-31T10:20:00',
|
updatedAt: '2026-07-31T10:20:00',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tenant = (id: number | string, tenantName: string): PlatformTenantResource => ({
|
||||||
|
id, tenantCode: String(id), tenantName, status: 'ACTIVE', legalName: tenantName,
|
||||||
|
legalRepresentative: null, unifiedSocialCreditCode: null, contactName: null,
|
||||||
|
contactPhone: null, contactEmail: null, servicePackage: null, contactWechat: null,
|
||||||
|
salesOwnerName: null, paymentTermDays: null, enterpriseType: null, establishedDate: null,
|
||||||
|
registeredCapital: null, registeredCapitalCurrency: null, registeredAddress: null,
|
||||||
|
internalRemark: null, createdAt: null, approvedAt: null,
|
||||||
|
})
|
||||||
|
const snowflakeTenantId = '9223372036854775806'
|
||||||
|
|
||||||
async function mountView() {
|
async function mountView() {
|
||||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||||
@@ -69,6 +83,9 @@ describe('ExpressCompaniesView query and table migration', () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||||
document.body.innerHTML = ''
|
document.body.innerHTML = ''
|
||||||
|
vi.mocked(listPlatformTenants).mockReset().mockResolvedValue({
|
||||||
|
records: [tenant(10001, '默认企业'), tenant(snowflakeTenantId, '雪花企业')], page: 1, size: 200, total: 2, pages: 1,
|
||||||
|
})
|
||||||
vi.mocked(listPlatformExpressCompanies).mockReset().mockResolvedValue({
|
vi.mocked(listPlatformExpressCompanies).mockReset().mockResolvedValue({
|
||||||
records: [company], page: 1, size: 20, total: 1, pages: 1,
|
records: [company], page: 1, size: 20, total: 1, pages: 1,
|
||||||
})
|
})
|
||||||
@@ -95,4 +112,13 @@ describe('ExpressCompaniesView query and table migration', () => {
|
|||||||
|
|
||||||
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(10001, 1, 20, '顺丰', '')
|
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(10001, 1, 20, '顺丰', '')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('preserves a snowflake tenant id as a string when switching enterprises', async () => {
|
||||||
|
const wrapper = await mountView()
|
||||||
|
|
||||||
|
wrapper.findComponent(PlatformTenantSelector).vm.$emit('update:modelValue', snowflakeTenantId)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(listPlatformExpressCompanies).toHaveBeenLastCalledWith(snowflakeTenantId, 1, 20, '', '')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
import { computed, reactive, ref, watch } from 'vue'
|
||||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||||
import { Download, ExternalLink, FileSpreadsheet, Pencil, Plus, Power, Truck, Upload } from '@lucide/vue'
|
import { Download, ExternalLink, FileSpreadsheet, Pencil, Plus, Power, Truck, Upload } from '@lucide/vue'
|
||||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||||
@@ -21,8 +21,8 @@ import {
|
|||||||
type SavePlatformExpressCompanyRequest,
|
type SavePlatformExpressCompanyRequest,
|
||||||
} from '@/modules/master-data/express-companies/api/platformExpressCompanies'
|
} from '@/modules/master-data/express-companies/api/platformExpressCompanies'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
|
import { PlatformTenantSelector } from '@/modules/iam'
|
||||||
|
|
||||||
const fixedTenantId = 10001
|
|
||||||
const access = useAccessPreviewStore()
|
const access = useAccessPreviewStore()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const saving = ref(false)
|
const saving = ref(false)
|
||||||
@@ -34,6 +34,8 @@ const rows = ref<PlatformExpressCompanyResource[]>([])
|
|||||||
const page = ref(1)
|
const page = ref(1)
|
||||||
const pageSize = ref(20)
|
const pageSize = ref(20)
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
|
const selectedTenantId = ref('')
|
||||||
|
const loadedTenantId = ref<string | null>(null)
|
||||||
const loadError = ref<ApiErrorDetails | null>(null)
|
const loadError = ref<ApiErrorDetails | null>(null)
|
||||||
const statusLoadingIds = ref(new Set<string>())
|
const statusLoadingIds = ref(new Set<string>())
|
||||||
const editLoadingIds = ref(new Set<string>())
|
const editLoadingIds = ref(new Set<string>())
|
||||||
@@ -91,6 +93,16 @@ const { captureBaseline } = useUnsavedWorkRegistration({
|
|||||||
requiredPermission: editorPermission,
|
requiredPermission: editorPermission,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const tenantReady = computed(() => Boolean(selectedTenantId.value)
|
||||||
|
&& loadedTenantId.value === selectedTenantId.value
|
||||||
|
&& !loading.value)
|
||||||
|
const tenantSwitchDisabled = computed(() => editorOpen.value
|
||||||
|
|| importOpen.value
|
||||||
|
|| saving.value
|
||||||
|
|| importing.value
|
||||||
|
|| editLoadingIds.value.size > 0
|
||||||
|
|| statusLoadingIds.value.size > 0)
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => access.can(editorPermission.value),
|
() => access.can(editorPermission.value),
|
||||||
(canWrite) => {
|
(canWrite) => {
|
||||||
@@ -131,13 +143,27 @@ const expressCompanyColumns: DataTableColumn[] = [
|
|||||||
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
|
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
|
||||||
]
|
]
|
||||||
|
|
||||||
async function loadExpressCompanies() {
|
function apiTenantId(value: string) {
|
||||||
|
const numeric = Number(value)
|
||||||
|
return Number.isSafeInteger(numeric) ? numeric : value
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireCurrentTenant() {
|
||||||
|
if (!tenantReady.value) {
|
||||||
|
ElMessage.warning('快递公司数据尚未加载完成,请稍后重试')
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return apiTenantId(selectedTenantId.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadExpressCompanies(tenantId = selectedTenantId.value) {
|
||||||
|
if (!tenantId) return
|
||||||
const sequence = ++loadSequence
|
const sequence = ++loadSequence
|
||||||
loading.value = true
|
loading.value = true
|
||||||
loadError.value = null
|
loadError.value = null
|
||||||
try {
|
try {
|
||||||
const result = await listPlatformExpressCompanies(
|
const result = await listPlatformExpressCompanies(
|
||||||
fixedTenantId,
|
apiTenantId(tenantId),
|
||||||
page.value,
|
page.value,
|
||||||
pageSize.value,
|
pageSize.value,
|
||||||
appliedFilters.value.keyword,
|
appliedFilters.value.keyword,
|
||||||
@@ -146,6 +172,7 @@ async function loadExpressCompanies() {
|
|||||||
if (sequence !== loadSequence) return
|
if (sequence !== loadSequence) return
|
||||||
rows.value = result.records
|
rows.value = result.records
|
||||||
total.value = result.total
|
total.value = result.total
|
||||||
|
loadedTenantId.value = tenantId
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (sequence !== loadSequence) return
|
if (sequence !== loadSequence) return
|
||||||
rows.value = []
|
rows.value = []
|
||||||
@@ -169,6 +196,7 @@ function applyFilters(model: QueryModel) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
|
if (!requireCurrentTenant()) return
|
||||||
Object.assign(form, emptyForm())
|
Object.assign(form, emptyForm())
|
||||||
captureBaseline()
|
captureBaseline()
|
||||||
editorOpen.value = true
|
editorOpen.value = true
|
||||||
@@ -192,12 +220,14 @@ function assignEditor(row: PlatformExpressCompanyResource) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openEdit(row: PlatformExpressCompanyResource) {
|
async function openEdit(row: PlatformExpressCompanyResource) {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
const id = String(row.id)
|
const id = String(row.id)
|
||||||
const pending = new Set(editLoadingIds.value)
|
const pending = new Set(editLoadingIds.value)
|
||||||
pending.add(id)
|
pending.add(id)
|
||||||
editLoadingIds.value = pending
|
editLoadingIds.value = pending
|
||||||
try {
|
try {
|
||||||
assignEditor(await getPlatformExpressCompany(fixedTenantId, row.id))
|
assignEditor(await getPlatformExpressCompany(tenantId, row.id))
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const details = getApiErrorDetails(error, '快递公司详情加载失败,请稍后重试')
|
const details = getApiErrorDetails(error, '快递公司详情加载失败,请稍后重试')
|
||||||
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
ElMessage.error(details.requestId ? `${details.message}(requestId: ${details.requestId})` : details.message)
|
||||||
@@ -262,6 +292,8 @@ function selectImportFile(event: Event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submitImport() {
|
async function submitImport() {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
if (!importFile.value) {
|
if (!importFile.value) {
|
||||||
ElMessage.warning('请先选择填写完成的 XLSX 文件')
|
ElMessage.warning('请先选择填写完成的 XLSX 文件')
|
||||||
return
|
return
|
||||||
@@ -270,7 +302,7 @@ async function submitImport() {
|
|||||||
importError.value = null
|
importError.value = null
|
||||||
importResult.value = null
|
importResult.value = null
|
||||||
try {
|
try {
|
||||||
const result = await importPlatformExpressCompanies(fixedTenantId, importFile.value)
|
const result = await importPlatformExpressCompanies(tenantId, importFile.value)
|
||||||
importResult.value = result
|
importResult.value = result
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
ElMessage.success(`成功导入 ${result.importedRows} 家快递公司`)
|
ElMessage.success(`成功导入 ${result.importedRows} 家快递公司`)
|
||||||
@@ -308,13 +340,15 @@ function buildPayload(): SavePlatformExpressCompanyRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function saveExpressCompany() {
|
async function saveExpressCompany() {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
const valid = await formRef.value?.validate().catch(() => false)
|
const valid = await formRef.value?.validate().catch(() => false)
|
||||||
if (!valid) return
|
if (!valid) return
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
try {
|
||||||
const payload = buildPayload()
|
const payload = buildPayload()
|
||||||
if (form.id) await updatePlatformExpressCompany(fixedTenantId, form.id, payload)
|
if (form.id) await updatePlatformExpressCompany(tenantId, form.id, payload)
|
||||||
else await createPlatformExpressCompany(fixedTenantId, payload)
|
else await createPlatformExpressCompany(tenantId, payload)
|
||||||
editorOpen.value = false
|
editorOpen.value = false
|
||||||
ElMessage.success(form.id ? '快递公司资料已更新' : '快递公司已创建')
|
ElMessage.success(form.id ? '快递公司资料已更新' : '快递公司已创建')
|
||||||
await loadExpressCompanies()
|
await loadExpressCompanies()
|
||||||
@@ -327,6 +361,8 @@ async function saveExpressCompany() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function toggleStatus(row: PlatformExpressCompanyResource) {
|
async function toggleStatus(row: PlatformExpressCompanyResource) {
|
||||||
|
const tenantId = requireCurrentTenant()
|
||||||
|
if (!tenantId) return
|
||||||
const nextStatus: PlatformExpressCompanyStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
const nextStatus: PlatformExpressCompanyStatus = row.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
|
||||||
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
|
const action = nextStatus === 'ACTIVE' ? '启用' : '停用'
|
||||||
try {
|
try {
|
||||||
@@ -343,7 +379,7 @@ async function toggleStatus(row: PlatformExpressCompanyResource) {
|
|||||||
pending.add(id)
|
pending.add(id)
|
||||||
statusLoadingIds.value = pending
|
statusLoadingIds.value = pending
|
||||||
try {
|
try {
|
||||||
await changePlatformExpressCompanyStatus(fixedTenantId, row.id, nextStatus)
|
await changePlatformExpressCompanyStatus(tenantId, row.id, nextStatus)
|
||||||
ElMessage.success(`已${action}${row.companyName}`)
|
ElMessage.success(`已${action}${row.companyName}`)
|
||||||
await loadExpressCompanies()
|
await loadExpressCompanies()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -357,19 +393,28 @@ async function toggleStatus(row: PlatformExpressCompanyResource) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
watch([page, pageSize], () => { void loadExpressCompanies() })
|
watch([page, pageSize], () => { void loadExpressCompanies() })
|
||||||
|
watch(selectedTenantId, (tenantId) => {
|
||||||
onMounted(() => {
|
editorOpen.value = false
|
||||||
void loadExpressCompanies()
|
importOpen.value = false
|
||||||
|
importFile.value = null
|
||||||
|
importResult.value = null
|
||||||
|
importError.value = null
|
||||||
|
rows.value = []
|
||||||
|
total.value = 0
|
||||||
|
loadedTenantId.value = null
|
||||||
|
page.value = 1
|
||||||
|
void loadExpressCompanies(tenantId)
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="business-page express-company-page">
|
<div class="business-page express-company-page">
|
||||||
|
<PlatformTenantSelector v-model="selectedTenantId" :disabled="tenantSwitchDisabled" />
|
||||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
|
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
|
||||||
<template #title>快递公司加载失败</template>
|
<template #title>快递公司加载失败</template>
|
||||||
<p>{{ loadError.message }}</p>
|
<p>{{ loadError.message }}</p>
|
||||||
<ApiErrorMeta :details="loadError" />
|
<ApiErrorMeta :details="loadError" />
|
||||||
<el-button size="small" @click="loadExpressCompanies">重新查询</el-button>
|
<el-button size="small" @click="loadExpressCompanies()">重新查询</el-button>
|
||||||
</el-alert>
|
</el-alert>
|
||||||
|
|
||||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="快递公司筛选" :fields="queryFields" @search="applyFilters" />
|
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="快递公司筛选" :fields="queryFields" @search="applyFilters" />
|
||||||
@@ -378,11 +423,11 @@ onMounted(() => {
|
|||||||
<div class="panel-heading">
|
<div class="panel-heading">
|
||||||
<div>
|
<div>
|
||||||
<h2>快递公司列表</h2>
|
<h2>快递公司列表</h2>
|
||||||
<p>共 {{ total }} 家快递公司</p>
|
<p>租户 {{ selectedTenantId || '—' }} · 共 {{ total }} 家快递公司</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="panel-actions">
|
<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:import')" :disabled="!tenantReady" @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>
|
<el-button v-if="access.can('platform:express:create')" type="primary" :disabled="!tenantReady" @click="openCreate"><Plus :size="16" />新增快递公司</el-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DataTable
|
<DataTable
|
||||||
@@ -403,12 +448,14 @@ onMounted(() => {
|
|||||||
v-if="access.can('platform:express:edit')"
|
v-if="access.can('platform:express:edit')"
|
||||||
link
|
link
|
||||||
type="primary"
|
type="primary"
|
||||||
|
:disabled="!tenantReady"
|
||||||
:loading="editLoadingIds.has(String((row as PlatformExpressCompanyResource).id))"
|
:loading="editLoadingIds.has(String((row as PlatformExpressCompanyResource).id))"
|
||||||
@click="openEdit(row as PlatformExpressCompanyResource)"
|
@click="openEdit(row as PlatformExpressCompanyResource)"
|
||||||
><Pencil :size="15" />编辑</el-button>
|
><Pencil :size="15" />编辑</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
v-if="access.can('platform:express:status')"
|
v-if="access.can('platform:express:status')"
|
||||||
link
|
link
|
||||||
|
:disabled="!tenantReady"
|
||||||
:type="(row as PlatformExpressCompanyResource).status === 'ACTIVE' ? 'danger' : 'success'"
|
:type="(row as PlatformExpressCompanyResource).status === 'ACTIVE' ? 'danger' : 'success'"
|
||||||
:loading="statusLoadingIds.has(String((row as PlatformExpressCompanyResource).id))"
|
:loading="statusLoadingIds.has(String((row as PlatformExpressCompanyResource).id))"
|
||||||
@click="toggleStatus(row as PlatformExpressCompanyResource)"
|
@click="toggleStatus(row as PlatformExpressCompanyResource)"
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ export interface PlatformWarehouseCapabilityRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface SavePlatformWarehouseRequest {
|
export interface SavePlatformWarehouseRequest {
|
||||||
tenantId: number
|
tenantId: number | string
|
||||||
warehouseCode: string
|
warehouseCode: string
|
||||||
warehouseName: string
|
warehouseName: string
|
||||||
warehouseType: string
|
warehouseType: string
|
||||||
@@ -99,14 +99,14 @@ export interface SavePlatformWarehouseRequest {
|
|||||||
|
|
||||||
const basePath = '/platform/v1/warehouse-admin'
|
const basePath = '/platform/v1/warehouse-admin'
|
||||||
|
|
||||||
export async function listPlatformWarehouses(tenantId: number, page = 1, size = 200) {
|
export async function listPlatformWarehouses(tenantId: number | string, page = 1, size = 200) {
|
||||||
const response = await http.get<ApiEnvelope<PlatformWarehousePage>, ApiEnvelope<PlatformWarehousePage>>(basePath, {
|
const response = await http.get<ApiEnvelope<PlatformWarehousePage>, ApiEnvelope<PlatformWarehousePage>>(basePath, {
|
||||||
params: { tenantId, page, size },
|
params: { tenantId, page, size },
|
||||||
})
|
})
|
||||||
return unwrapApiResponse(response)
|
return unwrapApiResponse(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPlatformWarehouse(tenantId: number, warehouseId: number | string) {
|
export async function getPlatformWarehouse(tenantId: number | string, warehouseId: number | string) {
|
||||||
const response = await http.get<ApiEnvelope<PlatformWarehouseDetailResource>, ApiEnvelope<PlatformWarehouseDetailResource>>(
|
const response = await http.get<ApiEnvelope<PlatformWarehouseDetailResource>, ApiEnvelope<PlatformWarehouseDetailResource>>(
|
||||||
`${basePath}/${warehouseId}`,
|
`${basePath}/${warehouseId}`,
|
||||||
{ params: { tenantId } },
|
{ params: { tenantId } },
|
||||||
@@ -119,7 +119,7 @@ export async function createPlatformWarehouse(payload: SavePlatformWarehouseRequ
|
|||||||
return unwrapApiResponse(response)
|
return unwrapApiResponse(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updatePlatformWarehouse(tenantId: number, warehouseId: number | string, payload: SavePlatformWarehouseRequest) {
|
export async function updatePlatformWarehouse(tenantId: number | string, warehouseId: number | string, payload: SavePlatformWarehouseRequest) {
|
||||||
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${warehouseId}`, payload, {
|
const response = await http.put<ApiEnvelope<null>, ApiEnvelope<null>>(`${basePath}/${warehouseId}`, payload, {
|
||||||
params: { tenantId },
|
params: { tenantId },
|
||||||
})
|
})
|
||||||
@@ -127,7 +127,7 @@ export async function updatePlatformWarehouse(tenantId: number, warehouseId: num
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function changePlatformWarehouseStatus(
|
export async function changePlatformWarehouseStatus(
|
||||||
tenantId: number,
|
tenantId: number | string,
|
||||||
warehouseId: number | string,
|
warehouseId: number | string,
|
||||||
status: PlatformWarehouseStatus,
|
status: PlatformWarehouseStatus,
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import {
|
|||||||
} from '@/modules/warehouses/api/platformWarehouses'
|
} from '@/modules/warehouses/api/platformWarehouses'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
import { useAuthStore } from '@/core/auth/auth'
|
import { useAuthStore } from '@/core/auth/auth'
|
||||||
|
import { listPlatformTenants, type PlatformTenantResource } from '../../iam/api/platformIam'
|
||||||
|
import PlatformTenantSelector from '../../iam/components/PlatformTenantSelector.vue'
|
||||||
import WarehousesView from './WarehousesView.vue'
|
import WarehousesView from './WarehousesView.vue'
|
||||||
|
|
||||||
vi.mock('@/modules/warehouses/api/platformWarehouses', () => ({
|
vi.mock('@/modules/warehouses/api/platformWarehouses', () => ({
|
||||||
@@ -22,6 +24,8 @@ vi.mock('@/modules/warehouses/api/platformWarehouses', () => ({
|
|||||||
changePlatformWarehouseStatus: vi.fn(),
|
changePlatformWarehouseStatus: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../iam/api/platformIam', () => ({ listPlatformTenants: vi.fn() }))
|
||||||
|
|
||||||
class ResizeObserverStub implements ResizeObserver {
|
class ResizeObserverStub implements ResizeObserver {
|
||||||
observe() {}
|
observe() {}
|
||||||
unobserve() {}
|
unobserve() {}
|
||||||
@@ -56,6 +60,16 @@ const warehouse: PlatformWarehouseResource = {
|
|||||||
updatedAt: '2026-07-31T10:20:00',
|
updatedAt: '2026-07-31T10:20:00',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tenant = (id: number | string, tenantName: string): PlatformTenantResource => ({
|
||||||
|
id, tenantCode: String(id), tenantName, status: 'ACTIVE', legalName: tenantName,
|
||||||
|
legalRepresentative: null, unifiedSocialCreditCode: null, contactName: null,
|
||||||
|
contactPhone: null, contactEmail: null, servicePackage: null, contactWechat: null,
|
||||||
|
salesOwnerName: null, paymentTermDays: null, enterpriseType: null, establishedDate: null,
|
||||||
|
registeredCapital: null, registeredCapitalCurrency: null, registeredAddress: null,
|
||||||
|
internalRemark: null, createdAt: null, approvedAt: null,
|
||||||
|
})
|
||||||
|
const snowflakeTenantId = '9223372036854775806'
|
||||||
|
|
||||||
const detail: PlatformWarehouseDetailResource = {
|
const detail: PlatformWarehouseDetailResource = {
|
||||||
warehouse,
|
warehouse,
|
||||||
addresses: [{
|
addresses: [{
|
||||||
@@ -94,6 +108,9 @@ describe('WarehousesView real API integration', () => {
|
|||||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||||
document.body.innerHTML = ''
|
document.body.innerHTML = ''
|
||||||
vi.mocked(listPlatformWarehouses).mockReset().mockResolvedValue({ records: [warehouse], page: 1, size: 200, total: 1, pages: 1 })
|
vi.mocked(listPlatformWarehouses).mockReset().mockResolvedValue({ records: [warehouse], page: 1, size: 200, total: 1, pages: 1 })
|
||||||
|
vi.mocked(listPlatformTenants).mockReset().mockResolvedValue({
|
||||||
|
records: [tenant(10001, '默认企业'), tenant(snowflakeTenantId, '雪花企业')], page: 1, size: 200, total: 2, pages: 1,
|
||||||
|
})
|
||||||
vi.mocked(getPlatformWarehouse).mockReset().mockResolvedValue(detail)
|
vi.mocked(getPlatformWarehouse).mockReset().mockResolvedValue(detail)
|
||||||
vi.mocked(createPlatformWarehouse).mockReset().mockResolvedValue('19005')
|
vi.mocked(createPlatformWarehouse).mockReset().mockResolvedValue('19005')
|
||||||
vi.mocked(updatePlatformWarehouse).mockReset().mockResolvedValue(null)
|
vi.mocked(updatePlatformWarehouse).mockReset().mockResolvedValue(null)
|
||||||
@@ -129,14 +146,23 @@ describe('WarehousesView real API integration', () => {
|
|||||||
expect(wrapper.text()).toContain('测试环境收货仓')
|
expect(wrapper.text()).toContain('测试环境收货仓')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('does not render a tenant selector during the single-tenant phase', async () => {
|
it('renders an explicit tenant selector and defaults to tenant 10001', async () => {
|
||||||
const wrapper = await mountView()
|
const wrapper = await mountView()
|
||||||
|
|
||||||
expect(wrapper.find('[aria-label="目标租户 ID"]').exists()).toBe(false)
|
expect(wrapper.find('[aria-label="目标企业"]').exists()).toBe(true)
|
||||||
expect(wrapper.text()).not.toContain('查询仓库')
|
expect(wrapper.text()).not.toContain('查询仓库')
|
||||||
expect(wrapper.text()).toContain('租户 10001')
|
expect(wrapper.text()).toContain('租户 10001')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('preserves a snowflake tenant id as a string when switching enterprises', async () => {
|
||||||
|
const wrapper = await mountView()
|
||||||
|
|
||||||
|
wrapper.findComponent(PlatformTenantSelector).vm.$emit('update:modelValue', snowflakeTenantId)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(listPlatformWarehouses).toHaveBeenLastCalledWith(snowflakeTenantId, 1, 200)
|
||||||
|
})
|
||||||
|
|
||||||
it('shows a recoverable real API error without falling back to demo warehouses', async () => {
|
it('shows a recoverable real API error without falling back to demo warehouses', async () => {
|
||||||
vi.mocked(listPlatformWarehouses).mockRejectedValueOnce(new Error('Gateway unavailable'))
|
vi.mocked(listPlatformWarehouses).mockRejectedValueOnce(new Error('Gateway unavailable'))
|
||||||
const wrapper = await mountView()
|
const wrapper = await mountView()
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
import { computed, reactive, ref, watch } from 'vue'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
import { MapPin, Pencil, Plus, Power, Warehouse as WarehouseIcon } from '@lucide/vue'
|
import { MapPin, Pencil, Plus, Power, Warehouse as WarehouseIcon } from '@lucide/vue'
|
||||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||||
@@ -17,16 +17,18 @@ import {
|
|||||||
type SavePlatformWarehouseRequest,
|
type SavePlatformWarehouseRequest,
|
||||||
} from '@/modules/warehouses/api/platformWarehouses'
|
} from '@/modules/warehouses/api/platformWarehouses'
|
||||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||||
|
import { PlatformTenantSelector } from '@/modules/iam'
|
||||||
import type { Warehouse } from '@/modules/warehouses/types'
|
import type { Warehouse } from '@/modules/warehouses/types'
|
||||||
|
|
||||||
const fixedTenantId = 10001
|
|
||||||
const access = useAccessPreviewStore()
|
const access = useAccessPreviewStore()
|
||||||
const editorOpen = ref(false)
|
const editorOpen = ref(false)
|
||||||
const saving = ref(false)
|
const saving = ref(false)
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
|
const editLoading = ref(false)
|
||||||
const page = ref(1)
|
const page = ref(1)
|
||||||
const pageSize = ref(10)
|
const pageSize = ref(10)
|
||||||
const loadedTenantId = ref<number | null>(null)
|
const selectedTenantId = ref('')
|
||||||
|
const loadedTenantId = ref<string | null>(null)
|
||||||
const loadError = ref<ApiErrorDetails | null>(null)
|
const loadError = ref<ApiErrorDetails | null>(null)
|
||||||
const detailWarningCount = ref(0)
|
const detailWarningCount = ref(0)
|
||||||
const statusLoadingIds = ref(new Set<string>())
|
const statusLoadingIds = ref(new Set<string>())
|
||||||
@@ -82,7 +84,13 @@ const { captureBaseline } = useUnsavedWorkRegistration({
|
|||||||
requiredPermission: editorPermission,
|
requiredPermission: editorPermission,
|
||||||
})
|
})
|
||||||
|
|
||||||
const warehouseReady = computed(() => loadedTenantId.value === fixedTenantId && !loading.value)
|
const warehouseReady = computed(() => Boolean(selectedTenantId.value)
|
||||||
|
&& loadedTenantId.value === selectedTenantId.value
|
||||||
|
&& !loading.value)
|
||||||
|
const tenantSwitchDisabled = computed(() => editorOpen.value
|
||||||
|
|| editLoading.value
|
||||||
|
|| saving.value
|
||||||
|
|| statusLoadingIds.value.size > 0)
|
||||||
const filteredRows = computed(() => rows.value.filter((warehouse) => {
|
const filteredRows = computed(() => rows.value.filter((warehouse) => {
|
||||||
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
||||||
const matchesKeyword = !keyword || [warehouse.code, warehouse.name, warehouse.province, warehouse.city, warehouse.address]
|
const matchesKeyword = !keyword || [warehouse.code, warehouse.name, warehouse.province, warehouse.city, warehouse.address]
|
||||||
@@ -159,14 +167,21 @@ function validateWarehouseForm() {
|
|||||||
.every(Boolean)
|
.every(Boolean)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadWarehouses() {
|
function apiTenantId(value: string) {
|
||||||
|
const numeric = Number(value)
|
||||||
|
return Number.isSafeInteger(numeric) ? numeric : value
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadWarehouses(tenantId = selectedTenantId.value) {
|
||||||
|
if (!tenantId) return
|
||||||
const sequence = ++loadSequence
|
const sequence = ++loadSequence
|
||||||
loading.value = true
|
loading.value = true
|
||||||
loadError.value = null
|
loadError.value = null
|
||||||
try {
|
try {
|
||||||
const result = await listPlatformWarehouses(fixedTenantId, 1, 200)
|
const requestTenantId = apiTenantId(tenantId)
|
||||||
|
const result = await listPlatformWarehouses(requestTenantId, 1, 200)
|
||||||
const details = await Promise.allSettled(
|
const details = await Promise.allSettled(
|
||||||
result.records.map((warehouse) => getPlatformWarehouse(fixedTenantId, warehouse.id)),
|
result.records.map((warehouse) => getPlatformWarehouse(requestTenantId, warehouse.id)),
|
||||||
)
|
)
|
||||||
if (sequence !== loadSequence) return
|
if (sequence !== loadSequence) return
|
||||||
rows.value = result.records.map((warehouse, index) => {
|
rows.value = result.records.map((warehouse, index) => {
|
||||||
@@ -174,7 +189,7 @@ async function loadWarehouses() {
|
|||||||
return toRow(warehouse, detailResult?.status === 'fulfilled' ? detailResult.value : null)
|
return toRow(warehouse, detailResult?.status === 'fulfilled' ? detailResult.value : null)
|
||||||
})
|
})
|
||||||
detailWarningCount.value = details.filter((item) => item.status === 'rejected').length
|
detailWarningCount.value = details.filter((item) => item.status === 'rejected').length
|
||||||
loadedTenantId.value = fixedTenantId
|
loadedTenantId.value = tenantId
|
||||||
page.value = 1
|
page.value = 1
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (sequence !== loadSequence) return
|
if (sequence !== loadSequence) return
|
||||||
@@ -189,7 +204,7 @@ function requireCurrentTenant() {
|
|||||||
ElMessage.warning('仓库数据尚未加载完成,请稍后重试')
|
ElMessage.warning('仓库数据尚未加载完成,请稍后重试')
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
return fixedTenantId
|
return apiTenantId(selectedTenantId.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
@@ -217,24 +232,30 @@ async function ensureDetail(warehouse: WarehouseRow) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openEdit(warehouse: WarehouseRow) {
|
async function openEdit(warehouse: WarehouseRow) {
|
||||||
const detail = await ensureDetail(warehouse)
|
const tenantAtStart = selectedTenantId.value
|
||||||
if (!detail) return
|
editLoading.value = true
|
||||||
const address = detail.addresses[0]
|
try {
|
||||||
Object.assign(form, warehouse, {
|
const detail = await ensureDetail(warehouse)
|
||||||
province: address?.stateProvince || '',
|
if (!detail || selectedTenantId.value !== tenantAtStart || loadedTenantId.value !== tenantAtStart) return
|
||||||
city: address?.city || '',
|
const address = detail.addresses[0]
|
||||||
address: address?.addressLine1 || '',
|
Object.assign(form, warehouse, {
|
||||||
})
|
province: address?.stateProvince || '',
|
||||||
clearWarehouseFormErrors()
|
city: address?.city || '',
|
||||||
captureBaseline()
|
address: address?.addressLine1 || '',
|
||||||
editorOpen.value = true
|
})
|
||||||
|
clearWarehouseFormErrors()
|
||||||
|
captureBaseline()
|
||||||
|
editorOpen.value = true
|
||||||
|
} finally {
|
||||||
|
editLoading.value = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function nullable(value: string) {
|
function nullable(value: string) {
|
||||||
return value.trim() || null
|
return value.trim() || null
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildSaveRequest(tenantId: number): SavePlatformWarehouseRequest {
|
function buildSaveRequest(tenantId: number | string): SavePlatformWarehouseRequest {
|
||||||
const existing = form.id ? rows.value.find((item) => item.id === form.id)?.detail : null
|
const existing = form.id ? rows.value.find((item) => item.id === form.id)?.detail : null
|
||||||
const warehouse = existing?.warehouse
|
const warehouse = existing?.warehouse
|
||||||
const currentAddress = existing?.addresses[0]
|
const currentAddress = existing?.addresses[0]
|
||||||
@@ -332,13 +353,19 @@ async function toggleStatus(warehouse: WarehouseRow) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
watch(selectedTenantId, (tenantId) => {
|
||||||
void loadWarehouses()
|
editorOpen.value = false
|
||||||
|
rows.value = []
|
||||||
|
loadedTenantId.value = null
|
||||||
|
detailWarningCount.value = 0
|
||||||
|
page.value = 1
|
||||||
|
void loadWarehouses(tenantId)
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="business-page">
|
<div class="business-page">
|
||||||
|
<PlatformTenantSelector v-model="selectedTenantId" :disabled="tenantSwitchDisabled" />
|
||||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
|
<el-alert v-if="loadError" type="error" :closable="false" show-icon class="state-alert">
|
||||||
<template #title>仓库数据加载失败</template>
|
<template #title>仓库数据加载失败</template>
|
||||||
<p>{{ loadErrorDescription }}</p>
|
<p>{{ loadErrorDescription }}</p>
|
||||||
@@ -355,7 +382,7 @@ onMounted(() => {
|
|||||||
<div class="panel-heading">
|
<div class="panel-heading">
|
||||||
<div>
|
<div>
|
||||||
<h2>平台收货仓</h2>
|
<h2>平台收货仓</h2>
|
||||||
<p>租户 {{ fixedTenantId }} · 共 {{ filteredRows.length }} 个收货仓</p>
|
<p>租户 {{ selectedTenantId || '—' }} · 共 {{ filteredRows.length }} 个收货仓</p>
|
||||||
</div>
|
</div>
|
||||||
<el-button
|
<el-button
|
||||||
v-if="access.can('platform:warehouse:create')"
|
v-if="access.can('platform:warehouse:create')"
|
||||||
|
|||||||
Reference in New Issue
Block a user