完成设计师端与店务端生产隔离改造
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const messageError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ant-design-vue', () => ({
|
||||
message: {
|
||||
error: messageError
|
||||
}
|
||||
}))
|
||||
|
||||
import adminApi from '../../src/api/admin'
|
||||
|
||||
function createTokenExpiredError(config: InternalAxiosRequestConfig) {
|
||||
const response = {
|
||||
data: {
|
||||
code: 401,
|
||||
message: 'Token expired'
|
||||
},
|
||||
status: 401,
|
||||
statusText: 'Unauthorized',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse
|
||||
|
||||
return new AxiosError(
|
||||
'Request failed with status code 401',
|
||||
AxiosError.ERR_BAD_REQUEST,
|
||||
config,
|
||||
{},
|
||||
response
|
||||
)
|
||||
}
|
||||
|
||||
describe('admin api stale token handling', () => {
|
||||
const originalAdapter = adminApi.defaults.adapter
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
messageError.mockClear()
|
||||
window.history.replaceState(null, '', '/admin')
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
adminApi.defaults.adapter = originalAdapter
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('keeps a newer admin session when an old-token request returns 401', async () => {
|
||||
localStorage.setItem('adminAccessToken', 'old-admin-token')
|
||||
localStorage.setItem('adminRefreshToken', 'old-admin-refresh')
|
||||
sessionStorage.setItem('adminAccessToken', 'old-admin-token')
|
||||
|
||||
const requests: Array<{ url?: string, authorization?: string }> = []
|
||||
let markRequestStarted!: () => void
|
||||
let releaseStale401!: () => void
|
||||
const requestStarted = new Promise<void>(resolve => {
|
||||
markRequestStarted = resolve
|
||||
})
|
||||
|
||||
adminApi.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||
if (config.url !== '/user/info') {
|
||||
return Promise.reject(new Error(`Unexpected request: ${config.url}`))
|
||||
}
|
||||
requests.push({
|
||||
url: config.url,
|
||||
authorization: String(config.headers.Authorization || '')
|
||||
})
|
||||
markRequestStarted()
|
||||
return new Promise((_resolve, reject) => {
|
||||
releaseStale401 = () => reject(createTokenExpiredError(config))
|
||||
})
|
||||
}) as AxiosAdapter
|
||||
|
||||
const staleRequest = adminApi.get('/user/info')
|
||||
|
||||
await requestStarted
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
url: '/user/info',
|
||||
authorization: 'Bearer old-admin-token'
|
||||
}
|
||||
])
|
||||
|
||||
localStorage.setItem('adminAccessToken', 'new-admin-token')
|
||||
localStorage.setItem('adminRefreshToken', 'new-admin-refresh')
|
||||
sessionStorage.setItem('adminAccessToken', 'new-admin-token')
|
||||
const hrefBefore401 = window.location.href
|
||||
|
||||
releaseStale401()
|
||||
|
||||
await expect(staleRequest).rejects.toMatchObject({
|
||||
response: {
|
||||
status: 401
|
||||
}
|
||||
})
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(localStorage.getItem('adminAccessToken')).toBe('new-admin-token')
|
||||
expect(localStorage.getItem('adminRefreshToken')).toBe('new-admin-refresh')
|
||||
expect(sessionStorage.getItem('adminAccessToken')).toBe('new-admin-token')
|
||||
expect(window.location.href).toBe(hrefBefore401)
|
||||
expect(messageError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isApiAuthFreePath, WEB_API_AUTH_FREE_PATHS } from '@/api/auth-free-paths'
|
||||
|
||||
describe('auth-free API contract', () => {
|
||||
it('covers public paths and rejects protected business APIs', () => {
|
||||
expect(isApiAuthFreePath('/comment/list/product/1')).toBe(true)
|
||||
expect(isApiAuthFreePath('/user/wechat-mini/auto-login')).toBe(true)
|
||||
expect(isApiAuthFreePath('/admin/auth/login-shops/1')).toBe(true)
|
||||
expect(isApiAuthFreePath('/nail-artist/profile/1')).toBe(true)
|
||||
expect(isApiAuthFreePath('/nail-artist/1/availability')).toBe(true)
|
||||
expect(isApiAuthFreePath('/nail-artist/1/reviews')).toBe(true)
|
||||
expect(isApiAuthFreePath('/shop/list')).toBe(true)
|
||||
|
||||
expect(isApiAuthFreePath('/order/list')).toBe(false)
|
||||
expect(isApiAuthFreePath('/shop/delete/1')).toBe(false)
|
||||
expect(isApiAuthFreePath('/permission/list')).toBe(false)
|
||||
expect(isApiAuthFreePath('/order/list?next=/user/login')).toBe(false)
|
||||
expect(isApiAuthFreePath('/user/profile/admin/auth/refresh')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps auth-free path constants unique', () => {
|
||||
expect(new Set(WEB_API_AUTH_FREE_PATHS).size).toBe(WEB_API_AUTH_FREE_PATHS.length)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const messageError = vi.hoisted(() => vi.fn())
|
||||
const modalError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ant-design-vue', () => ({
|
||||
message: {
|
||||
error: messageError
|
||||
},
|
||||
Modal: {
|
||||
error: modalError
|
||||
}
|
||||
}))
|
||||
|
||||
import api from '../../src/api'
|
||||
|
||||
function createTokenExpiredError(config: InternalAxiosRequestConfig) {
|
||||
const response = {
|
||||
data: {
|
||||
code: 401,
|
||||
message: 'Token expired'
|
||||
},
|
||||
status: 401,
|
||||
statusText: 'Unauthorized',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse
|
||||
|
||||
return new AxiosError(
|
||||
'Request failed with status code 401',
|
||||
AxiosError.ERR_BAD_REQUEST,
|
||||
config,
|
||||
{},
|
||||
response
|
||||
)
|
||||
}
|
||||
|
||||
describe('api stale token handling', () => {
|
||||
const originalAdapter = api.defaults.adapter
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
messageError.mockClear()
|
||||
modalError.mockClear()
|
||||
window.history.replaceState(null, '', '/profile')
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
api.defaults.adapter = originalAdapter
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('keeps a newer login session when an old-token request returns 401', async () => {
|
||||
localStorage.setItem('accessToken', 'old-token')
|
||||
sessionStorage.setItem('accessToken', 'old-token')
|
||||
|
||||
const requests: Array<{ url?: string, authorization?: string }> = []
|
||||
let markRequestStarted!: () => void
|
||||
let releaseStale401!: () => void
|
||||
const requestStarted = new Promise<void>(resolve => {
|
||||
markRequestStarted = resolve
|
||||
})
|
||||
|
||||
api.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||
if (config.url !== '/user/info') {
|
||||
return Promise.reject(new Error(`Unexpected request: ${config.url}`))
|
||||
}
|
||||
|
||||
requests.push({
|
||||
url: config.url,
|
||||
authorization: String(config.headers.Authorization || '')
|
||||
})
|
||||
markRequestStarted()
|
||||
|
||||
return new Promise((_resolve, reject) => {
|
||||
releaseStale401 = () => reject(createTokenExpiredError(config))
|
||||
})
|
||||
}) as AxiosAdapter
|
||||
|
||||
const staleRequest = api.get('/user/info')
|
||||
|
||||
await requestStarted
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
url: '/user/info',
|
||||
authorization: 'Bearer old-token'
|
||||
}
|
||||
])
|
||||
|
||||
localStorage.setItem('accessToken', 'new-token')
|
||||
localStorage.setItem('refreshToken', 'new-refresh')
|
||||
localStorage.setItem('userInfo', JSON.stringify({ id: 2, nickname: 'new-user' }))
|
||||
sessionStorage.setItem('accessToken', 'new-token')
|
||||
sessionStorage.setItem('refreshToken', 'new-refresh')
|
||||
const hrefBefore401 = window.location.href
|
||||
|
||||
releaseStale401()
|
||||
|
||||
await expect(staleRequest).rejects.toMatchObject({
|
||||
response: {
|
||||
status: 401
|
||||
}
|
||||
})
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(localStorage.getItem('accessToken')).toBe('new-token')
|
||||
expect(localStorage.getItem('refreshToken')).toBe('new-refresh')
|
||||
expect(localStorage.getItem('userInfo')).toBe(JSON.stringify({ id: 2, nickname: 'new-user' }))
|
||||
expect(sessionStorage.getItem('accessToken')).toBe('new-token')
|
||||
expect(sessionStorage.getItem('refreshToken')).toBe('new-refresh')
|
||||
expect(window.location.href).toBe(hrefBefore401)
|
||||
expect(messageError).not.toHaveBeenCalled()
|
||||
expect(modalError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const messageError = vi.hoisted(() => vi.fn())
|
||||
const modalError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ant-design-vue', () => ({
|
||||
message: {
|
||||
error: messageError
|
||||
},
|
||||
Modal: {
|
||||
error: modalError
|
||||
}
|
||||
}))
|
||||
|
||||
import api from '../../src/api'
|
||||
|
||||
const createResponseError = (config: InternalAxiosRequestConfig, status: number): AxiosError => {
|
||||
const response = {
|
||||
data: {
|
||||
code: status,
|
||||
message: `HTTP ${status}`
|
||||
},
|
||||
status,
|
||||
statusText: 'Error',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse
|
||||
|
||||
return new AxiosError(
|
||||
`Request failed with status code ${status}`,
|
||||
AxiosError.ERR_BAD_RESPONSE,
|
||||
config,
|
||||
{},
|
||||
response
|
||||
)
|
||||
}
|
||||
|
||||
const createNetworkError = (config: InternalAxiosRequestConfig): AxiosError =>
|
||||
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, {})
|
||||
|
||||
type MockRequestResult = AxiosError | null
|
||||
|
||||
const mockRequestResults = (results: MockRequestResult[]) => {
|
||||
let currentResultIndex = 0
|
||||
api.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||
const result = results[currentResultIndex]
|
||||
currentResultIndex += 1
|
||||
if (!result) {
|
||||
return Promise.resolve({
|
||||
data: { code: 200, data: { ok: true } },
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse)
|
||||
}
|
||||
result.config = config
|
||||
return Promise.reject(result)
|
||||
}) as AxiosAdapter
|
||||
}
|
||||
|
||||
describe('api system unavailable handling', () => {
|
||||
const originalAdapter = api.defaults.adapter
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(1_000)
|
||||
messageError.mockClear()
|
||||
modalError.mockClear()
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
api.defaults.adapter = originalAdapter
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('shows one system unavailable modal after three server failures in the window', async () => {
|
||||
const config = {} as InternalAxiosRequestConfig
|
||||
mockRequestResults([
|
||||
createResponseError(config, 500),
|
||||
createResponseError(config, 502),
|
||||
createResponseError(config, 503),
|
||||
createResponseError(config, 500)
|
||||
])
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 502 } })
|
||||
expect(modalError).not.toHaveBeenCalled()
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 503 } })
|
||||
expect(modalError).toHaveBeenCalledTimes(1)
|
||||
expect(modalError).toHaveBeenCalledWith(expect.objectContaining({
|
||||
title: '系统暂不可用',
|
||||
content: '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。',
|
||||
okText: '我知道了'
|
||||
}))
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
expect(modalError).toHaveBeenCalledTimes(1)
|
||||
modalError.mock.calls[0]?.[0]?.afterClose?.()
|
||||
})
|
||||
|
||||
it('counts network failures as system failures', async () => {
|
||||
const config = {} as InternalAxiosRequestConfig
|
||||
vi.setSystemTime(70_000)
|
||||
mockRequestResults([
|
||||
createNetworkError(config),
|
||||
createNetworkError(config),
|
||||
createNetworkError(config)
|
||||
])
|
||||
|
||||
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
|
||||
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
|
||||
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
|
||||
|
||||
expect(modalError).toHaveBeenCalledTimes(1)
|
||||
expect(messageError).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('resets failure count after a successful response', async () => {
|
||||
const config = {} as InternalAxiosRequestConfig
|
||||
vi.setSystemTime(140_000)
|
||||
mockRequestResults([
|
||||
createResponseError(config, 500),
|
||||
createResponseError(config, 500),
|
||||
null,
|
||||
createResponseError(config, 500)
|
||||
])
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
await expect(api.get('/health')).resolves.toEqual({ ok: true })
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
|
||||
expect(modalError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { AxiosAdapter, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const messageError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ant-design-vue', () => ({
|
||||
message: {
|
||||
error: messageError
|
||||
}
|
||||
}))
|
||||
|
||||
import adminApi, {
|
||||
adminAfterSaleApi,
|
||||
adminArtistScheduleApi,
|
||||
adminCampaignApi,
|
||||
adminDashboardApi,
|
||||
adminInventoryApi,
|
||||
adminPaymentApi
|
||||
} from '../../src/api/admin'
|
||||
import api from '../../src/api'
|
||||
import { afterSaleApi, growthApi, paymentApi } from '../../src/api/order'
|
||||
|
||||
type CapturedRequest = {
|
||||
method?: string
|
||||
url?: string
|
||||
params?: any
|
||||
data?: any
|
||||
}
|
||||
|
||||
function okResponse(config: InternalAxiosRequestConfig): AxiosResponse {
|
||||
return {
|
||||
data: {
|
||||
code: 200,
|
||||
message: 'ok',
|
||||
data: {}
|
||||
},
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
}
|
||||
}
|
||||
|
||||
function parseData(data: unknown) {
|
||||
return typeof data === 'string' && data ? JSON.parse(data) : data
|
||||
}
|
||||
|
||||
function captureAdapter(requests: CapturedRequest[]): AxiosAdapter {
|
||||
return (config: InternalAxiosRequestConfig) => {
|
||||
requests.push({
|
||||
method: config.method,
|
||||
url: config.url,
|
||||
params: config.params,
|
||||
data: parseData(config.data)
|
||||
})
|
||||
return Promise.resolve(okResponse(config))
|
||||
}
|
||||
}
|
||||
|
||||
describe('vNext API contracts', () => {
|
||||
const originalAdminAdapter = adminApi.defaults.adapter
|
||||
const originalApiAdapter = api.defaults.adapter
|
||||
|
||||
beforeEach(() => {
|
||||
messageError.mockClear()
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
adminApi.defaults.adapter = originalAdminAdapter
|
||||
api.defaults.adapter = originalApiAdapter
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
it('uses backend admin vNext endpoints', async () => {
|
||||
const requests: CapturedRequest[] = []
|
||||
adminApi.defaults.adapter = captureAdapter(requests)
|
||||
|
||||
await adminArtistScheduleApi.listSchedules({ artistId: 9, startDate: '2026-06-01', endDate: '2026-06-07' })
|
||||
await adminArtistScheduleApi.saveSchedule({ artistId: 9, workDate: '2026-06-01', startTime: '09:00', endTime: '18:00' })
|
||||
await adminPaymentApi.manualConfirmOrder(42, 'cash verified')
|
||||
await adminAfterSaleApi.listAfterSales({ status: 'APPLIED', page: 1, size: 20 })
|
||||
await adminAfterSaleApi.approveAfterSale(5, { auditReason: 'approved' })
|
||||
await adminInventoryApi.saveItem({ itemName: 'Base Gel', category: 'gel', unit: 'bottle', stockQuantity: 12 })
|
||||
await adminInventoryApi.adjustStock(7, { changeType: 'IN', changeQuantity: 3, remark: 'restock' })
|
||||
await adminCampaignApi.saveCampaign({ title: 'Summer Set', scene: 'HOME', status: 1 })
|
||||
await adminDashboardApi.getAnalytics()
|
||||
|
||||
expect(requests).toEqual([
|
||||
{ method: 'get', url: '/artist-schedule/list', params: { artistId: 9, startDate: '2026-06-01', endDate: '2026-06-07' }, data: undefined },
|
||||
{ method: 'post', url: '/artist-schedule/save', params: undefined, data: { artistId: 9, workDate: '2026-06-01', startTime: '09:00', endTime: '18:00' } },
|
||||
{ method: 'post', url: '/payment/order/42/manual-confirm', params: { remark: 'cash verified' }, data: undefined },
|
||||
{ method: 'get', url: '/after-sale/list', params: { status: 'APPLIED', page: 1, size: 20 }, data: undefined },
|
||||
{ method: 'put', url: '/after-sale/5/approve', params: undefined, data: { auditReason: 'approved' } },
|
||||
{ method: 'post', url: '/inventory/save', params: undefined, data: { itemName: 'Base Gel', category: 'gel', unit: 'bottle', stockQuantity: 12 } },
|
||||
{ method: 'post', url: '/inventory/7/adjust', params: undefined, data: { changeType: 'IN', changeQuantity: 3, remark: 'restock' } },
|
||||
{ method: 'post', url: '/campaign/save', params: undefined, data: { title: 'Summer Set', scene: 'HOME', status: 1 } },
|
||||
{ method: 'get', url: '/dashboard/analytics', params: undefined, data: undefined }
|
||||
])
|
||||
})
|
||||
|
||||
it('uses backend user vNext endpoints', async () => {
|
||||
const requests: CapturedRequest[] = []
|
||||
api.defaults.adapter = captureAdapter(requests)
|
||||
|
||||
await paymentApi.prepareOrderPayment(42)
|
||||
await paymentApi.mockSuccess(42)
|
||||
await afterSaleApi.apply({ orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 })
|
||||
await afterSaleApi.listMy({ page: 1, size: 5 })
|
||||
await growthApi.getSummary()
|
||||
|
||||
expect(requests).toEqual([
|
||||
{ method: 'post', url: '/payment/order/42/prepare', params: undefined, data: undefined },
|
||||
{ method: 'post', url: '/payment/order/42/mock-success', params: undefined, data: undefined },
|
||||
{ method: 'post', url: '/after-sale/apply', params: undefined, data: { orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 } },
|
||||
{ method: 'get', url: '/after-sale/my', params: { page: 1, size: 5 }, data: undefined },
|
||||
{ method: 'get', url: '/growth/summary', params: undefined, data: undefined }
|
||||
])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user