提交开发分支未提交代码并修正配置

This commit is contained in:
2026-06-23 15:33:06 +08:00
parent a53b27ef20
commit 0fd96d150e
141 changed files with 3624 additions and 6048 deletions
+12
View File
@@ -367,8 +367,20 @@ export const adminLegalAgreementApi = {
export interface ObjectStorageFileVO {
id: IdType
fileName: string
fileUrl?: string
objectName?: string
primaryProvider?: string
primaryUrl?: string
backupProvider?: string
backupUrl?: string
fileSize: number
contentType: string
primaryUploadStatus?: number
backupUploadStatus?: number
backupRetryCount?: number
backupLastError?: string
backupUploadedAt?: string
backupLastRetryTime?: string
createTime: string
}
+28
View File
@@ -3,6 +3,8 @@
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { AxiosProgressEvent } from 'axios'
import type { ChunkUploadInitRequest, ChunkUploadSessionVO } from '@/api/file'
import type { IdType } from '@/utils/id'
/**
@@ -75,6 +77,32 @@ export const commentApi = {
}
}) as unknown as Promise<CommentImageFileVO>
},
initImageChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/comment/upload-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadImageChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/comment/upload-image/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeImageChunkUpload: (uploadId: string) => {
return api.post<CommentImageFileVO>('/comment/upload-image/complete', { uploadId }) as unknown as Promise<CommentImageFileVO>
},
cancelImageChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/comment/upload-image/${uploadId}`)
},
/**
* `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest'
import type { AxiosError } from 'axios'
import {
getApiResponseMessage,
isPermissionErrorMessage,
isSystemFailureResponse,
isTokenExpiredMessage,
normalizeApiErrorMessage,
shouldShowDedupedError,
updateSystemFailureWindow
} from './error'
describe('api error helpers', () => {
it('extracts messages and classifies error types', () => {
const error = { message: 'fallback', response: { data: { message: '服务异常' } } } as AxiosError
expect(getApiResponseMessage(error, '请求失败')).toBe('服务异常')
expect(isPermissionErrorMessage('权限不足')).toBe(true)
expect(isPermissionErrorMessage('permission denied')).toBe(true)
expect(isTokenExpiredMessage('登录已过期,请重新登录')).toBe(true)
})
it('dedupes prompts by message and time', () => {
expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'a', 40, 50)).toBe(false)
expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'b', 100, 50)).toBe(true)
})
it('normalizes garbled booking unavailable messages', () => {
expect(normalizeApiErrorMessage('涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试')
expect(normalizeApiErrorMessage('创建订单失败:涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试')
})
it('classifies system failure responses', () => {
expect(isSystemFailureResponse({ response: { status: 500 } } as AxiosError)).toBe(true)
expect(isSystemFailureResponse({ response: { status: 503 } } as AxiosError)).toBe(true)
expect(isSystemFailureResponse({ response: { status: 400 } } as AxiosError)).toBe(false)
expect(isSystemFailureResponse({ response: undefined } as AxiosError)).toBe(true)
})
it('tracks failure windows with pruning and threshold', () => {
expect(updateSystemFailureWindow([1_000, 12_000], 40_000, 30_000, 3)).toEqual({
failureTimes: [12_000, 40_000],
triggered: false
})
expect(updateSystemFailureWindow([1_000, 12_000, 20_000], 30_000, 30_000, 3)).toEqual({
failureTimes: [1_000, 12_000, 20_000, 30_000],
triggered: true
})
})
})
+90
View File
@@ -0,0 +1,90 @@
import type { AxiosError } from 'axios'
export interface ApiResponseBody {
message?: string
}
export interface ErrorPromptState {
lastErrorTime: number
lastErrorMessage: string
}
export interface SystemFailureWindowState {
failureTimes: number[]
triggered: boolean
}
const BOOKING_UNAVAILABLE_MESSAGE = '不可预约,请调整美甲师或预约时间后重试'
const GARbled_BOOKING_UNAVAILABLE_MESSAGES = [
'涓嶅彲棰勭害'
]
export const normalizeApiErrorMessage = (messageText: string): string => {
const trimmedMessage = String(messageText || '').trim()
if (!trimmedMessage) return trimmedMessage
if (GARbled_BOOKING_UNAVAILABLE_MESSAGES.some(message => trimmedMessage.includes(message))) {
return BOOKING_UNAVAILABLE_MESSAGE
}
return trimmedMessage
}
export const getApiResponseMessage = (error: AxiosError, fallbackMessage: string): string => {
const responseData = error.response?.data as ApiResponseBody | undefined
return normalizeApiErrorMessage(responseData?.message || error.message || fallbackMessage)
}
export const isPermissionErrorMessage = (messageText: string): boolean =>
messageText.includes('权限') || messageText.includes('permission')
export const isTokenExpiredMessage = (messageText: string): boolean => (
messageText.includes('Token')
|| messageText.includes('token')
|| messageText.includes('登录态')
|| messageText.includes('登录已过期')
|| messageText.includes('未登录')
|| messageText.includes('认证')
|| messageText.includes('重新登录')
)
export const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null): boolean =>
Boolean(requestToken && isTokenExpiredMessage(getApiResponseMessage(error, '请求失败')))
export const isSystemFailureResponse = (error: AxiosError): boolean => {
const status = error.response?.status
if (typeof status === 'number') {
return status >= 500
}
return !error.response
}
export const shouldShowDedupedError = (
state: ErrorPromptState,
messageText: string,
now: number,
debounceTime: number
): boolean => now - state.lastErrorTime > debounceTime || messageText !== state.lastErrorMessage
export const updateErrorPromptState = (
messageText: string,
now: number
): ErrorPromptState => ({
lastErrorTime: now,
lastErrorMessage: messageText
})
export const updateSystemFailureWindow = (
failureTimes: number[],
now: number,
windowMs: number,
threshold: number
): SystemFailureWindowState => {
const nextFailureTimes = failureTimes
.filter(failureTime => now - failureTime <= windowMs)
.concat(now)
return {
failureTimes: nextFailureTimes,
triggered: nextFailureTimes.length >= threshold
}
}
+26
View File
@@ -114,6 +114,32 @@ export const fileApi = {
cancelAvatarChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-avatar/${uploadId}`)
},
initProfileImageChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-profile-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadProfileImageChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/user/upload-profile-image/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeProfileImageChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-profile-image/complete', { uploadId }) as unknown as Promise<string>
},
cancelProfileImageChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-profile-image/${uploadId}`)
},
/**
* `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
+88 -39
View File
@@ -6,12 +6,23 @@ import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { adminAuthApi } from './admin'
import { wishlistApi } from './wishlist'
import { message } from 'ant-design-vue'
import { message, Modal } from 'ant-design-vue'
import { API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
import { clearAdminSessionStorage } from '@/utils/admin-session'
import { attachRequestSignature } from '@/utils/request-signature'
import { isApiAuthFreePath } from './auth-free-paths'
import {
getApiResponseMessage,
isPermissionErrorMessage,
isSystemFailureResponse,
isTokenExpiredResponse,
normalizeApiErrorMessage,
shouldShowDedupedError,
updateSystemFailureWindow,
updateErrorPromptState,
type ErrorPromptState
} from './error'
// 防重复提示标志
let lastErrorTime = 0
@@ -25,6 +36,15 @@ let lastErrorMessage = ''
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误
const SYSTEM_FAILURE_WINDOW_MS = 30 * 1000
const SYSTEM_FAILURE_THRESHOLD = 3
const SYSTEM_FAILURE_MODAL_COOLDOWN_MS = 60 * 1000
const SYSTEM_FAILURE_MODAL_TITLE = '系统暂不可用'
const SYSTEM_FAILURE_MODAL_CONTENT = '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。'
const SYSTEM_FAILURE_MODAL_OK_TEXT = '我知道了'
let systemFailureTimes: number[] = []
let systemFailureModalVisible = false
let lastSystemFailureModalTime: number | null = null
/**
* Purpose: api supports index.ts by holding or executing the api page or API role.
@@ -93,39 +113,11 @@ const isCurrentStoredToken = (token: string | null, isAdmin = false) => {
return Boolean(token && token === getStoredAccessToken(isAdmin))
}
/**
* Purpose: getResponseMessage supports index.ts by holding or executing the get response message page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const getResponseMessage = (error: AxiosError) => {
return (error.response?.data as any)?.message || error.message || '请求失败'
}
/**
* Purpose: isTokenExpiredResponse supports index.ts by holding or executing the is token expired response page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null) => {
const messageText = getResponseMessage(error)
return Boolean(
requestToken
&& (
messageText.includes('Token')
|| messageText.includes('token')
|| messageText.includes('登录态')
|| messageText.includes('登录已过期')
|| messageText.includes('未登录')
|| messageText.includes('认证')
|| messageText.includes('重新登录')
)
)
}
/**
* Purpose: processQueue supports index.ts by holding or executing the process queue page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const processQueue = (error: any, token: string | null = null) => {
const processQueue = (error: unknown, token: string | null = null) => {
failedQueue.forEach(prom => {
if (error) {
prom.reject(error)
@@ -139,11 +131,65 @@ const processQueue = (error: any, token: string | null = null) => {
// 防抖处理错误提示
const showError = (msg: string) => {
const now = Date.now()
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) {
lastErrorTime = now
lastErrorMessage = msg
message.error(msg)
const state: ErrorPromptState = { lastErrorTime, lastErrorMessage }
if (!shouldShowDedupedError(state, msg, now, ERROR_DEBOUNCE_TIME)) {
return
}
const nextState = updateErrorPromptState(msg, now)
lastErrorTime = nextState.lastErrorTime
lastErrorMessage = nextState.lastErrorMessage
message.error(msg)
}
const resetSystemFailureWindow = () => {
systemFailureTimes = []
}
const showSystemFailureModal = (now: number) => {
if (
systemFailureModalVisible
|| (
lastSystemFailureModalTime !== null
&& now - lastSystemFailureModalTime < SYSTEM_FAILURE_MODAL_COOLDOWN_MS
)
) {
return
}
systemFailureModalVisible = true
lastSystemFailureModalTime = now
Modal.error({
title: SYSTEM_FAILURE_MODAL_TITLE,
content: SYSTEM_FAILURE_MODAL_CONTENT,
okText: SYSTEM_FAILURE_MODAL_OK_TEXT,
onOk: () => {
systemFailureModalVisible = false
},
afterClose: () => {
systemFailureModalVisible = false
}
})
}
const recordSystemFailure = (error: AxiosError): boolean => {
if (!isSystemFailureResponse(error)) {
return false
}
const now = Date.now()
const nextState = updateSystemFailureWindow(
systemFailureTimes,
now,
SYSTEM_FAILURE_WINDOW_MS,
SYSTEM_FAILURE_THRESHOLD
)
systemFailureTimes = nextState.failureTimes
if (nextState.triggered) {
showSystemFailureModal(now)
return true
}
return false
}
/**
@@ -221,10 +267,11 @@ api.interceptors.request.use(
api.interceptors.response.use(
response => {
resetSystemFailureWindow()
const res = response.data
if (res.code !== 200) {
const errorMsg = res.message || '请求失败'
if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) {
const errorMsg = normalizeApiErrorMessage(res.message || '请求失败')
if (!isPermissionErrorMessage(errorMsg)) {
showError(errorMsg)
}
return Promise.reject(new Error(errorMsg))
@@ -245,7 +292,7 @@ api.interceptors.response.use(
const isRealTokenExpired = isTokenExpiredResponse(error, requestToken)
if (!isRealTokenExpired) {
showError(getResponseMessage(error))
showError(getApiResponseMessage(error, '请求失败'))
return Promise.reject(error)
}
@@ -319,8 +366,10 @@ api.interceptors.response.use(
return Promise.reject(error)
}
} else if (error.response?.status !== 403) { // 403权限不足不提示
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
showError(errorMsg)
const errorMsg = getApiResponseMessage(error, '请求失败')
if (!recordSystemFailure(error)) {
showError(errorMsg)
}
}
return Promise.reject(error)
}
@@ -0,0 +1,11 @@
import { describe, expect, it } from 'vitest'
import { adminNavigationItems, adminPermissionRouteMap, findAdminNavigationItemByPath, ADMIN_DASHBOARD_PATH } from './admin-navigation'
describe('admin-navigation', () => {
it('keeps dashboard landing and permission routes aligned', () => {
expect(ADMIN_DASHBOARD_PATH).toBe('/admin/dashboard')
expect(findAdminNavigationItemByPath('/admin/products')?.label).toBe('作品管理')
expect(adminPermissionRouteMap.some(item => item.code === 'shop:view' && item.path === '/admin/shops')).toBe(true)
expect(adminNavigationItems[0]?.path).toBe('/admin')
})
})
@@ -0,0 +1,56 @@
export type AdminNavIconKey =
| 'home'
| 'dashboard'
| 'user'
| 'shop'
| 'gift'
| 'message'
| 'security'
| 'tag'
| 'shopping'
| 'calendar'
| 'tool'
| 'team'
export interface AdminNavigationItem {
path: string
iconKey: AdminNavIconKey
label: string
permissionCode: string
}
export const ADMIN_HOME_PATH = '/admin'
export const ADMIN_DASHBOARD_PATH = '/admin/dashboard'
export const adminNavigationItems: AdminNavigationItem[] = [
{ path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' },
{ path: ADMIN_DASHBOARD_PATH, iconKey: 'dashboard', label: '仪表盘', permissionCode: 'dashboard:view' },
{ path: '/admin/users', iconKey: 'user', label: '用户管理', permissionCode: 'user:view' },
{ path: '/admin/products', iconKey: 'shop', label: '作品管理', permissionCode: 'product:view' },
{ path: '/admin/coupons', iconKey: 'gift', label: '优惠券管理', permissionCode: 'coupon:view' },
{ path: '/admin/comments', iconKey: 'message', label: '评论管理', permissionCode: 'comment:view' },
{ path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' },
{ path: '/admin/permissions', iconKey: 'security', label: '权限管理', permissionCode: 'permission:view' },
{ path: '/admin/tags', iconKey: 'tag', label: '标签管理', permissionCode: 'tag:view' },
{ path: '/admin/orders', iconKey: 'shopping', label: '订单管理', permissionCode: 'order:view' },
{ path: '/admin/schedules', iconKey: 'calendar', label: '排班管理', permissionCode: 'schedule:view' },
{ path: '/admin/after-sales', iconKey: 'message', label: '售后处理', permissionCode: 'after_sale:view' },
{ path: '/admin/inventory', iconKey: 'tool', label: '库存管理', permissionCode: 'inventory:view' },
{ path: '/admin/campaigns', iconKey: 'gift', label: '活动管理', permissionCode: 'campaign:view' },
{ path: '/admin/nail-artists', iconKey: 'team', label: '美甲师管理', permissionCode: 'nail_artist:view' },
{ path: '/admin/messages', iconKey: 'message', label: '消息发布', permissionCode: 'message:view' },
{ path: '/admin/announcements', iconKey: 'message', label: '公告管理', permissionCode: 'announcement:view' },
{ path: '/admin/vip-recharge-plans', iconKey: 'gift', label: 'VIP充值配置', permissionCode: 'user:vip:manage' },
{ path: '/admin/messagehub-push-configs', iconKey: 'message', label: '参数管理', permissionCode: 'messagehub:config:manage' },
{ path: '/admin/legal-agreements', iconKey: 'security', label: '协议管理', permissionCode: 'legal_agreement:manage' }
]
export const adminPermissionRouteMap = adminNavigationItems
.filter(item => item.permissionCode)
.map(item => ({
code: item.permissionCode,
path: item.path
}))
export const findAdminNavigationItemByPath = (path: string) =>
adminNavigationItems.find(item => item.path === path)
+2 -19
View File
@@ -5,6 +5,7 @@ import {
isBootstrapAdminUser,
loadCachedAdminUserInfo,
} from '@/utils/admin-session'
import { ADMIN_DASHBOARD_PATH, adminPermissionRouteMap } from '@/config/admin-navigation'
import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions'
import {
clearStoredPermissions,
@@ -12,7 +13,6 @@ import {
getStoredUserPermissions,
} from '@/utils/permission'
const ADMIN_DASHBOARD_PATH = '/admin/dashboard'
/**
* Purpose: AuthBootstrapState supports admin-auth-bootstrap.ts by holding or executing the auth bootstrap state page or API role.
@@ -27,23 +27,6 @@ export type AuthBootstrapState = 'pending' | 'ready' | 'invalid'
const adminBootstrapState = ref<AuthBootstrapState>('pending')
let bootstrapPromise: Promise<AuthBootstrapState> | null = null
const ADMIN_PERMISSION_ROUTE_MAP: Array<{ code: string; path: string }> = [
{ code: 'dashboard:view', path: '/admin/dashboard' },
{ code: 'shop:view', path: '/admin/shops' },
{ code: 'product:view', path: '/admin/products' },
{ code: 'coupon:view', path: '/admin/coupons' },
{ code: 'comment:view', path: '/admin/comments' },
{ code: 'order:view', path: '/admin/orders' },
{ code: 'user:view', path: '/admin/users' },
{ code: 'tag:view', path: '/admin/tags' },
{ code: 'permission:view', path: '/admin/permissions' },
{ code: 'nail_artist:view', path: '/admin/nail-artists' },
{ code: 'message:view', path: '/admin/messages' },
{ code: 'announcement:view', path: '/admin/announcements' },
{ code: 'user:vip:manage', path: '/admin/vip-recharge-plans' },
{ code: 'messagehub:config:manage', path: '/admin/messagehub-push-configs' },
{ code: 'legal_agreement:manage', path: '/admin/legal-agreements' },
]
/**
* Purpose: useAdminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the use admin bootstrap state page or API role.
@@ -116,7 +99,7 @@ export const resolveAdminLandingPath = () => {
return ADMIN_DASHBOARD_PATH
}
const matchedRoute = ADMIN_PERMISSION_ROUTE_MAP.find(item => snapshot.permissions.includes(item.code))
const matchedRoute = adminPermissionRouteMap.find(item => snapshot.permissions.includes(item.code))
return matchedRoute?.path || '/admin'
}
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest'
import {
buildAdminUploadFileList,
buildSignedImageUrlMap,
getRecordImageUrls,
resolveSignedImageUrls
} from './admin-image-assets'
vi.mock('@/utils/signed-image-cache', () => ({
parseImageFileIds: (value?: string | null) => String(value || '').split(',').map(id => id.trim()).filter(Boolean),
getCachedSignedImageUrl: async (fileId: string | number | null | undefined, fallback = '') =>
fileId ? `signed-${fileId}` : fallback,
getCachedSignedImageUrls: async (fileIds: Array<string | number | null | undefined>, fallback = '') => {
const urls = fileIds.filter(Boolean).map(fileId => `signed-${fileId}`)
return urls.length ? urls : (fallback ? [fallback] : [])
}
}))
describe('admin-image-assets', () => {
it('resolves comma separated image ids with fallback policy', async () => {
await expect(resolveSignedImageUrls('1, 2,,3', 'fallback.png', true)).resolves.toEqual([
'signed-1',
'signed-2',
'signed-3'
])
await expect(resolveSignedImageUrls('', 'fallback.png', true)).resolves.toEqual(['fallback.png'])
await expect(resolveSignedImageUrls('', 'fallback.png', false)).resolves.toEqual([])
})
it('builds image url maps and respects cancellation', async () => {
await expect(buildSignedImageUrlMap(
[{ id: 7, imageFileIds: '10,11' }],
'imageFileIds',
'fallback.png',
true,
() => false
)).resolves.toEqual({ 7: ['signed-10', 'signed-11'] })
await expect(buildSignedImageUrlMap(
[{ id: 7, imageFileIds: '10,11' }],
'imageFileIds',
'fallback.png',
true,
() => true
)).resolves.toBeNull()
})
it('returns mapped record images or fallback images', () => {
expect(getRecordImageUrls({ id: 1 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['a.png'])
expect(getRecordImageUrls({ id: 2 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['fallback.png'])
})
it('builds upload file list from ids', async () => {
await expect(buildAdminUploadFileList(['8', ' 9 '], '图片', 'fallback.png')).resolves.toEqual([
{ uid: '8', fileId: '8', name: '图片1', status: 'done', url: 'signed-8' },
{ uid: '9', fileId: '9', name: '图片2', status: 'done', url: 'signed-9' }
])
})
})
+104
View File
@@ -0,0 +1,104 @@
import {
getCachedSignedImageUrl,
getCachedSignedImageUrls,
parseImageFileIds,
refreshCachedSignedImageUrl
} from '@/utils/signed-image-cache'
import type { IdType } from '@/utils/id'
export interface AdminUploadFileItem {
uid: string
fileId: string
name: string
status: 'done'
url: string
}
export type SignedImageRecord = {
id?: IdType
imageFileIds?: string
coverImageFileId?: string
}
export type ImageFieldName = 'imageFileIds' | 'coverImageFileId'
export const resolveSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback: string
): Promise<string> => getCachedSignedImageUrl(fileId, fallback, 'admin')
export const refreshSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback: string
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'admin')
export const resolveSignedImageUrls = async (
fileIdsValue: string | null | undefined,
fallback: string,
emptyFallback: boolean
): Promise<string[]> => {
const fileIds = parseImageFileIds(fileIdsValue)
if (!fileIds.length) {
return emptyFallback ? [fallback] : []
}
return getCachedSignedImageUrls(fileIds, fallback, 'admin')
}
export const buildSignedImageUrlMap = async <TRecord extends SignedImageRecord>(
records: TRecord[],
fieldName: ImageFieldName,
fallback: string,
emptyFallback: boolean,
isCancelled: () => boolean
): Promise<Record<string, string[]> | null> => {
const nextImageUrls: Record<string, string[]> = {}
for (const record of records) {
if (isCancelled()) {
return null
}
if (record.id === undefined || record.id === null) {
continue
}
nextImageUrls[String(record.id)] = await resolveSignedImageUrls(record[fieldName], fallback, emptyFallback)
}
return nextImageUrls
}
export const getRecordImageUrls = <TRecord extends { id?: IdType }>(
record: TRecord,
imageUrlMap: Record<string, string[]>,
fallbackImages: string[]
): string[] => {
if (record.id === undefined || record.id === null) {
return fallbackImages
}
return imageUrlMap[String(record.id)] || fallbackImages
}
export const buildAdminUploadFileList = async (
fileIds: string[],
fileNamePrefix: string,
fallback: string
): Promise<AdminUploadFileItem[]> => {
const fileList: AdminUploadFileItem[] = []
for (const [index, fileId] of fileIds.entries()) {
const normalizedFileId = fileId.trim()
if (!normalizedFileId) {
continue
}
const url = await resolveSignedImageUrl(normalizedFileId, fallback)
fileList.push({
uid: normalizedFileId,
fileId: normalizedFileId,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url
})
}
return fileList
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest'
import { applyAdminTablePaginationChange, createAdminPagination } from './admin-table'
describe('admin-table', () => {
it('creates default pagination state', () => {
expect(createAdminPagination().current).toBe(1)
expect(createAdminPagination().pageSize).toBe(10)
})
it('applies pagination changes', () => {
const pagination = createAdminPagination()
const nextPagination = applyAdminTablePaginationChange(pagination, { current: 3, pageSize: 20 })
expect(nextPagination.current).toBe(3)
expect(nextPagination.pageSize).toBe(20)
expect(pagination.current).toBe(1)
})
})
+35
View File
@@ -0,0 +1,35 @@
export interface AdminPaginationState {
current: number
pageSize: number
total: number
showSizeChanger: boolean
showQuickJumper: boolean
showTotal: (total: number) => string
}
export interface AdminTablePaginationChange {
current?: number
pageSize?: number
}
export interface AdminPaginationPageChange {
current: number
pageSize: number
}
export const createAdminPagination = (): AdminPaginationState => ({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
export const applyAdminTablePaginationChange = (
pagination: AdminPaginationState,
change: AdminTablePaginationChange
): AdminPaginationPageChange => ({
current: change.current || pagination.current,
pageSize: change.pageSize || pagination.pageSize
})
@@ -0,0 +1,11 @@
import { describe, expect, it } from 'vitest'
import { getUploadResponse, resolveUploadedFileId } from './admin-upload-file'
describe('admin-upload-file', () => {
it('resolves uploaded file id from response or file shape', () => {
expect(resolveUploadedFileId({ response: { id: 7 } })).toBe('7')
expect(resolveUploadedFileId({ fileId: '8' })).toBe('8')
expect(resolveUploadedFileId({ uid: '9' })).toBe('9')
expect(getUploadResponse(null)).toBeNull()
})
})
@@ -0,0 +1,49 @@
export interface AdminUploadResponseData {
id?: string | number
fileId?: string | number
}
export interface AdminUploadResponse {
id?: string | number
fileId?: string | number
data?: AdminUploadResponseData
}
export interface AdminUploadFileLike {
uid?: string | number
url?: string
thumbUrl?: string
fileId?: string | number
response?: AdminUploadResponse
}
export interface AdminUploadTaskFile extends File {
uid: string
}
export const getUploadResponse = (file: AdminUploadFileLike | null | undefined): AdminUploadResponse | null => {
if (!file || typeof file !== 'object') {
return null
}
return file.response || null
}
export const resolveUploadedFileId = (file: AdminUploadFileLike | null | undefined): string => {
const response = getUploadResponse(file)
const responseId = response?.id ?? response?.data?.id ?? response?.fileId ?? response?.data?.fileId ?? file?.fileId
if (responseId !== undefined && responseId !== null && responseId !== '') {
return String(responseId)
}
const fileUid = String(file?.uid || '')
if (/^\d+$/.test(fileUid)) {
return fileUid
}
const fileUrl = String(file?.url || '')
if (/^\d+$/.test(fileUrl)) {
return fileUrl
}
return ''
}
@@ -0,0 +1,84 @@
import { describe, expect, it, vi } from 'vitest'
import { createChunkUploadTask, type ChunkUploadApi } from './chunk-upload'
const createFile = (size: number) => new File([new Uint8Array(size)], 'large.png', {
type: 'image/png',
lastModified: 1
})
describe('chunk-upload', () => {
it('uploads chunks with the requested concurrency', async () => {
const releaseCallbacks: Array<() => void> = []
let activeUploads = 0
let maxActiveUploads = 0
const api: ChunkUploadApi<string> = {
initUpload: vi.fn().mockResolvedValue({
uploadId: 'upload-1',
chunkSize: 2,
totalChunks: 4,
uploadedChunks: []
}),
uploadChunk: vi.fn((_payload, config) => {
activeUploads += 1
maxActiveUploads = Math.max(maxActiveUploads, activeUploads)
config?.onUploadProgress?.({ loaded: 2, total: 2 } as never)
return new Promise(resolve => {
releaseCallbacks.push(() => {
activeUploads -= 1
resolve(true)
})
})
}),
completeUpload: vi.fn().mockResolvedValue('done'),
cancelUpload: vi.fn()
}
const task = createChunkUploadTask({
file: createFile(8),
scene: 'test-image',
concurrency: 3,
api
})
await vi.waitFor(() => expect(maxActiveUploads).toBe(3))
while (releaseCallbacks.length) {
releaseCallbacks.shift()?.()
await Promise.resolve()
}
await expect(task.promise).resolves.toMatchObject({
response: 'done',
uploadId: 'upload-1'
})
expect(api.uploadChunk).toHaveBeenCalledTimes(4)
expect(api.completeUpload).toHaveBeenCalledWith('upload-1')
})
it('skips already uploaded chunks', async () => {
const api: ChunkUploadApi<string> = {
initUpload: vi.fn().mockResolvedValue({
uploadId: 'upload-2',
chunkSize: 2,
totalChunks: 3,
uploadedChunks: [0, 2]
}),
uploadChunk: vi.fn().mockResolvedValue(true),
completeUpload: vi.fn().mockResolvedValue('done')
}
const task = createChunkUploadTask({
file: createFile(6),
scene: 'test-image',
concurrency: 3,
api
})
await expect(task.promise).resolves.toMatchObject({ response: 'done' })
expect(api.uploadChunk).toHaveBeenCalledTimes(1)
expect(api.uploadChunk).toHaveBeenCalledWith(
expect.objectContaining({ chunkIndex: 1 }),
expect.any(Object)
)
})
})
+44 -48
View File
@@ -1,9 +1,5 @@
import type { AxiosProgressEvent } from 'axios'
/**
* Purpose: ChunkUploadSession supports chunk-upload.ts by holding or executing the chunk upload session page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadSession {
uploadId: string
chunkSize: number
@@ -11,10 +7,6 @@ export interface ChunkUploadSession {
uploadedChunks: number[]
}
/**
* Purpose: ChunkUploadInitRequest supports chunk-upload.ts by holding or executing the chunk upload init request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
@@ -23,10 +15,6 @@ export interface ChunkUploadInitRequest {
scene: string
}
/**
* Purpose: ChunkUploadApi supports chunk-upload.ts by holding or executing the chunk upload api page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadApi<TResponse> {
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
uploadChunk: (
@@ -37,42 +25,27 @@ export interface ChunkUploadApi<TResponse> {
cancelUpload?: (uploadId: string) => Promise<unknown>
}
/**
* Purpose: ChunkUploadOptions supports chunk-upload.ts by holding or executing the chunk upload options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadOptions<TResponse> {
file: File
scene: string
api: ChunkUploadApi<TResponse>
concurrency: number
preprocessFile?: (file: File) => Promise<File>
onProgress?: (percent: number) => void
}
/**
* Purpose: ChunkUploadResult supports chunk-upload.ts by holding or executing the chunk upload result page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadResult<TResponse> {
response: TResponse
uploadId: string
processedFile: File
}
/**
* Purpose: ChunkUploadTask supports chunk-upload.ts by holding or executing the chunk upload task page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadTask<TResponse> {
promise: Promise<ChunkUploadResult<TResponse>>
cancel: () => void
getUploadId: () => string
}
/**
* Purpose: computeFileFingerprint supports chunk-upload.ts by holding or executing the compute file fingerprint page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const computeFileFingerprint = async (file: File) => {
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
if (!window.crypto?.subtle) {
@@ -84,32 +57,37 @@ const computeFileFingerprint = async (file: File) => {
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
}
/**
* Purpose: getChunkSizeByIndex supports chunk-upload.ts by holding or executing the get chunk size by index page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileSize)
return Math.max(end - start, 0)
}
/**
* Purpose: calculateUploadedBytes supports chunk-upload.ts by holding or executing the calculate uploaded bytes page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => {
return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) =>
uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
const normalizeConcurrency = (concurrency: number) => {
if (!Number.isFinite(concurrency) || concurrency < 1) {
return 1
}
return Math.floor(concurrency)
}
const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set<number>) => {
const chunkIndexes: number[] = []
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
if (!uploadedChunkSet.has(chunkIndex)) {
chunkIndexes.push(chunkIndex)
}
}
return chunkIndexes
}
/**
* Purpose: createChunkUploadTask supports chunk-upload.ts by holding or executing the create chunk upload task page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
const abortController = new AbortController()
let uploadId = ''
let cancelled = false
const cleanupCancelledSession = async () => {
if (uploadId && options.api.cancelUpload) {
await options.api.cancelUpload(uploadId).catch(() => undefined)
@@ -135,16 +113,29 @@ export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TRe
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
const uploadingChunkBytes = new Map<number, number>()
const pendingChunkIndexes = createPendingChunkIndexes(session.totalChunks, uploadedChunkSet)
const concurrency = Math.min(normalizeConcurrency(options.concurrency), Math.max(pendingChunkIndexes.length, 1))
const emitProgress = (limit: number) => {
const inFlightBytes = Array.from(uploadingChunkBytes.values()).reduce((total, loaded) => total + loaded, 0)
const percent = ((uploadedBytes + inFlightBytes) / Math.max(processedFile.size, 1)) * 100
options.onProgress?.(Math.min(percent, limit))
}
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
for (let chunkIndex = 0; chunkIndex < session.totalChunks; chunkIndex++) {
let nextChunkIndexCursor = 0
const uploadNextChunk = async (): Promise<void> => {
const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor]
nextChunkIndexCursor += 1
if (chunkIndex === undefined) {
return
}
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * session.chunkSize
const end = Math.min(start + session.chunkSize, processedFile.size)
@@ -162,17 +153,22 @@ export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TRe
signal: abortController.signal,
onUploadProgress: (event) => {
const loaded = Math.min(event.loaded || 0, chunkBytes)
const percent = ((uploadedBytes + loaded) / Math.max(processedFile.size, 1)) * 100
options.onProgress?.(Math.min(percent, 99.9))
uploadingChunkBytes.set(chunkIndex, loaded)
emitProgress(99.9)
}
}
)
uploadedChunkSet.add(chunkIndex)
uploadedBytes += chunkBytes
uploadingChunkBytes.delete(chunkIndex)
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
await uploadNextChunk()
}
await Promise.all(Array.from({ length: concurrency }, () => uploadNextChunk()))
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
@@ -0,0 +1,69 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const publicGetSignedUrl = vi.fn()
vi.mock('@/api/file', () => ({
fileApi: {
getSignedUrl: publicGetSignedUrl
}
}))
vi.mock('@/api/admin', () => ({
adminFileApi: {
getSignedUrl: vi.fn()
}
}))
describe('public-image-assets', () => {
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
publicGetSignedUrl.mockResolvedValue({ data: 'img.yunail.art/signed.jpg?token=1' })
})
it('prefers direct image urls over signing file ids', async () => {
const { resolvePublicImageUrls } = await import('./public-image-assets')
await expect(resolvePublicImageUrls({
imageUrls: ['http://img.yunail.art/direct.jpg'],
imageFileIds: '42'
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg'])
expect(publicGetSignedUrl).not.toHaveBeenCalled()
})
it('normalizes direct image urls without scheme', async () => {
const { resolvePublicImageUrls } = await import('./public-image-assets')
await expect(resolvePublicImageUrls({
imageUrls: ['img.yunail.art/direct.jpg?token=1']
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg?token=1'])
})
it('signs public file ids when direct urls are missing', async () => {
const { resolvePublicImageUrls, resolvePublicImageUrlsSync } = await import('./public-image-assets')
expect(resolvePublicImageUrlsSync({ imageFileIds: '42' }, 'fallback.png')).toEqual(['fallback.png'])
await expect(resolvePublicImageUrls({ imageFileIds: '42' }, 'fallback.png')).resolves.toEqual([
'http://img.yunail.art/signed.jpg?token=1'
])
expect(publicGetSignedUrl).toHaveBeenCalledWith('42')
})
it('extracts legacy file ids from old file urls', async () => {
const { getDirectPublicImageUrls, getPublicImageFileIds } = await import('./public-image-assets')
const record = {
imageUrl: '/api/file/get/325517232303947776',
imageFileIds: '325517232303947776,325517220106911744'
}
expect(getDirectPublicImageUrls(record)).toEqual([])
expect(getPublicImageFileIds(record)).toEqual(['325517232303947776', '325517220106911744'])
})
it('uses fallback when no image source is available', async () => {
const { resolvePublicImageUrls } = await import('./public-image-assets')
await expect(resolvePublicImageUrls({}, 'fallback.png')).resolves.toEqual(['fallback.png'])
})
})
@@ -0,0 +1,97 @@
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
import {
extractLegacyFileId,
getCachedSignedImageUrl,
getCachedSignedImageUrlSync,
parseImageFileIds,
refreshCachedSignedImageUrl
} from '@/utils/signed-image-cache'
export interface PublicImageRecord {
imageUrls?: string[] | string | null
imageFileIds?: string[] | string | null
coverImageUrl?: string | null
coverImageUrls?: string[] | string | null
coverImageFileId?: string[] | string | null
imageUrl?: string | null
}
const normalizePublicUrl = (value: unknown): string => {
const source = String(value || '').replace(/[`]/g, '').trim()
if (!source) return ''
if (/^\/?api\/file\/get\/\d+/i.test(source)) return ''
if (/^(https?:)?\/\//i.test(source) || /^(data|blob):/i.test(source) || source.startsWith('/')) {
return source.startsWith('//') ? `http:${source}` : source
}
if (source.includes('/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|#|$)/i.test(source)) {
return `http://${source}`
}
return ''
}
const normalizeUrlList = (value: unknown): string[] => {
const rawValues = Array.isArray(value) ? value : String(value || '').split(',')
return Array.from(new Set(rawValues.map(normalizePublicUrl).filter(Boolean)))
}
export const getPublicImageFileIds = (record: PublicImageRecord): string[] => {
const rawFileIds = [
...(Array.isArray(record.coverImageFileId) ? record.coverImageFileId : parseImageFileIds(String(record.coverImageFileId || ''))),
...(Array.isArray(record.imageFileIds) ? record.imageFileIds : parseImageFileIds(String(record.imageFileIds || ''))),
extractLegacyFileId(record.coverImageUrl),
extractLegacyFileId(record.imageUrl)
]
return Array.from(new Set(rawFileIds.map(id => String(id || '').trim()).filter(Boolean)))
}
export const getDirectPublicImageUrls = (record: PublicImageRecord): string[] => {
return Array.from(new Set([
...normalizeUrlList(record.coverImageUrls),
...normalizeUrlList(record.coverImageUrl),
...normalizeUrlList(record.imageUrls),
...normalizeUrlList(record.imageUrl)
]))
}
export const resolvePublicImageUrlsSync = (
record: PublicImageRecord,
fallback = DEFAULT_PRODUCT_IMAGE
): string[] => {
const directUrls = getDirectPublicImageUrls(record)
if (directUrls.length) return directUrls
const cachedUrls = getPublicImageFileIds(record)
.map(fileId => getCachedSignedImageUrlSync(fileId, 'public'))
.filter(Boolean)
if (cachedUrls.length) return cachedUrls
return fallback ? [fallback] : []
}
export const resolvePublicImageUrls = async (
record: PublicImageRecord,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string[]> => {
const directUrls = getDirectPublicImageUrls(record)
if (directUrls.length) return directUrls
const signedUrls = await Promise.all(getPublicImageFileIds(record).map(fileId => getCachedSignedImageUrl(fileId, '', 'public')))
const usableUrls = signedUrls.filter(Boolean)
if (usableUrls.length) return usableUrls
return fallback ? [fallback] : []
}
export const resolvePublicImageUrl = async (
record: PublicImageRecord,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string> => {
const urls = await resolvePublicImageUrls(record, fallback)
return urls[0] || fallback
}
export const refreshPublicImageUrl = async (
fileId: IdType | null | undefined,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'public')
@@ -0,0 +1,70 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const publicGetSignedUrl = vi.fn()
const adminGetSignedUrl = vi.fn()
vi.mock('@/api/file', () => ({
fileApi: {
getSignedUrl: publicGetSignedUrl
}
}))
vi.mock('@/api/admin', () => ({
adminFileApi: {
getSignedUrl: adminGetSignedUrl
}
}))
describe('signed-image-cache', () => {
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
publicGetSignedUrl.mockResolvedValue({ data: 'https://public.test/image.jpg' })
adminGetSignedUrl.mockResolvedValue('https://admin.test/image.jpg')
})
it('keeps public and admin signed url cache entries isolated', async () => {
const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache')
await expect(getCachedSignedImageUrl('42', '', 'public')).resolves.toBe('https://public.test/image.jpg')
await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/image.jpg')
expect(publicGetSignedUrl).toHaveBeenCalledTimes(1)
expect(adminGetSignedUrl).toHaveBeenCalledTimes(1)
expect(getCachedSignedImageUrlSync('42', 'public')).toBe('https://public.test/image.jpg')
expect(getCachedSignedImageUrlSync('42', 'admin')).toBe('https://admin.test/image.jpg')
})
it('uses fallback when file id is empty or signing fails', async () => {
const { getCachedSignedImageUrl } = await import('./signed-image-cache')
await expect(getCachedSignedImageUrl('', 'fallback.png', 'public')).resolves.toBe('fallback.png')
publicGetSignedUrl.mockRejectedValueOnce(new Error('sign failed'))
await expect(getCachedSignedImageUrl('99', 'fallback.png', 'public')).resolves.toBe('fallback.png')
})
it('normalizes signed image urls without scheme', async () => {
const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache')
adminGetSignedUrl.mockResolvedValueOnce('img.yunail.art/325517220106911744.jpg?e=1&token=test')
await expect(getCachedSignedImageUrl('325517232303947776', '', 'admin')).resolves.toBe(
'http://img.yunail.art/325517220106911744.jpg?e=1&token=test'
)
expect(getCachedSignedImageUrlSync('325517232303947776', 'admin')).toBe(
'http://img.yunail.art/325517220106911744.jpg?e=1&token=test'
)
})
it('refreshes a cached signed image url after clearing the old entry', async () => {
const { getCachedSignedImageUrl, refreshCachedSignedImageUrl } = await import('./signed-image-cache')
adminGetSignedUrl
.mockResolvedValueOnce('https://admin.test/old.jpg')
.mockResolvedValueOnce('https://admin.test/new.jpg')
await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/old.jpg')
await expect(refreshCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/new.jpg')
expect(adminGetSignedUrl).toHaveBeenCalledTimes(2)
})
})
+61 -12
View File
@@ -1,8 +1,11 @@
import { fileApi } from '@/api/file'
import { adminFileApi } from '@/api/admin'
import type { IdType } from '@/utils/id'
const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000
export type SignedImageSource = 'public' | 'admin'
type SignedImageCacheEntry = {
url: string
expiresAt: number
@@ -12,6 +15,22 @@ const signedImageUrlCache = new Map<string, SignedImageCacheEntry>()
const pendingSignedImageUrlRequests = new Map<string, Promise<string>>()
const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim()
const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}`
const normalizeImageUrl = (url: string): string => {
const trimmedUrl = url.trim()
if (!trimmedUrl) return ''
if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) {
return trimmedUrl
}
return `http://${trimmedUrl}`
}
const requestSignedImageUrl = (source: SignedImageSource, fileId: string): Promise<string> => {
if (source === 'admin') {
return adminFileApi.getSignedUrl(fileId)
}
return fileApi.getSignedUrl(fileId).then(response => String(response.data || ''))
}
const getUsableCacheEntry = (key: string) => {
const cached = signedImageUrlCache.get(key)
@@ -29,17 +48,23 @@ export const parseImageFileIds = (value?: string | null): string[] =>
.map(id => id.trim())
.filter(Boolean)
export const getCachedSignedImageUrlSync = (fileId: IdType | null | undefined): string => {
const key = normalizeFileId(fileId)
return key ? getUsableCacheEntry(key) || '' : ''
export const getCachedSignedImageUrlSync = (
fileId: IdType | null | undefined,
source: SignedImageSource = 'public'
): string => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return ''
return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || ''
}
export const getCachedSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback = ''
fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => {
const key = normalizeFileId(fileId)
if (!key) return fallback
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return fallback
const key = buildCacheKey(source, fileIdKey)
const cachedUrl = getUsableCacheEntry(key)
if (cachedUrl) return cachedUrl
@@ -49,9 +74,9 @@ export const getCachedSignedImageUrl = async (
return pendingRequest.then(url => url || fallback).catch(() => fallback)
}
const request = fileApi.getSignedUrl(key)
const request = requestSignedImageUrl(source, fileIdKey)
.then(response => {
const url = String(response || '').trim()
const url = normalizeImageUrl(String(response || ''))
if (url) {
signedImageUrlCache.set(key, {
url,
@@ -68,17 +93,41 @@ export const getCachedSignedImageUrl = async (
return request.then(url => url || fallback).catch(() => fallback)
}
export const clearCachedSignedImageUrl = (
fileId: IdType | null | undefined,
source: SignedImageSource = 'public'
): void => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return
const cacheKey = buildCacheKey(source, fileIdKey)
signedImageUrlCache.delete(cacheKey)
pendingSignedImageUrlRequests.delete(cacheKey)
}
export const refreshCachedSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => {
clearCachedSignedImageUrl(fileId, source)
return getCachedSignedImageUrl(fileId, fallback, source)
}
export const getCachedSignedImageUrls = async (
fileIds: Array<IdType | null | undefined>,
fallback = ''
fallback = '',
source: SignedImageSource = 'public'
): Promise<string[]> => {
const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId)))
const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source)))
const validUrls = urls.filter(Boolean)
return validUrls.length ? validUrls : (fallback ? [fallback] : [])
}
export const getCachedSignedImageUrlsSync = (fileIds: Array<IdType | null | undefined>): string[] =>
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId)).filter(Boolean)
export const getCachedSignedImageUrlsSync = (
fileIds: Array<IdType | null | undefined>,
source: SignedImageSource = 'public'
): string[] =>
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean)
export const extractLegacyFileId = (value?: string | null): string => {
const source = String(value || '').replace(/<[^>]*>/g, '')
+72 -2
View File
@@ -14,6 +14,12 @@ import {
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrl,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
import {
nailArtistApi,
type NailArtistAvailabilityVO,
@@ -21,11 +27,13 @@ import {
type NailArtistReviewVO,
type NailArtistWorkVO
} from '@/api/nail-artist'
import { productApi, type ProductVO } from '@/api/product'
const route = useRoute()
const router = useRouter()
const profile = shallowRef<NailArtistProfileVO | null>(null)
const workImageUrls = ref<Record<string, string>>({})
const reviews = ref<NailArtistReviewVO[]>([])
const availability = ref<NailArtistAvailabilityVO[]>([])
const loading = shallowRef(false)
@@ -41,7 +49,10 @@ const serviceCountText = computed(() => formatCompactNumber(Number(profile.value
const goodRateText = computed(() => ratingValue.value > 0 ? `${Math.min(99, Math.round((ratingValue.value / 5) * 100))}%` : '暂无')
const works = computed<NailArtistWorkVO[]>(() => profile.value?.works || [])
const styleTags = computed(() => profile.value?.styleTags?.filter(Boolean) || [])
const firstWorkImage = computed(() => works.value.find(work => work.coverImageUrl)?.coverImageUrl || DEFAULT_PRODUCT_IMAGE)
const firstWorkImage = computed(() => {
const firstWork = works.value.find(work => getWorkImage(work) !== DEFAULT_PRODUCT_IMAGE)
return firstWork ? getWorkImage(firstWork) : DEFAULT_PRODUCT_IMAGE
})
const workTimeText = computed(() => {
const start = profile.value?.workStartTime?.slice(0, 5)
const end = profile.value?.workEndTime?.slice(0, 5)
@@ -85,6 +96,8 @@ const filteredWorks = computed(() => {
return works.value.filter(work => work.tags?.includes(workFilter.value))
})
const PROFILE_WORK_LIMIT = 20
const certificationText = computed(() => {
const identity = profile.value?.identity || '认证美甲师'
const experience = Number(profile.value?.experience || 0)
@@ -135,6 +148,60 @@ const openProduct = (work: NailArtistWorkVO) => {
router.push(`/product/${work.id}`)
}
const getWorkImage = (work: NailArtistWorkVO) => workImageUrls.value[String(work.id)] || work.coverImageUrl || DEFAULT_PRODUCT_IMAGE
const isArtistBookableForProduct = (product: ProductVO) => {
const ids = String(product.bookableArtists || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
return ids.includes(artistId.value)
}
const mapProductToWork = (product: ProductVO): NailArtistWorkVO & { imageFileIds?: string } => ({
id: product.id,
title: product.title || product.name,
description: product.description,
price: product.price,
imageUrls: product.imageUrls,
imageFileIds: product.imageFileIds,
tags: product.tagList || product.tags?.split(/[;,,、]/).map(tag => tag.trim()).filter(Boolean),
likeCount: product.likeCount,
collectCount: product.collectCount
})
const loadSupplementWorks = async (existingWorks: NailArtistWorkVO[]): Promise<NailArtistWorkVO[]> => {
if (existingWorks.length >= PROFILE_WORK_LIMIT) {
return existingWorks.slice(0, PROFILE_WORK_LIMIT)
}
const existingIds = new Set(existingWorks.map(work => String(work.id)))
const products = await productApi.getAllProducts().catch(() => [])
const supplementWorks = products
.filter(product => !existingIds.has(String(product.id)))
.filter(product => !profile.value?.shopId || String(product.shopId || '') === String(profile.value.shopId))
.filter(isArtistBookableForProduct)
.slice(0, PROFILE_WORK_LIMIT - existingWorks.length)
.map(mapProductToWork)
return [...existingWorks, ...supplementWorks]
}
const loadWorkImages = async (nextWorks: NailArtistWorkVO[]) => {
const entries = await Promise.all(nextWorks.map(async work => {
const cachedUrls = resolvePublicImageUrlsSync(work as NailArtistWorkVO & Record<string, unknown>, '')
const imageUrl = cachedUrls[0] || await resolvePublicImageUrl(work as NailArtistWorkVO & Record<string, unknown>, DEFAULT_PRODUCT_IMAGE)
return [String(work.id), imageUrl] as const
}))
workImageUrls.value = Object.fromEntries(entries)
}
const handleWorkImageError = async (work: NailArtistWorkVO) => {
const fileId = getPublicImageFileIds(work as NailArtistWorkVO & Record<string, unknown>)[0]
const imageUrl = fileId ? await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE
workImageUrls.value = { ...workImageUrls.value, [String(work.id)]: imageUrl }
}
const openShop = () => {
if (!profile.value?.shopId) {
message.info('门店信息暂未完善')
@@ -191,6 +258,9 @@ const loadProfile = async () => {
profile.value = profileData
availability.value = availabilityData || profileData.availability || []
reviews.value = reviewData || profileData.reviews || []
const nextWorks = await loadSupplementWorks(profileData.works || [])
profile.value = { ...profileData, works: nextWorks }
await loadWorkImages(nextWorks)
selectedDate.value = availability.value[0]?.dateText || String(availability.value[0]?.startTime || '').slice(0, 10)
} catch (error) {
loadError.value = error instanceof Error ? error.message : '美甲师个人页加载失败'
@@ -317,7 +387,7 @@ onMounted(loadProfile)
</div>
<div v-if="filteredWorks.length" class="work-grid">
<button v-for="work in filteredWorks" :key="work.id" type="button" class="work-card" @click="openProduct(work)">
<img :src="work.coverImageUrl || DEFAULT_PRODUCT_IMAGE" :alt="work.title || '作品'" loading="lazy" decoding="async" />
<img :src="getWorkImage(work)" :alt="work.title || '作品'" loading="lazy" decoding="async" @error="handleWorkImageError(work)" />
<span>{{ work.title || '美甲作品' }}</span>
</button>
</div>
+71 -184
View File
@@ -10,40 +10,19 @@
<main class="auth-page">
<section class="brand-stage" aria-label="指尖设计师">
<div class="brand-mark" aria-hidden="true">
<span>指</span>
</div>
<p class="brand-name">指尖设计师</p>
<h1 class="brand-title">
{{ activeTab === 'login' ? '艺术触手可及' : '开启你的预约账号' }}
</h1>
<p class="brand-copy">
{{ activeTab === 'login' ? '选择门店,继续你的美甲灵感旅程。' : '注册后即可收藏款式、预约服务并同步门店权益。' }}
</p>
<p class="brand-copy">{{ activeTab === 'login' ? '登录后继续预约与收藏' : '填写信息完成账号注册' }}</p>
</section>
<section class="auth-container" aria-label="账号登录注册">
<div class="auth-card-header">
<span class="auth-card-kicker">{{ activeTab === 'login' ? 'Welcome back' : 'Create account' }}</span>
<h2>{{ activeTab === 'login' ? '登录账号' : '注册账号' }}</h2>
</div>
<div class="tab-container">
<div
class="tab-item"
:class="{ active: activeTab === 'login' }"
<button
v-if="activeTab === 'register'"
class="auth-mode-link auth-mode-link--top"
type="button"
@click="activeTab = 'login'"
>
账号登录
</div>
<div
class="tab-item"
:class="{ active: activeTab === 'register' }"
@click="activeTab = 'register'"
>
注册账号
</div>
</div>
返回登录
</button>
<div v-if="activeTab === 'login'" class="login-type-toggle">
<a-radio-group v-model:value="loginType" button-style="solid">
@@ -345,6 +324,13 @@
<div class="admin-login">
<span class="admin-login-link" @click="handleAdminLogin">管理后台登录</span>
</div>
<div v-if="activeTab === 'login'" class="auth-mode-footer">
<span>还没有账号?</span>
<button class="auth-mode-link" type="button" @click="activeTab = 'register'">
注册账号
</button>
</div>
</a-form>
</section>
</main>
@@ -1334,8 +1320,9 @@ onBeforeUnmount(() => {
var(--theme-page-bg) 100%
),
var(--theme-background-image),
var(--theme-gradient),
var(--theme-gradient-soft);
background-size: cover, cover, auto;
background-size: cover, cover, auto, auto;
background-position: center top;
color: var(--text-primary);
overflow-x: hidden;
@@ -1389,113 +1376,41 @@ onBeforeUnmount(() => {
display: flex;
flex-direction: column;
justify-content: center;
gap: 22px;
gap: 14px;
margin: 0 auto;
}
.brand-stage {
width: 100%;
text-align: center;
padding: 12px 10px 0;
}
.brand-mark {
width: 76px;
height: 76px;
margin: 0 auto 14px;
display: grid;
place-items: center;
border-radius: 999px;
background:
linear-gradient(
145deg,
color-mix(in srgb, var(--theme-card-bg) 88%, transparent),
color-mix(in srgb, var(--theme-primary-soft) 84%, var(--theme-card-bg))
);
border: 1px solid color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-border));
box-shadow: var(--theme-button-shadow);
}
.brand-mark span {
width: 52px;
height: 52px;
display: grid;
place-items: center;
border-radius: 999px;
background: var(--theme-gradient);
color: var(--theme-card-bg);
font-family: "Playfair Display", serif;
font-size: 24px;
font-weight: 700;
line-height: 1;
letter-spacing: 0;
padding: 6px 10px 0;
}
.brand-name {
margin: 0;
color: var(--theme-primary-action);
font-family: "Playfair Display", serif;
font-size: 28px;
font-weight: 700;
line-height: 1.05;
letter-spacing: 0;
}
.brand-title {
margin: 8px 0 0;
color: var(--text-primary);
font-family: "Playfair Display", serif;
font-size: 22px;
font-weight: 600;
font-size: 24px;
font-weight: 800;
line-height: 1.2;
letter-spacing: 0;
}
.brand-copy {
max-width: 310px;
margin: 10px auto 0;
margin: 8px auto 0;
color: var(--text-secondary);
font-size: 14px;
line-height: 1.7;
font-size: 13px;
line-height: 1.5;
letter-spacing: 0;
}
.auth-container {
width: 100%;
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent);
border: 1px solid color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-border));
border-radius: 28px;
padding: 22px 18px 20px;
box-shadow: 0 22px 46px color-mix(in srgb, var(--theme-primary) 14%, transparent);
backdrop-filter: blur(18px);
}
.auth-card-header {
margin-bottom: 18px;
}
.auth-card-kicker {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 4px 10px;
border-radius: 999px;
background: color-mix(in srgb, var(--theme-primary-soft) 82%, var(--theme-card-bg));
color: var(--theme-primary-action);
font-size: 12px;
font-weight: 700;
line-height: 1;
letter-spacing: 0;
}
.auth-card-header h2 {
margin: 10px 0 0;
color: var(--text-primary);
font-family: "Playfair Display", serif;
font-size: 22px;
font-weight: 600;
line-height: 1.25;
letter-spacing: 0;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
border-radius: 18px;
padding: 20px 18px 18px;
box-shadow: 0 12px 28px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.logo-section {
@@ -1515,41 +1430,6 @@ onBeforeUnmount(() => {
color: var(--text-secondary);
}
.tab-container {
display: flex;
gap: 8px;
margin-bottom: 18px;
padding: 5px;
border: 1px solid var(--theme-border);
border-radius: 999px;
background: color-mix(in srgb, var(--theme-primary-soft) 52%, var(--theme-card-bg));
}
.tab-item {
flex: 1;
text-align: center;
min-height: 42px;
padding: 11px 8px;
border-radius: 999px;
font-size: 14px;
font-weight: 700;
color: var(--text-secondary);
cursor: pointer;
transition: background 0.25s ease, color 0.25s ease, box-shadow 0.25s ease;
position: relative;
user-select: none;
}
.tab-item.active {
color: var(--theme-card-bg);
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.tab-item.active::after {
display: none;
}
.login-type-toggle {
margin-bottom: 18px;
}
@@ -1666,16 +1546,11 @@ onBeforeUnmount(() => {
}
.shop-select-item {
margin: 4px 0 18px;
padding: 14px;
border-radius: 22px;
margin: 0 0 14px;
padding: 10px 12px;
border-radius: 16px;
border: 1px solid var(--theme-border);
background:
linear-gradient(
145deg,
color-mix(in srgb, var(--theme-card-bg) 88%, var(--theme-primary-soft)),
color-mix(in srgb, var(--theme-secondary-soft) 32%, var(--theme-card-bg))
);
background: color-mix(in srgb, var(--theme-card-bg) 92%, var(--theme-primary-soft));
}
.shop-select-item :deep(.ant-form-item-label > label) {
@@ -1826,6 +1701,38 @@ onBeforeUnmount(() => {
text-decoration: underline;
}
.auth-mode-footer {
display: flex;
justify-content: center;
align-items: center;
gap: 6px;
margin-top: 14px;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.5;
}
.auth-mode-link {
padding: 0;
border: 0;
background: transparent;
color: var(--theme-primary-action);
font-size: 13px;
font-weight: 700;
line-height: 1.5;
letter-spacing: 0;
cursor: pointer;
}
.auth-mode-link:hover {
text-decoration: underline;
}
.auth-mode-link--top {
display: inline-flex;
margin: 0 0 16px;
}
.phone-login-tip {
margin-top: 8px;
font-size: 12px;
@@ -1838,19 +1745,19 @@ onBeforeUnmount(() => {
min-height: 52px;
border: none;
border-radius: 999px;
background: var(--theme-gradient);
background: var(--theme-primary-action);
color: var(--theme-card-bg);
font-size: 15px;
font-weight: 800;
letter-spacing: 0;
box-shadow: var(--theme-button-shadow);
box-shadow: 0 10px 22px color-mix(in srgb, var(--theme-primary) 16%, transparent);
}
.primary-action:not(:disabled):hover,
.primary-action:not(:disabled):focus {
background: var(--theme-gradient);
background: var(--theme-primary-action);
color: var(--theme-card-bg);
box-shadow: var(--theme-button-shadow);
box-shadow: 0 10px 22px color-mix(in srgb, var(--theme-primary) 16%, transparent);
}
.primary-action:disabled {
@@ -1953,27 +1860,11 @@ onBeforeUnmount(() => {
.auth-page {
min-height: calc(100svh - 92px);
gap: 18px;
}
.brand-mark {
width: 68px;
height: 68px;
margin-bottom: 12px;
}
.brand-mark span {
width: 48px;
height: 48px;
font-size: 22px;
gap: 12px;
}
.brand-name {
font-size: 28px;
}
.brand-title {
font-size: 21px;
font-size: 23px;
}
.brand-copy {
@@ -1981,12 +1872,8 @@ onBeforeUnmount(() => {
}
.auth-container {
border-radius: 24px;
border-radius: 18px;
padding: 20px 16px 18px;
}
.auth-card-header h2 {
font-size: 21px;
}
}
</style>
+280 -39
View File
@@ -34,7 +34,7 @@
>
<a-checkbox class="product-check" v-model:checked="item.selected" @change="handleToggleSelect" />
<button type="button" class="product-thumb" @click="openProduct(item)">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" />
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" @error="handleCartImageError(item)" />
<span v-else>{{ item.productTitle?.[0] || 'Y' }}</span>
</button>
@@ -92,10 +92,11 @@
<img
v-if="item.productImage"
:src="item.productImage"
:alt="item.productTitle"
loading="lazy"
decoding="async"
/>
:alt="item.productTitle"
loading="lazy"
decoding="async"
@error="handleCartImageError(item)"
/>
<span v-else>{{ item.productTitle?.[0] || 'Y' }}</span>
</div>
<div class="service-copy">
@@ -107,11 +108,11 @@
<RightOutlined />
</button>
<div v-if="item.availableArtists?.length" class="service-artist-strip">
<div v-if="getDisplayArtists(item).length" class="service-artist-strip">
<span class="service-label">选择美甲师</span>
<div class="service-artist-list">
<button
v-for="artist in item.availableArtists"
v-for="artist in getDisplayArtists(item)"
:key="artist.id"
type="button"
class="service-artist-option"
@@ -132,7 +133,7 @@
</div>
<div class="service-time-grid">
<button
v-for="slot in getQuickAppointmentSlots(item)"
v-for="slot in getDisplayQuickAppointmentSlots(item)"
:key="`${item.id}-${slot.value}`"
type="button"
class="service-time-option"
@@ -234,14 +235,14 @@
<a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal">
<div class="modal-section">
<div class="section-title">美甲师</div>
<div v-if="availableArtists.length" class="artist-list">
<div v-if="getDraftDisplayArtists().length" class="artist-list">
<button
v-for="artist in availableArtists"
v-for="artist in getDraftDisplayArtists()"
:key="artist.id"
type="button"
class="artist-option"
:class="{ active: sameId(draftArtistId, artist.id) }"
@click="draftArtistId = artist.id"
@click="selectDraftArtist(artist)"
>
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" loading="lazy" decoding="async" />
<span>{{ artist.name }}</span>
@@ -273,7 +274,7 @@
type="button"
class="quick-time"
:class="{ active: draftAppointmentTime === slot.value }"
@click="draftAppointmentTime = slot.value"
@click="selectDraftAppointmentTime(slot.value)"
>
<span>{{ slot.label }}</span>
<strong>{{ slot.time }}</strong>
@@ -313,7 +314,9 @@ import { sameId, toOptionalIdString } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { getBuyNowProductIdFromQuery, isBuyNowCartItem } from '@/utils/buy-now'
import { buildRecoveryActions, getRecoveryMessage } from '@/utils/recovery'
import { extractLegacyFileId, getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache'
import { extractLegacyFileId } from '@/utils/signed-image-cache'
import { normalizeApiErrorMessage } from '@/api/error'
import { refreshPublicImageUrl, resolvePublicImageUrl, resolvePublicImageUrlsSync } from '@/utils/public-image-assets'
/**
* Purpose: router supports CartView.vue by holding or executing the router page or API role.
@@ -397,6 +400,19 @@ interface CheckoutIssue {
productTitle?: string
}
interface AppointmentSlotOption {
value: string
label: string
time: string
}
interface BookableOptionState {
loading: boolean
artists: ArtistOption[]
slots: AppointmentSlotOption[]
validKeys: Set<string>
}
/**
* Purpose: cartItems supports CartView.vue by holding or executing the cart items page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -452,6 +468,7 @@ const currentShopHours = ref('')
const shopHoursById = ref<Record<string, string>>({})
/** submittingOrder is a reactive state variable used by the template and event handlers. */
const submittingOrder = ref(false)
const bookableOptionsByItemId = ref<Record<string, BookableOptionState>>({})
/** buyNowProductId limits checkout selection to the product that opened cart from "立即预约". */
const buyNowProductId = computed(() => getBuyNowProductIdFromQuery(route.query))
/** isBuyNowMode switches cart copy into a focused order-confirmation experience. */
@@ -501,12 +518,80 @@ const bookingHelperText = computed(() => {
/** quickAppointmentSlots is a reactive state variable used by the template and event handlers. */
const quickAppointmentSlots = computed(() => {
if (currentItem.value) {
return getQuickAppointmentSlots(currentItem.value)
return getDisplayQuickAppointmentSlotsForArtist(currentItem.value, draftArtistId.value)
}
return buildQuickAppointmentSlots()
})
const getItemKey = (item: CartItem) => toOptionalIdString(item.id) || toOptionalIdString(item.productId) || ''
const getBookableKey = (artistId: IdType, appointmentTime: string) => {
return `${toOptionalIdString(artistId) || ''}|${appointmentTime}`
}
const normalizeArtists = (item: CartItem): ArtistOption[] => {
return Array.isArray(item.availableArtists)
? (item.availableArtists || [])
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
}))
: []
}
const getBookableOptionState = (item: CartItem): BookableOptionState | null => {
const itemKey = getItemKey(item)
return itemKey ? bookableOptionsByItemId.value[itemKey] || null : null
}
const getDisplayArtists = (item: CartItem) => {
const state = getBookableOptionState(item)
return state ? state.artists : normalizeArtists(item)
}
const getDisplayQuickAppointmentSlots = (item: CartItem) => {
const state = getBookableOptionState(item)
return state ? state.slots : getQuickAppointmentSlots(item)
}
const getDisplayQuickAppointmentSlotsForArtist = (item: CartItem, artistId?: IdType) => {
const state = getBookableOptionState(item)
if (!state || !artistId) {
return getDisplayQuickAppointmentSlots(item)
}
return state.slots.filter(slot => state.validKeys.has(getBookableKey(artistId, slot.value)))
}
const getDraftDisplayArtists = () => {
if (!currentItem.value || !draftAppointmentTime.value) {
return availableArtists.value
}
const state = getBookableOptionState(currentItem.value)
if (!state) {
return availableArtists.value
}
return availableArtists.value.filter(artist =>
state.validKeys.has(getBookableKey(artist.id, draftAppointmentTime.value))
)
}
const hasBookableCombination = (item: CartItem, artistId?: IdType, appointmentTime?: string) => {
if (!artistId || !appointmentTime) {
return false
}
const state = getBookableOptionState(item)
if (!state) {
return true
}
return state.validKeys.has(getBookableKey(artistId, appointmentTime))
}
const buildQuickAppointmentSlots = (item?: CartItem) => {
const now = getMinAppointmentDate()
const today = new Date(now)
@@ -537,6 +622,94 @@ const buildQuickAppointmentSlots = (item?: CartItem) => {
const getQuickAppointmentSlots = (item: CartItem) => buildQuickAppointmentSlots(item)
const isCheckoutPreviewBookable = (preview: CheckoutPreview) => {
return preview.bookingAvailable !== false && !(preview.bookingIssues || []).length
}
const checkBookableCombination = async (item: CartItem, artist: ArtistOption, slot: AppointmentSlotOption) => {
try {
const preview = await orderApi.checkoutPreview({
items: [{
productId: item.productId,
quantity: item.quantity,
artistId: artist.id,
appointmentTime: slot.value
}]
})
return isCheckoutPreviewBookable(preview)
} catch {
return false
}
}
const refreshBookableOptions = async (item: CartItem) => {
const itemKey = getItemKey(item)
if (!itemKey) {
return
}
const artists = normalizeArtists(item)
const slots = getQuickAppointmentSlots(item)
bookableOptionsByItemId.value = {
...bookableOptionsByItemId.value,
[itemKey]: { loading: true, artists: [], slots: [], validKeys: new Set<string>() }
}
const checks = await Promise.all(artists.flatMap(artist =>
slots.map(async slot => ({
artist,
slot,
valid: await checkBookableCombination(item, artist, slot)
}))
))
const validKeys = new Set(
checks
.filter(check => check.valid)
.map(check => getBookableKey(check.artist.id, check.slot.value))
)
const validArtists = artists.filter(artist =>
slots.some(slot => validKeys.has(getBookableKey(artist.id, slot.value)))
)
const validSlots = slots.filter(slot =>
artists.some(artist => validKeys.has(getBookableKey(artist.id, slot.value)))
)
bookableOptionsByItemId.value = {
...bookableOptionsByItemId.value,
[itemKey]: { loading: false, artists: validArtists, slots: validSlots, validKeys }
}
if (item.artistId && !validArtists.some(artist => sameId(artist.id, item.artistId))) {
item.artistId = undefined
item.artist = undefined
}
if (item.appointmentTime && !validSlots.some(slot => slot.value === item.appointmentTime)) {
item.appointmentTime = ''
}
}
const refreshSelectedBookableOptions = async () => {
await Promise.all(selectedItems.value.map(item => refreshBookableOptions(item)))
}
const findFirstSlotForArtist = (item: CartItem, artistId: IdType) => {
const state = getBookableOptionState(item)
return state?.slots.find(slot => state.validKeys.has(getBookableKey(artistId, slot.value)))
}
const findFirstArtistForSlot = (item: CartItem, appointmentTime: string) => {
const state = getBookableOptionState(item)
return state?.artists.find(artist => state.validKeys.has(getBookableKey(artist.id, appointmentTime)))
}
const findInvalidBookableCombination = () => {
return selectedItems.value.find(item =>
item.artistId
&& item.appointmentTime
&& !hasBookableCombination(item, item.artistId, item.appointmentTime)
)
}
/** getMinAppointmentDate is a local helper used by this page script. */
const getMinAppointmentDate = () => {
const date = new Date()
@@ -730,7 +903,7 @@ const mapApiCheckoutIssue = (issue: ApiCheckoutIssue): CheckoutIssue | null => {
return {
key: `server-${issue.code || issue.message}`,
message: issue.message,
message: normalizeApiErrorMessage(issue.message),
itemId: matchedItem?.id || issue.itemId,
productId: issue.productId,
productTitle: issue.productTitle || matchedItem?.productTitle
@@ -816,9 +989,10 @@ const isDisplayableImageSource = (value?: string | null) => {
const getInitialCartImage = (rawImage?: string, previousImage?: string) => {
const imageId = extractLegacyFileId(rawImage)
const cachedUrl = imageId ? getCachedSignedImageUrlSync(imageId) : ''
const cachedUrl = imageId ? resolvePublicImageUrlsSync({ imageFileIds: imageId }, '')[0] : ''
if (cachedUrl) return cachedUrl
if (previousImage) return previousImage
if (imageId) return ''
return isDisplayableImageSource(rawImage) ? String(rawImage) : ''
}
@@ -846,6 +1020,7 @@ const loadCartItems = async () => {
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
await Promise.all([loadProductImages(), loadCartItemShopHours()])
await refreshSelectedBookableOptions()
await loadAvailableCoupons()
} finally {
cartLoading.value = false
@@ -866,13 +1041,18 @@ const loadProductImages = async () => {
}
continue
}
const cachedUrl = getCachedSignedImageUrlSync(imageId)
const cachedUrl = resolvePublicImageUrlsSync({ imageFileIds: imageId }, '')[0]
if (cachedUrl) item.productImage = cachedUrl
const signedUrl = await getCachedSignedImageUrl(imageId, item.productImage || item.originalProductImage)
const signedUrl = await resolvePublicImageUrl({ imageFileIds: imageId }, item.productImage || '')
if (signedUrl) item.productImage = signedUrl
}
}
const handleCartImageError = async (item: CartItem) => {
const imageId = extractLegacyFileId(item.originalProductImage)
item.productImage = imageId ? await refreshPublicImageUrl(imageId, '') : ''
}
const loadCartItemShopHours = async () => {
const shopIds = Array.from(new Set(
cartItems.value
@@ -963,7 +1143,10 @@ const loadAvailableCoupons = async () => {
/** handleToggleSelect is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleToggleSelect = async () => {
await runWithGlobalLoading(() => loadAvailableCoupons())
await runWithGlobalLoading(async () => {
await refreshSelectedBookableOptions()
await loadAvailableCoupons()
})
}
/** changeQuantity is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -974,6 +1157,7 @@ const changeQuantity = async (item: CartItem, delta: number) => {
try {
await runWithGlobalLoading(async () => {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: next })
await refreshBookableOptions(item)
await loadAvailableCoupons()
})
await updateCartCount()
@@ -1007,12 +1191,20 @@ const openProduct = (item: CartItem) => {
const selectInlineArtist = async (item: CartItem, artist: ArtistOption) => {
item.artistId = artist.id
item.artist = artist
if (!hasBookableCombination(item, artist.id, item.appointmentTime)) {
item.appointmentTime = findFirstSlotForArtist(item, artist.id)?.value || ''
}
await runWithGlobalLoading(() => loadAvailableCoupons())
}
/** selectInlineTime updates a cart item's appointment slot from the page-level service detail controls. */
const selectInlineTime = async (item: CartItem, appointmentTime: string) => {
item.appointmentTime = appointmentTime
if (!hasBookableCombination(item, item.artistId, appointmentTime)) {
const artist = findFirstArtistForSlot(item, appointmentTime)
item.artistId = artist?.id
item.artist = artist
}
await runWithGlobalLoading(() => loadAvailableCoupons())
}
@@ -1022,28 +1214,21 @@ const openBookingModal = async (item: CartItem) => {
draftArtistId.value = item.artistId
draftAppointmentTime.value = item.appointmentTime || ''
showBookingModal.value = true
await runWithGlobalLoading(() => Promise.all([loadArtists(item), loadShopHours(item.shopId)]))
await runWithGlobalLoading(async () => {
await Promise.all([refreshBookableOptions(item), loadShopHours(item.shopId)])
await loadArtists(item)
})
}
/** loadArtists is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadArtists = async (item: CartItem) => {
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。
availableArtists.value = Array.isArray(item.availableArtists)
? item.availableArtists
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
}))
: []
availableArtists.value = getDisplayArtists(item)
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
draftArtistId.value = undefined
}
if (draftAppointmentTime.value && !hasBookableCombination(item, draftArtistId.value, draftAppointmentTime.value)) {
draftAppointmentTime.value = ''
}
}
/** loadShopHours is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -1097,6 +1282,26 @@ const disablePastAppointmentTime = (current: any) => {
}
}
const selectDraftArtist = (artist: ArtistOption) => {
if (!currentItem.value) {
return
}
draftArtistId.value = artist.id
if (!hasBookableCombination(currentItem.value, artist.id, draftAppointmentTime.value)) {
draftAppointmentTime.value = findFirstSlotForArtist(currentItem.value, artist.id)?.value || ''
}
}
const selectDraftAppointmentTime = (appointmentTime: string) => {
if (!currentItem.value) {
return
}
draftAppointmentTime.value = appointmentTime
if (!hasBookableCombination(currentItem.value, draftArtistId.value, appointmentTime)) {
draftArtistId.value = findFirstArtistForSlot(currentItem.value, appointmentTime)?.id
}
}
/** closeBookingModal is a local helper used by this page script. */
const closeBookingModal = () => {
showBookingModal.value = false
@@ -1113,6 +1318,9 @@ const confirmBooking = async () => {
if (!draftArtistId.value) return message.warning('请先选择美甲师')
if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
if (!hasBookableCombination(currentItem.value, draftArtistId.value, draftAppointmentTime.value)) {
return message.warning('请选择可预约的美甲师和时间')
}
currentItem.value.artistId = draftArtistId.value
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
currentItem.value.appointmentTime = draftAppointmentTime.value
@@ -1138,20 +1346,36 @@ const applyCouponSelection = async () => {
await runWithGlobalLoading(() => loadAvailableCoupons())
}
let checkoutRecoveryModal: { destroy: () => void } | null = null
const openCheckoutRecovery = (error: unknown) => {
checkoutRecoveryModal?.destroy()
checkoutRecoveryModal = null
const recoveryMessage = error instanceof Error
? normalizeApiErrorMessage(error.message)
: normalizeApiErrorMessage(getRecoveryMessage(error, '询价预约发起失败'))
const actions = buildRecoveryActions([
{ key: 'retry', text: '重试发起询价' },
{ key: 'orders', text: '查看订单' }
])
const retryAction = actions[0]
const ordersAction = actions[1]
Modal.confirm({
checkoutRecoveryModal = Modal.confirm({
title: '发起询价预约失败',
content: `${getRecoveryMessage(error, '询价预约发起失败')}。如果担心重复提交,请先查看订单;仍失败时请联系客服。`,
content: `${recoveryMessage}。如担心重复提交,请先查看订单;仍失败时请联系管理员。`,
closable: true,
okText: retryAction?.text || '重试发起询价',
cancelText: ordersAction?.text || '查看订单',
onOk: () => checkout(),
onCancel: () => router.push(ordersAction?.route || '/orders')
onOk: () => {
checkoutRecoveryModal?.destroy()
checkoutRecoveryModal = null
void checkout()
},
onCancel: () => {
checkoutRecoveryModal?.destroy()
checkoutRecoveryModal = null
void router.push(ordersAction?.route || '/orders')
}
})
}
@@ -1172,6 +1396,18 @@ const checkout = async () => {
return message.warning('请先选择要结算的作品')
}
await runWithGlobalLoading(async () => {
await refreshSelectedBookableOptions()
await loadAvailableCoupons()
})
const invalidCombination = findInvalidBookableCombination()
if (invalidCombination) {
message.warning(`"${invalidCombination.productTitle}" 当前美甲师和预约时间不可预约,请重新选择`)
scrollToIssue({ key: 'bookable-combination', message: '请选择可预约的美甲师和时间', itemId: invalidCombination.id })
return
}
const firstIssue = checkoutIssues.value[0]
if (firstIssue) {
message.warning(firstIssue.message)
@@ -1214,7 +1450,12 @@ const checkout = async () => {
}
}
} catch (error: any) {
console.error('创建订单失败:', error)
const checkoutErrorMessage = normalizeApiErrorMessage(error instanceof Error ? error.message : getRecoveryMessage(error, '询价预约发起失败'))
if (checkoutErrorMessage.includes('不可预约')) {
console.warn('询价预约被业务规则拦截:', checkoutErrorMessage)
} else {
console.error('创建订单失败:', error)
}
openCheckoutRecovery(error)
} finally {
submittingOrder.value = false
+48 -31
View File
@@ -73,6 +73,7 @@
class="feature-banner__image"
:loading="index === 0 ? 'eager' : 'lazy'"
decoding="async"
@error="handleProductCardImageError(item)"
/>
<div class="feature-banner__shade"></div>
<div class="feature-banner__copy">
@@ -131,7 +132,7 @@
@click="handleProductClick(item)"
>
<div class="product-img">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" />
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" @error="handleProductCardImageError(item)" />
<span v-else>{{ item.name[0] }}</span>
</div>
<div class="product-info">
@@ -164,7 +165,7 @@
@click="handleProductClick(item)"
>
<div class="product-img">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" />
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" @error="handleProductCardImageError(item)" />
<span v-else>{{ item.name[0] }}</span>
</div>
<div class="product-info">
@@ -208,7 +209,7 @@
type="button"
@click="openShopById(shop.shopId)"
>
<img :src="shop.url" :alt="shop.shopName" loading="lazy" decoding="async" />
<img :src="shop.url" :alt="shop.shopName" loading="lazy" decoding="async" @error="handleBannerImageError(shop)" />
<span>{{ shop.shopName }}</span>
</button>
</div>
@@ -250,7 +251,12 @@ import { shopApi, type ShopVO } from '../api/shop'
import { DEFAULT_AVATAR, DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
import { extractRichText, renderRichContent } from '@/utils/rich-content'
import { getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrl,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
/**
* Purpose: BannerImage supports HomeView.vue by holding or executing the banner image page or API role.
@@ -262,6 +268,7 @@ interface BannerImage {
shopName: string
businessHours?: string
url: string
imageFileId?: string
}
/**
@@ -275,6 +282,7 @@ interface ProductCardItem {
meta: string
shopName?: string
coverUrl: string
imageFileId?: string
bgColor: string
}
@@ -421,14 +429,9 @@ const getRandomColor = (): string => {
/** getProductCoverUrl is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const getProductCoverUrl = async (product: ProductVO): Promise<string> => {
const firstImageId = product.imageFileIds?.split(',').map(id => id.trim()).find(Boolean)
if (firstImageId) {
return getCachedSignedImageUrlSync(firstImageId) || await getCachedSignedImageUrl(firstImageId, DEFAULT_PRODUCT_IMAGE)
}
const directImageUrl = product.imageUrls?.map(url => String(url || '').trim())
.find(url => /^(https?:\/\/|data:image\/|blob:|\/assets\/)/.test(url))
return directImageUrl || DEFAULT_PRODUCT_IMAGE
const cachedUrls = resolvePublicImageUrlsSync(product, '')
if (cachedUrls.length) return cachedUrls[0] || DEFAULT_PRODUCT_IMAGE
return resolvePublicImageUrl(product, DEFAULT_PRODUCT_IMAGE)
}
/** formatProductCards is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const formatProductCards = async (products: ProductVO[]): Promise<ProductCardItem[]> =>
@@ -439,6 +442,7 @@ const formatProductCards = async (products: ProductVO[]): Promise<ProductCardIte
meta: item.approximateDuration || item.shopName || '支持预约',
shopName: item.shopName,
coverUrl: await getProductCoverUrl(item),
imageFileId: getPublicImageFileIds(item)[0],
bgColor: getRandomColor()
})))
@@ -484,30 +488,43 @@ const loadPublicShops = async () => {
const loadBannerImages = async () => {
const banners: BannerImage[] = []
for (const shop of publicShops.value) {
const coverIds = (shop.coverImageFileId || shop.imageFileIds || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
for (const id of coverIds) {
try {
const url = getCachedSignedImageUrlSync(id) || await getCachedSignedImageUrl(id)
if (url) {
banners.push({
id: `${shop.id}-${id}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours,
url
})
}
} catch (error) {
console.error('获取门店轮播图失败:', error)
}
const imageRecord = {
coverImageFileId: shop.coverImageFileId,
imageFileIds: shop.imageFileIds,
imageUrls: shop.imageUrls
}
const fileId = getPublicImageFileIds(imageRecord)[0]
const url = await resolvePublicImageUrl(imageRecord, '')
if (url) {
banners.push({
id: `${shop.id}-${fileId || url}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours,
url,
imageFileId: fileId
})
}
}
bannerImages.value = banners.slice(0, 8)
}
const replaceProductCardImage = (items: ProductCardItem[], productId: IdType, imageUrl: string): ProductCardItem[] =>
items.map(item => String(item.id) === String(productId) ? { ...item, coverUrl: imageUrl } : item)
const handleProductCardImageError = async (item: ProductCardItem) => {
const imageUrl = item.imageFileId ? await refreshPublicImageUrl(item.imageFileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE
newArrivalItems.value = replaceProductCardImage(newArrivalItems.value, item.id, imageUrl)
featuredItems.value = replaceProductCardImage(featuredItems.value, item.id, imageUrl)
popularSource.value = replaceProductCardImage(popularSource.value, item.id, imageUrl)
popularItems.value = replaceProductCardImage(popularItems.value, item.id, imageUrl)
}
const handleBannerImageError = async (shop: BannerImage) => {
const imageUrl = shop.imageFileId ? await refreshPublicImageUrl(shop.imageFileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE
bannerImages.value = bannerImages.value.map(item => item.id === shop.id ? { ...item, url: imageUrl } : item)
}
/** loadNewArrivalProducts fills the top carousel with products tagged as new arrivals. */
const loadNewArrivalProducts = async () => {
try {
+54 -17
View File
@@ -36,6 +36,7 @@
:alt="`${productTitle} 图片 ${index + 1}`"
:loading="index === 0 ? 'eager' : 'lazy'"
decoding="async"
@error="handleProductImageError(index)"
/>
</button>
</div>
@@ -54,6 +55,7 @@
:alt="`${productTitle} 图片 ${index + 1}`"
:loading="index === 0 ? 'eager' : 'lazy'"
decoding="async"
@error="handleProductImageError(index)"
/>
</button>
</div>
@@ -218,9 +220,9 @@
</span>
</div>
<p>{{ comment.commentContent }}</p>
<div v-if="comment.imageUrls?.length" class="review-images">
<div v-if="getCommentImages(comment).length" class="review-images">
<a-image
v-for="(image, index) in comment.imageUrls"
v-for="(image, index) in getCommentImages(comment)"
:key="`${comment.id}-${index}`"
class="review-image"
:src="image"
@@ -323,7 +325,13 @@ import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
import { toOptionalIdString } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { getCachedSignedImageUrls, getCachedSignedImageUrlsSync, parseImageFileIds } from '@/utils/signed-image-cache'
import { createChunkUploadTask } from '@/utils/chunk-upload'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrls,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
import { buildRatingStars, normalizeCommentRating } from '@/utils/comment-review'
/**
@@ -366,6 +374,7 @@ const productImagePreviewIndex = ref(0)
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const comments = ref<CommentVO[]>([])
const commentImageUrls = ref<Record<string, string[]>>({})
/** commentText is a reactive state variable used by the template and event handlers. */
const commentText = ref('')
/**
@@ -484,25 +493,24 @@ const requireLogin = (actionText: string) => {
const loadProductImages = async () => {
productImagesReady.value = false
productImagePreviewIndex.value = 0
const fileIds = parseImageFileIds(product.value.imageFileIds)
if (!fileIds.length) {
const fallbackImages = [DEFAULT_PRODUCT_IMAGE]
productImages.value = fallbackImages
productImagesReady.value = true
return
}
const cachedImages = getCachedSignedImageUrlsSync(fileIds)
const cachedImages = resolvePublicImageUrlsSync(product.value, '')
if (cachedImages.length) {
productImages.value = cachedImages
productImagesReady.value = true
}
const nextImages = await getCachedSignedImageUrls(fileIds, DEFAULT_PRODUCT_IMAGE)
const nextImages = await resolvePublicImageUrls(product.value, DEFAULT_PRODUCT_IMAGE)
productImages.value = nextImages
productImagesReady.value = true
}
const handleProductImageError = async (imageIndex: number) => {
const fileId = getPublicImageFileIds(product.value)[imageIndex]
productImages.value[imageIndex] = DEFAULT_PRODUCT_IMAGE
if (!fileId) return
productImages.value[imageIndex] = await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE)
}
/** loadShopInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadShopInfo = async (shopId?: IdType | null) => {
shopInfo.value = shopId ? await shopApi.getShopById(shopId).catch(() => null) : null
@@ -511,9 +519,20 @@ const loadShopInfo = async (shopId?: IdType | null) => {
/** loadComments is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadComments = async () => {
if (!product.value.id) return
comments.value = await commentApi.listByProduct(product.value.id).catch(() => [])
const nextComments = await commentApi.listByProduct(product.value.id).catch(() => [])
comments.value = nextComments
const entries = await Promise.all(nextComments.map(async comment => {
const urls = await resolvePublicImageUrls({
imageUrls: comment.imageUrls,
imageFileIds: Array.isArray(comment.imageFileIds) ? comment.imageFileIds.map(id => String(id)).join(',') : comment.imageFileIds
}, '')
return [String(comment.id), urls] as const
}))
commentImageUrls.value = Object.fromEntries(entries)
}
const getCommentImages = (comment: CommentVO): string[] => commentImageUrls.value[String(comment.id)] || []
/** checkInteractionStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkInteractionStatus = async () => {
if (!isLoggedIn.value || !product.value.id) {
@@ -651,8 +670,23 @@ const handleUploadCommentImage: UploadProps['customRequest'] = async options =>
return String(item.uid) === uid ? { ...item, url: previewUrl, thumbUrl: previewUrl, status: 'uploading' } : item
})
const task = createChunkUploadTask({
file,
scene: 'comment-image',
concurrency: 3,
api: {
initUpload: commentApi.initImageChunkUpload,
uploadChunk: commentApi.uploadImageChunk,
completeUpload: commentApi.completeImageChunkUpload,
cancelUpload: commentApi.cancelImageChunkUpload
},
onProgress: (percent) => {
options.onProgress?.({ percent })
}
})
try {
const uploaded = await commentApi.uploadImage(file)
const { response: uploaded } = await task.promise
const stillListed = commentImageFileList.value.some(item => String(item.uid) === uid)
if (!stillListed) {
URL.revokeObjectURL(previewUrl)
@@ -669,8 +703,11 @@ const handleUploadCommentImage: UploadProps['customRequest'] = async options =>
commentImageFileList.value = commentImageFileList.value.map(item => {
return String(item.uid) === uid ? { ...item, status: 'error' } : item
})
options.onError?.(error)
message.error(error?.message || '评价图片上传失败')
const errorMessage = error?.message || '评价图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
options.onError?.(error)
message.error(errorMessage)
}
} finally {
uploadingCommentImages.value = Math.max(0, uploadingCommentImages.value - 1)
}
+21 -11
View File
@@ -75,6 +75,7 @@
class="product-image"
loading="lazy"
decoding="async"
@error="handleProductImageError(item)"
/>
<div v-else class="product-img-placeholder">
<span>{{ (item.title || item.name)?.[0] || '作' }}</span>
@@ -189,7 +190,12 @@ import { tagApi, type TagFilterGroupVO, type TagVO } from '@/api/tag'
import { cartApi } from '@/api/cart'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state'
import { getCachedSignedImageUrls, getCachedSignedImageUrlsSync, parseImageFileIds } from '@/utils/signed-image-cache'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrls,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
/**
* Purpose: ProductListItem supports ProductListView.vue by holding or executing the product list item page or API role.
@@ -323,24 +329,28 @@ const ensureLoginForAction = (actionText: string) => {
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (productList: ProductVO[]) => {
for (const product of productList) {
if (!product.imageFileIds) {
imageUrls.value[String(product.id)] = [DEFAULT_PRODUCT_IMAGE]
continue
}
const ids = parseImageFileIds(product.imageFileIds)
const cachedUrls = getCachedSignedImageUrlsSync(ids)
const productKey = String(product.id)
const cachedUrls = resolvePublicImageUrlsSync(product, '')
if (cachedUrls.length) {
imageUrls.value[String(product.id)] = cachedUrls
imageUrls.value[productKey] = cachedUrls
}
const urls = await getCachedSignedImageUrls(ids, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[String(product.id)] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
const urls = await resolvePublicImageUrls(product, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: ProductVO): string[] => imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
const handleProductImageError = async (product: ProductVO) => {
const productKey = String(product.id)
const firstFileId = getPublicImageFileIds(product)[0]
imageUrls.value[productKey] = [DEFAULT_PRODUCT_IMAGE]
if (!firstFileId) return
const refreshedUrl = await refreshPublicImageUrl(firstFileId, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[productKey] = [refreshedUrl || DEFAULT_PRODUCT_IMAGE]
}
const displayProductDuration = (product: ProductVO) => {
const duration = product.approximateDuration?.trim()
if (duration) return duration
+27 -12
View File
@@ -604,15 +604,10 @@ const handleEditProfile = () => {
const beforeUploadAvatar: UploadProps['beforeUpload'] = file => {
const isImage = file.type.startsWith('image/')
const isLt20M = file.size / 1024 / 1024 < 20
if (!isImage) {
message.error('只能上传图片文件')
}
if (!isLt20M) {
message.error('图片大小不能超过 20MB')
}
return isImage && isLt20M
return isImage
}
/** handleAvatarUpload is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -626,6 +621,7 @@ const handleAvatarUpload = async (options: any) => {
const task = createChunkUploadTask({
file: file as File,
scene: 'profile-avatar',
concurrency: 3,
api: {
initUpload: fileApi.initAvatarChunkUpload,
uploadChunk: fileApi.uploadAvatarChunk,
@@ -684,18 +680,37 @@ const handleDeleteAvatar = () => {
}
/** handleWechatQrUpload uploads a user profile QR image without changing the avatar. */
const handleWechatQrUpload = async (options: any) => {
const { file, onSuccess, onError } = options
const handleWechatQrUpload: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
qrUploadPending.value = true
const task = createChunkUploadTask({
file: file as File,
scene: 'profile-wechat-qr',
concurrency: 3,
api: {
initUpload: fileApi.initProfileImageChunkUpload,
uploadChunk: fileApi.uploadProfileImageChunk,
completeUpload: fileApi.completeProfileImageChunkUpload,
cancelUpload: fileApi.cancelProfileImageChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
try {
const response = await fileApi.uploadProfileImage(file as File)
const { response } = await task.promise
editForm.wechatQrCode = response as unknown as string
onSuccess?.({ url: response })
message.success('微信二维码上传成功')
} catch (error) {
console.error('微信二维码上传失败:', error)
message.error((error as Error)?.message || '微信二维码上传失败')
onError?.(error)
const errorMessage = (error as Error)?.message || '微信二维码上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('微信二维码上传失败:', error)
message.error(errorMessage)
onError?.(error as Error)
}
} finally {
qrUploadPending.value = false
}
+22 -21
View File
@@ -308,11 +308,12 @@ import { nailArtistApi } from '@/api/nail-artist'
import { userApi, type ContactInfoVO } from '@/api/user'
import { toOptionalIdString } from '@/utils/id'
import {
getCachedSignedImageUrl,
getCachedSignedImageUrls,
getCachedSignedImageUrlSync,
parseImageFileIds
} from '@/utils/signed-image-cache'
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrl,
resolvePublicImageUrls
} from '@/utils/public-image-assets'
import { parseImageFileIds } from '@/utils/signed-image-cache'
/**
* Purpose: router supports ShopDetailView.vue by holding or executing the router page or API role.
@@ -412,15 +413,13 @@ const artistCount = computed(() => {
const featuredProducts = computed(() => trustProfile.value?.featuredProducts || [])
const featuredProductCards = computed(() => featuredProducts.value.map(product => {
const productId = String(product.id)
const fileIds = parseFileIdList(product.imageFileIds)
const cachedUrl = fileIds[0] ? getCachedSignedImageUrlSync(fileIds[0]) : ''
const directUrl = normalizeImageUrl(product.imageUrl)
return {
...product,
displayImageUrl: failedFeaturedProductImages.value[productId]
? ''
: (featuredProductImageUrls.value[productId] || cachedUrl || directUrl)
: (featuredProductImageUrls.value[productId] || directUrl)
}
}))
/**
@@ -629,23 +628,25 @@ const copyContactInfo = async () => {
}
const handleFeaturedImageError = (productId: string | number) => {
failedFeaturedProductImages.value = {
...failedFeaturedProductImages.value,
[String(productId)]: true
const product = featuredProducts.value.find(item => String(item.id) === String(productId))
const fileId = product ? getPublicImageFileIds({ imageFileIds: product.imageFileIds, imageUrl: product.imageUrl })[0] : ''
if (!fileId) {
failedFeaturedProductImages.value = {
...failedFeaturedProductImages.value,
[String(productId)]: true
}
return
}
refreshPublicImageUrl(fileId, '').then(url => {
featuredProductImageUrls.value = { ...featuredProductImageUrls.value, [String(productId)]: url }
failedFeaturedProductImages.value = { ...failedFeaturedProductImages.value, [String(productId)]: false }
})
}
const loadFeaturedProductImages = async () => {
const entries = await Promise.all(featuredProducts.value.map(async product => {
const productId = String(product.id)
const firstFileId = parseFileIdList(product.imageFileIds)[0]
if (!firstFileId) {
return [productId, normalizeImageUrl(product.imageUrl)] as const
}
const cachedUrl = getCachedSignedImageUrlSync(firstFileId)
const signedUrl = cachedUrl || await getCachedSignedImageUrl(firstFileId)
const signedUrl = await resolvePublicImageUrl({ imageFileIds: product.imageFileIds, imageUrl: product.imageUrl }, '')
return [productId, signedUrl] as const
}))
@@ -674,8 +675,8 @@ const loadShopImages = async () => {
])
const environmentFileIds = parseFileIdList(shop.imageFileIds)
const [bannerSignedUrls, environmentSignedUrls] = await Promise.all([
getCachedSignedImageUrls(bannerFileIds),
getCachedSignedImageUrls(environmentFileIds)
resolvePublicImageUrls({ imageFileIds: bannerFileIds.join(',') }, ''),
resolvePublicImageUrls({ imageFileIds: environmentFileIds.join(',') }, '')
])
const bannerUrls = bannerFileIds.length > 0
+10 -13
View File
@@ -92,7 +92,8 @@ import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state'
import { getCachedSignedImageUrls, getCachedSignedImageUrlsSync, parseImageFileIds } from '@/utils/signed-image-cache'
import { resolvePublicImageUrls, resolvePublicImageUrlsSync } from '@/utils/public-image-assets'
import type { PublicImageRecord } from '@/utils/public-image-assets'
/**
* Purpose: router supports WishlistView.vue by holding or executing the router page or API role.
@@ -158,22 +159,18 @@ const fetchWishlist = async () => {
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (items: WishlistItem[]) => {
for (const item of items) {
if (item.product.imageFileIds) {
const ids = parseImageFileIds(item.product.imageFileIds)
const cachedUrls = getCachedSignedImageUrlsSync(ids)
if (cachedUrls.length) {
imageUrls.value[String(item.product.id)] = cachedUrls
}
const urls = await getCachedSignedImageUrls(ids, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[String(item.product.id)] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
} else {
imageUrls.value[String(item.product.id)] = [DEFAULT_PRODUCT_IMAGE]
const productKey = String(item.product.id)
const cachedUrls = resolvePublicImageUrlsSync(item.product as PublicImageRecord, '')
if (cachedUrls.length) {
imageUrls.value[productKey] = cachedUrls
}
const urls = await resolvePublicImageUrls(item.product as PublicImageRecord, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: any): string[] => {
const getProductImages = (product: { id: IdType }): string[] => {
return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
}
+24 -35
View File
@@ -219,6 +219,7 @@ import {
UserOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import type { Component } from 'vue'
/**
* Purpose: UserVO supports AdminLayout.vue by holding or executing the user vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
@@ -230,6 +231,7 @@ import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permis
import { runWithGlobalLoading } from '@/utils/action-loading'
import { notifyShopThemeChanged } from '@/utils/shop-theme'
import { useAdminViewport } from '@/composables/useAdminViewport'
import { adminNavigationItems, findAdminNavigationItemByPath, type AdminNavIconKey } from '@/config/admin-navigation'
import {
getAdminCurrentShopName,
getAdminRoleLabel,
@@ -237,17 +239,6 @@ import {
isBootstrapAdminUser
} from './admin-helpers'
/**
* Purpose: AdminMenuItem supports AdminLayout.vue by holding or executing the admin menu item page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
type AdminMenuItem = {
key: string
icon: any
label: string
permissionCode: string
}
/**
* Purpose: router supports AdminLayout.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -283,29 +274,27 @@ const selectedShopId = ref<string>()
const shopSwitchLoading = ref(false)
const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission()
const menuItems: AdminMenuItem[] = [
{ key: '/admin', icon: HomeOutlined, label: '首页', permissionCode: '' },
{ key: '/admin/dashboard', icon: DashboardOutlined, label: '仪表盘', permissionCode: 'dashboard:view' },
{ key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' },
{ key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' },
{ key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' },
{ key: '/admin/comments', icon: MessageOutlined, label: '评论管理', permissionCode: 'comment:view' },
{ key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' },
{ key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' },
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' },
{ key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order:view' },
{ key: '/admin/schedules', icon: CalendarOutlined, label: '排班管理', permissionCode: 'schedule:view' },
{ key: '/admin/after-sales', icon: MessageOutlined, label: '售后处理', permissionCode: 'after_sale:view' },
{ key: '/admin/inventory', icon: ToolOutlined, label: '库存管理', permissionCode: 'inventory:view' },
{ key: '/admin/campaigns', icon: GiftOutlined, label: '活动管理', permissionCode: 'campaign:view' },
{ key: '/admin/nail-artists', icon: TeamOutlined, label: '美甲师管理', permissionCode: 'nail_artist:view' }
,
{ key: '/admin/messages', icon: MessageOutlined, label: '消息发布', permissionCode: 'message:view' },
{ key: '/admin/announcements', icon: MessageOutlined, label: '公告管理', permissionCode: 'announcement:view' },
{ key: '/admin/vip-recharge-plans', icon: GiftOutlined, label: 'VIP充值配置', permissionCode: 'user:vip:manage' },
{ key: '/admin/messagehub-push-configs', icon: MessageOutlined, label: '参数管理', permissionCode: 'messagehub:config:manage' },
{ key: '/admin/legal-agreements', icon: SafetyCertificateOutlined, label: '协议管理', permissionCode: 'legal_agreement:manage' }
]
const adminMenuIconMap: Record<AdminNavIconKey, Component> = {
home: HomeOutlined,
dashboard: DashboardOutlined,
user: UserOutlined,
shop: ShopOutlined,
gift: GiftOutlined,
message: MessageOutlined,
security: SafetyCertificateOutlined,
tag: TagOutlined,
shopping: ShoppingOutlined,
calendar: CalendarOutlined,
tool: ToolOutlined,
team: TeamOutlined
}
const menuItems = adminNavigationItems.map(item => ({
key: item.path,
icon: adminMenuIconMap[item.iconKey],
label: item.label,
permissionCode: item.permissionCode
}))
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
@@ -364,7 +353,7 @@ const currentMobileSectionLabel = computed(() => {
/** currentMobileTitle is a reactive state variable used by the template and event handlers. */
const currentMobileTitle = computed(() => {
const currentMenu = menuItems.find(item => item.key === route.path)
const currentMenu = findAdminNavigationItemByPath(route.path)
if (currentMenu) {
return currentMenu.label
}
+62 -173
View File
@@ -69,6 +69,7 @@
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false"
@error="handleProductImageError(record, index)"
/>
<a-image
v-if="getProductImages(record).length === 0"
@@ -128,6 +129,7 @@
class="admin-mobile-card__cover admin-mobile-card__cover--wide"
:src="getProductImages(item)[0] || DEFAULT_PRODUCT_IMAGE"
:preview="false"
@error="handleProductImageError(item, 0)"
/>
<div class="admin-mobile-card__head" style="margin-top: 14px">
<div class="admin-mobile-card__body">
@@ -244,7 +246,7 @@
<div style="margin-top: 8px">上传图片</div>
</div>
</a-upload>
<div class="upload-tip">支持多选上传,不限制上传张数,单张图片超过 5MB 会自动压缩后再上传。</div>
<div class="upload-tip">支持多选上传,不限制上传张数,大图将自动使用分片并发上传。</div>
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
<a-modal v-model:open="previewVisible" :footer="null" :mask-closable="false" @cancel="previewVisible = false">
<img alt="预览" style="width: 100%" :src="previewImage" />
@@ -536,6 +538,7 @@
*/
import { computed, ref, reactive, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
@@ -552,10 +555,20 @@ import { adminProductApi, type Product, adminShopApi, type Shop, adminFileApi, a
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import { MAX_IMAGE_UPLOAD_SIZE, compressImageIfNeeded, formatFileSize } from '@/utils/image-upload'
import {
buildAdminUploadFileList,
buildSignedImageUrlMap,
getRecordImageUrls,
refreshSignedImageUrl,
resolveSignedImageUrl,
resolveSignedImageUrls
} from '@/utils/admin-image-assets'
import { parseImageFileIds } from '@/utils/signed-image-cache'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { createAdminPagination, applyAdminTablePaginationChange, type AdminTablePaginationChange } from '@/utils/admin-table'
import { resolveUploadedFileId, type AdminUploadFileLike, type AdminUploadTaskFile } from '@/utils/admin-upload-file'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
@@ -671,11 +684,6 @@ const imageUrls = ref<Record<string, string[]>>({})
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const viewImageUrls = ref<string[]>([])
/**
* Purpose: imageIdCache supports ProductsView.vue by holding or executing the image id cache page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const imageIdCache = ref<Record<string, string>>({})
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false)
/**
@@ -751,14 +759,7 @@ const viewFormState = reactive({
* Purpose: pagination supports ProductsView.vue by holding or executing the pagination page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const pagination = reactive(createAdminPagination())
/**
* Purpose: formState supports ProductsView.vue by holding or executing the form state page or API role.
@@ -1053,53 +1054,35 @@ const resetFilters = () => {
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (products: Product[], requestToken?: number) => {
const nextImageUrls: Record<string, string[]> = {}
for (const product of products) {
if (requestToken && !isLatestRequestToken('products', requestToken)) {
return null
}
if (product.imageFileIds) {
const ids = product.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (requestToken && !isLatestRequestToken('products', requestToken)) {
return null
}
if (id) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
}
if (product.id) {
nextImageUrls[String(product.id)] = urls
}
} else {
if (product.id) {
nextImageUrls[String(product.id)] = [DEFAULT_PRODUCT_IMAGE]
}
}
}
return nextImageUrls
return buildSignedImageUrlMap(
products,
'imageFileIds',
DEFAULT_PRODUCT_IMAGE,
true,
() => Boolean(requestToken && !isLatestRequestToken('products', requestToken))
)
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: Product | Record<string, any>): string[] => {
const productId = 'id' in product ? product.id : (product as any).id
if (productId !== undefined) {
return imageUrls.value[String(productId)] || [DEFAULT_PRODUCT_IMAGE]
const getProductImages = (product: { id?: IdType }): string[] =>
getRecordImageUrls(product, imageUrls.value, [DEFAULT_PRODUCT_IMAGE])
const handleProductImageError = async (product: { id?: IdType; imageFileIds?: string }, imageIndex: number) => {
if (product.id === undefined || product.id === null) return
const fileId = parseImageFileIds(product.imageFileIds)[imageIndex]
if (!fileId) return
const refreshedUrl = await refreshSignedImageUrl(fileId, DEFAULT_PRODUCT_IMAGE)
if (!refreshedUrl || refreshedUrl === DEFAULT_PRODUCT_IMAGE) return
const productKey = String(product.id)
const currentUrls = imageUrls.value[productKey] || []
const nextUrls = [...currentUrls]
nextUrls[imageIndex] = refreshedUrl
imageUrls.value = {
...imageUrls.value,
[productKey]: nextUrls
}
return [DEFAULT_PRODUCT_IMAGE]
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -1109,9 +1092,10 @@ const handleSearch = async () => {
}
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
const handleTableChange = async (pag: AdminTablePaginationChange) => {
const nextPagination = applyAdminTablePaginationChange(pagination, pag)
pagination.current = nextPagination.current
pagination.pageSize = nextPagination.pageSize
await runWithGlobalLoading(() => fetchProductList())
}
@@ -1252,27 +1236,7 @@ const showViewModal = async (record: Product | Record<string, any>) => {
})
// 加载图片URL
if (recordImageFileIds) {
const ids = recordImageFileIds.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id) as unknown as string
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id])
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
viewImageUrls.value = urls
} else {
viewImageUrls.value = [DEFAULT_PRODUCT_IMAGE]
}
viewImageUrls.value = await resolveSignedImageUrls(recordImageFileIds, DEFAULT_PRODUCT_IMAGE, true)
// 获取该店铺的美甲师列表
if (recordShopId) {
@@ -1319,32 +1283,7 @@ const buildDraftPayload = () => ({
/** buildImageFileListByIds is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const buildImageFileListByIds = async (ids: string[]) => {
const fileList = []
for (const [index, id] of ids.entries()) {
try {
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id) as any
imageIdCache.value[id] = response
}
fileList.push({
uid: id,
fileId: id,
name: `图片${index + 1}`,
status: 'done',
url: imageIdCache.value[id]
})
} catch (error) {
console.error('获取签名链接失败:', error)
fileList.push({
uid: id,
fileId: id,
name: `图片${index + 1}`,
status: 'done',
url: ''
})
}
}
return fileList
return buildAdminUploadFileList(ids, '图片', DEFAULT_PRODUCT_IMAGE)
}
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -1390,37 +1329,8 @@ const syncUploadedFileIds = (fileIds: string[]) => {
formState.imageFileIds = uploadedFileIds.value.join(',')
}
/** getUploadResponse is a local helper used by this page script. */
const getUploadResponse = (file: any) => {
if (!file || typeof file !== 'object') {
return null
}
return file.response || null
}
/** resolveUploadedFileId is a local helper used by this page script. */
const resolveUploadedFileId = (file: any) => {
const response = getUploadResponse(file)
const responseId = response?.id ?? response?.data?.id ?? file?.fileId
if (responseId !== undefined && responseId !== null && responseId !== '') {
return String(responseId)
}
const fileUid = String(file?.uid || '')
if (/^\d+$/.test(fileUid)) {
return fileUid
}
const fileUrl = String(file?.url || '')
if (/^\d+$/.test(fileUrl)) {
return fileUrl
}
return ''
}
/** getPreviewUrlFromFile is a local helper used by this page script. */
const getPreviewUrlFromFile = (file: any) => {
const getPreviewUrlFromFile = (file: AdminUploadFileLike) => {
const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) {
return fileUrl
@@ -1445,41 +1355,25 @@ const beforeUpload = (file: File) => {
// 作品图片走分片上传,并在上传前做压缩兜底,保证大图也能稳定进入对象存储。
/** handleUploadImage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadImage = async (options: any) => {
const handleUploadImage: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
let successMessage = '图片上传成功'
const uploadFile = file as AdminUploadTaskFile
const task = createChunkUploadTask({
file: file as File,
file: uploadFile,
scene: 'admin-product-image',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
preprocessFile: async (originalFile) => {
const compressedResult = await compressImageIfNeeded(originalFile, MAX_IMAGE_UPLOAD_SIZE)
if (compressedResult.skippedReason) {
throw new Error(compressedResult.skippedReason)
}
if (compressedResult.finalSize > MAX_IMAGE_UPLOAD_SIZE) {
throw new Error('图片压缩后仍超过 5MB,请裁剪后重试')
}
if (compressedResult.compressed && compressedResult.originalSize !== compressedResult.finalSize) {
successMessage = `${originalFile.name} 已压缩并上传成功(${formatFileSize(compressedResult.originalSize)} -> ${formatFileSize(compressedResult.finalSize)})`
}
return compressedResult.file
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(String(file.uid), task)
uploadTaskMap.set(String(uploadFile.uid), task)
activeUploadCount.value += 1
try {
@@ -1487,42 +1381,37 @@ const handleUploadImage = async (options: any) => {
const fileId = String((response as any).id)
syncUploadedFileIds([...uploadedFileIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
message.success(successMessage)
message.success('图片上传成功')
} catch (error) {
const errorMessage = (error as Error)?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error)
message.error(errorMessage)
onError?.(error)
onError?.(error as never)
}
} finally {
uploadTaskMap.delete(String(file.uid))
uploadTaskMap.delete(String(uploadFile.uid))
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
}
}
// Ant Upload 的文件对象来源很多,预览时优先复用已有 URL,缺失时再回源签名地址。
/** handlePreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePreview = async (file: any) => {
const handlePreview: UploadProps['onPreview'] = async (file) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl
previewVisible.value = true
return
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
previewImage.value = imageIdCache.value[fileId] || ''
previewImage.value = await resolveSignedImageUrl(fileId, '')
previewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
@@ -1531,14 +1420,14 @@ const handlePreview = async (file: any) => {
}
/** handleRemove is a local helper used by this page script. */
const handleRemove = (file: any) => {
const handleRemove: UploadProps['onRemove'] = (file) => {
const uploadTask = uploadTaskMap.get(String(file.uid))
if (uploadTask) {
uploadTask.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
}
+269 -258
View File
@@ -47,15 +47,22 @@
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'image'">
<div class="shop-images">
<a-image
<div
v-for="(url, index) in getShopImages(record)"
:key="index"
:width="50"
:height="50"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false"
/>
class="shop-image-frame"
>
<a-spin v-if="isShopImageLoading(record, 'imageFileIds', index)" size="small" />
<img
:width="50"
:height="50"
:src="url"
class="shop-table-image"
alt="店铺图片"
@load="handleShopImageLoad(record, 'imageFileIds', index)"
@error="handleShopImageError(record, index)"
>
</div>
<a-image
v-if="getShopImages(record).length === 0"
:width="50"
@@ -68,15 +75,22 @@
</template>
<template v-else-if="column.key === 'banner'">
<div class="shop-banner">
<a-image
<div
v-for="(url, index) in getShopBannerImages(record)"
:key="index"
:width="80"
:height="40"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false"
/>
class="shop-image-frame shop-image-frame--banner"
>
<a-spin v-if="isShopImageLoading(record, 'coverImageFileId', index)" size="small" />
<img
:width="80"
:height="40"
:src="url"
class="shop-table-image"
alt="店铺Banner"
@load="handleShopImageLoad(record, 'coverImageFileId', index)"
@error="handleShopBannerImageError(record, index)"
>
</div>
<span v-if="getShopBannerImages(record).length === 0" class="no-banner">暂无Banner</span>
</div>
</template>
@@ -133,11 +147,16 @@
<AdminMobileCardList v-else :items="shopList" empty-description="暂无店铺数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<a-image
class="admin-mobile-card__cover admin-mobile-card__cover--wide"
:src="getShopBannerImages(item)[0] || getShopImages(item)[0] || DEFAULT_SHOP_IMAGE"
:preview="false"
/>
<div class="shop-mobile-cover-frame">
<a-spin v-if="isShopCoverImageLoading(item)" size="small" />
<img
class="admin-mobile-card__cover admin-mobile-card__cover--wide"
:src="getShopBannerImages(item)[0] || getShopImages(item)[0] || DEFAULT_SHOP_IMAGE"
alt="店铺封面"
@load="handleShopCoverImageLoad(item)"
@error="handleShopCoverImageError(item)"
>
</div>
<div class="admin-mobile-card__head" style="margin-top: 14px">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.shopName }}</div>
@@ -584,7 +603,7 @@
*/
import { computed, ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { FormInstance, UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
@@ -602,6 +621,18 @@ import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-uploa
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { createAdminPagination, applyAdminTablePaginationChange, type AdminTablePaginationChange } from '@/utils/admin-table'
import { resolveUploadedFileId, type AdminUploadFileLike, type AdminUploadTaskFile } from '@/utils/admin-upload-file'
import type { IdType } from '@/utils/id'
import {
buildAdminUploadFileList,
buildSignedImageUrlMap,
getRecordImageUrls,
refreshSignedImageUrl,
resolveSignedImageUrl,
resolveSignedImageUrls
} from '@/utils/admin-image-assets'
import { parseImageFileIds } from '@/utils/signed-image-cache'
import { notifyShopThemeChanged, resolveShopTheme } from '@/utils/shop-theme'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
@@ -842,11 +873,6 @@ const themeBackgroundFileList = ref<any[]>([])
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const uploadedThemeBackgroundId = ref('')
/**
* Purpose: imageIdCache supports ShopsView.vue by holding or executing the image id cache page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const imageIdCache = ref<Record<string, string>>({})
/**
* Purpose: shopImageUrls supports ShopsView.vue by holding or executing the shop image urls page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -857,6 +883,7 @@ const shopImageUrls = ref<Record<string, string[]>>({})
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shopBannerUrls = ref<Record<string, string[]>>({})
const shopImageLoadingKeys = ref<Record<string, boolean>>({})
/**
* Purpose: viewImageUrls supports ShopsView.vue by holding or executing the view image urls page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -933,14 +960,7 @@ const viewFormState = reactive({
* Purpose: pagination supports ShopsView.vue by holding or executing the pagination page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const pagination = reactive(createAdminPagination())
/**
* Purpose: formState supports ShopsView.vue by holding or executing the form state page or API role.
@@ -1253,85 +1273,142 @@ const getThemeTemplateStorageKey = () => {
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (shops: Shop[]) => {
for (const shop of shops) {
// 加载店铺图片
if (shop.imageFileIds) {
const ids = shop.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
}
if (shop.id !== undefined) {
shopImageUrls.value[String(shop.id)] = urls
}
} else {
if (shop.id !== undefined) {
shopImageUrls.value[String(shop.id)] = []
}
}
// 加载Banner图片
if (shop.coverImageFileId) {
const ids = shop.coverImageFileId.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
}
if (shop.id !== undefined) {
shopBannerUrls.value[String(shop.id)] = urls
}
} else {
if (shop.id !== undefined) {
shopBannerUrls.value[String(shop.id)] = []
}
}
}
const [nextShopImageUrls, nextShopBannerUrls] = await Promise.all([
buildSignedImageUrlMap(shops, 'imageFileIds', DEFAULT_SHOP_IMAGE, false, () => false),
buildSignedImageUrlMap(shops, 'coverImageFileId', DEFAULT_SHOP_IMAGE, false, () => false)
])
shopImageUrls.value = nextShopImageUrls || {}
shopBannerUrls.value = nextShopBannerUrls || {}
}
/** getShopImages is a local helper used by this page script. */
const getShopImages = (shop: Shop | Record<string, any>): string[] => {
const shopId = 'id' in shop ? shop.id : (shop as any).id
if (shopId !== undefined) {
return shopImageUrls.value[String(shopId)] || []
}
return []
}
const getShopImages = (shop: { id?: IdType }): string[] =>
getRecordImageUrls(shop, shopImageUrls.value, [])
/** getShopBannerImages is a local helper used by this page script. */
const getShopBannerImages = (shop: Shop | Record<string, any>): string[] => {
const shopId = 'id' in shop ? shop.id : (shop as any).id
if (shopId !== undefined) {
return shopBannerUrls.value[String(shopId)] || []
const getShopBannerImages = (shop: { id?: IdType }): string[] =>
getRecordImageUrls(shop, shopBannerUrls.value, [])
const getShopImageLoadingKey = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number
): string => `${String(shop.id ?? '')}:${fieldName}:${imageIndex}`
const setShopImageLoading = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number,
loadingValue: boolean
): void => {
const key = getShopImageLoadingKey(shop, fieldName, imageIndex)
if (!key.startsWith(':')) {
shopImageLoadingKeys.value = {
...shopImageLoadingKeys.value,
[key]: loadingValue
}
}
return []
}
const isShopImageLoading = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number
): boolean => {
const key = getShopImageLoadingKey(shop, fieldName, imageIndex)
return shopImageLoadingKeys.value[key] !== false
}
const handleShopImageLoad = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number
): void => {
setShopImageLoading(shop, fieldName, imageIndex, false)
}
const isShopCoverImageLoading = (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string }
): boolean => {
const bannerFileIds = parseImageFileIds(shop.coverImageFileId)
if (bannerFileIds.length) {
return isShopImageLoading(shop, 'coverImageFileId', 0)
}
const imageFileIds = parseImageFileIds(shop.imageFileIds)
if (imageFileIds.length) {
return isShopImageLoading(shop, 'imageFileIds', 0)
}
return false
}
const handleShopCoverImageLoad = (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string }
): void => {
const bannerFileIds = parseImageFileIds(shop.coverImageFileId)
if (bannerFileIds.length) {
handleShopImageLoad(shop, 'coverImageFileId', 0)
return
}
handleShopImageLoad(shop, 'imageFileIds', 0)
}
const refreshShopImageUrl = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number,
imageUrlMap: Record<string, string[]>
) => {
if (shop.id === undefined || shop.id === null) return null
const fileId = parseImageFileIds(shop[fieldName])[imageIndex]
if (!fileId) return null
const refreshedUrl = await refreshSignedImageUrl(fileId, DEFAULT_SHOP_IMAGE)
if (!refreshedUrl || refreshedUrl === DEFAULT_SHOP_IMAGE) return null
const shopKey = String(shop.id)
const currentUrls = imageUrlMap[shopKey] || []
const nextUrls = [...currentUrls]
nextUrls[imageIndex] = refreshedUrl
return {
...imageUrlMap,
[shopKey]: nextUrls
}
}
const handleShopImageError = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string },
imageIndex: number
) => {
setShopImageLoading(shop, 'imageFileIds', imageIndex, false)
const nextImageUrls = await refreshShopImageUrl(shop, 'imageFileIds', imageIndex, shopImageUrls.value)
if (nextImageUrls) {
setShopImageLoading(shop, 'imageFileIds', imageIndex, true)
shopImageUrls.value = nextImageUrls
}
}
const handleShopBannerImageError = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string },
imageIndex: number
) => {
setShopImageLoading(shop, 'coverImageFileId', imageIndex, false)
const nextBannerUrls = await refreshShopImageUrl(shop, 'coverImageFileId', imageIndex, shopBannerUrls.value)
if (nextBannerUrls) {
setShopImageLoading(shop, 'coverImageFileId', imageIndex, true)
shopBannerUrls.value = nextBannerUrls
}
}
const handleShopCoverImageError = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string }
) => {
const bannerFileIds = parseImageFileIds(shop.coverImageFileId)
if (bannerFileIds.length) {
await handleShopBannerImageError(shop, 0)
return
}
await handleShopImageError(shop, 0)
}
/** formatAuthorizationExpireTime is a local helper used by this page script. */
@@ -1600,9 +1677,10 @@ const handleSearch = async () => {
}
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
const handleTableChange = async (pag: AdminTablePaginationChange) => {
const nextPagination = applyAdminTablePaginationChange(pagination, pag)
pagination.current = nextPagination.current
pagination.pageSize = nextPagination.pageSize
await runWithGlobalLoading(() => fetchShopList())
}
@@ -1610,23 +1688,21 @@ const handleTableChange = async (pag: any) => {
const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/')
if (!isImage) {
message.error('只能上传图片文件!')
message.error('只能上传图片文件')
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
message.error('图片大小不能超过 2MB!')
}
return isImage && isLt2M
return isImage
}
// Banner 与门店环境图分开维护上传任务,便于表单回显和删除时分别同步 fileId 列表。
/** handleUploadBanner is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadBanner = async (options: any) => {
const handleUploadBanner: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
const taskKey = `banner:${String(file.uid)}`
const uploadFile = file as AdminUploadTaskFile
const taskKey = `banner:${String(uploadFile.uid)}`
const task = createChunkUploadTask({
file: file as File,
file: uploadFile,
scene: 'admin-shop-banner',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
@@ -1652,7 +1728,7 @@ const handleUploadBanner = async (options: any) => {
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('Banner上传失败:', error)
message.error(errorMessage)
onError?.(error)
onError?.(error as never)
}
} finally {
uploadTaskMap.delete(taskKey)
@@ -1661,25 +1737,21 @@ const handleUploadBanner = async (options: any) => {
}
/** handleBannerPreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBannerPreview = async (file: any) => {
const handleBannerPreview: UploadProps['onPreview'] = async (file) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) {
bannerPreviewImage.value = cachedPreviewUrl
bannerPreviewVisible.value = true
return
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
bannerPreviewImage.value = imageIdCache.value[fileId] || ''
bannerPreviewImage.value = await resolveSignedImageUrl(fileId, '')
bannerPreviewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
@@ -1688,14 +1760,14 @@ const handleBannerPreview = async (file: any) => {
}
/** handleBannerRemove is a local helper used by this page script. */
const handleBannerRemove = (file: any) => {
const handleBannerRemove: UploadProps['onRemove'] = (file) => {
const task = uploadTaskMap.get(`banner:${String(file.uid)}`)
if (task) {
task.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) {
syncUploadedBannerIds(uploadedBannerIds.value.filter(id => id !== fileId))
}
@@ -1704,12 +1776,14 @@ const handleBannerRemove = (file: any) => {
// 店铺环境图与 Banner 走同一套分片上传协议,但写入不同业务字段。
/** handleUploadImage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadImage = async (options: any) => {
const handleUploadImage: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
const taskKey = `image:${String(file.uid)}`
const uploadFile = file as AdminUploadTaskFile
const taskKey = `image:${String(uploadFile.uid)}`
const task = createChunkUploadTask({
file: file as File,
file: uploadFile,
scene: 'admin-shop-image',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
@@ -1735,7 +1809,7 @@ const handleUploadImage = async (options: any) => {
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error)
message.error(errorMessage)
onError?.(error)
onError?.(error as never)
}
} finally {
uploadTaskMap.delete(taskKey)
@@ -1745,25 +1819,21 @@ const handleUploadImage = async (options: any) => {
// 编辑态下 Upload 里的文件可能只剩 fileId,所以预览时需要兼容本地 URL 与远端签名地址两种来源。
/** handlePreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePreview = async (file: any) => {
const handlePreview: UploadProps['onPreview'] = async (file) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl
previewVisible.value = true
return
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
previewImage.value = imageIdCache.value[fileId] || ''
previewImage.value = await resolveSignedImageUrl(fileId, '')
previewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
@@ -1772,14 +1842,14 @@ const handlePreview = async (file: any) => {
}
/** handleRemove is a local helper used by this page script. */
const handleRemove = (file: any) => {
const handleRemove: UploadProps['onRemove'] = (file) => {
const task = uploadTaskMap.get(`image:${String(file.uid)}`)
if (task) {
task.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
}
@@ -1787,12 +1857,14 @@ const handleRemove = (file: any) => {
}
/** handleUploadThemeBackground is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadThemeBackground = async (options: any) => {
const handleUploadThemeBackground: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
const taskKey = `theme-bg:${String(file.uid)}`
const uploadFile = file as AdminUploadTaskFile
const taskKey = `theme-bg:${String(uploadFile.uid)}`
const task = createChunkUploadTask({
file: file as File,
file: uploadFile,
scene: 'admin-shop-theme-background',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
@@ -1818,7 +1890,7 @@ const handleUploadThemeBackground = async (options: any) => {
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('背景图上传失败:', error)
message.error(errorMessage)
onError?.(error)
onError?.(error as never)
}
} finally {
uploadTaskMap.delete(taskKey)
@@ -1827,25 +1899,21 @@ const handleUploadThemeBackground = async (options: any) => {
}
/** handleThemeBackgroundPreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleThemeBackgroundPreview = async (file: any) => {
const handleThemeBackgroundPreview: UploadProps['onPreview'] = async (file) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) {
bannerPreviewImage.value = cachedPreviewUrl
bannerPreviewVisible.value = true
return
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) {
throw new Error('未找到背景图文件标识')
}
if (!imageIdCache.value[fileId]) {
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
bannerPreviewImage.value = imageIdCache.value[fileId] || ''
bannerPreviewImage.value = await resolveSignedImageUrl(fileId, '')
bannerPreviewVisible.value = true
} catch (error) {
console.error('获取背景图预览链接失败:', error)
@@ -1854,14 +1922,14 @@ const handleThemeBackgroundPreview = async (file: any) => {
}
/** handleThemeBackgroundRemove is a local helper used by this page script. */
const handleThemeBackgroundRemove = (file: any) => {
const handleThemeBackgroundRemove: UploadProps['onRemove'] = (file) => {
const task = uploadTaskMap.get(`theme-bg:${String(file.uid)}`)
if (task) {
task.cancel()
return true
}
const fileId = resolveUploadedFileId(file)
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) {
syncUploadedThemeBackgroundId('')
}
@@ -2015,53 +2083,11 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
themeBackgroundImageFileId: 'themeBackgroundImageFileId' in record ? record.themeBackgroundImageFileId : (record as any).themeBackgroundImageFileId
})
// 加载Banner图片URL
// 加载图片URL
const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId
if (coverImageFileId) {
const ids = coverImageFileId.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
viewBannerUrls.value = urls
} else {
viewBannerUrls.value = []
}
// 加载店铺图片URL
const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
if (imageFileIds) {
const ids = imageFileIds.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
viewImageUrls.value = urls
} else {
viewImageUrls.value = []
}
viewBannerUrls.value = await resolveSignedImageUrls(coverImageFileId, DEFAULT_SHOP_IMAGE, false)
viewImageUrls.value = await resolveSignedImageUrls(imageFileIds, DEFAULT_SHOP_IMAGE, false)
viewModalVisible.value = true
}
@@ -2113,32 +2139,7 @@ const buildDraftPayload = () => ({
/** buildShopUploadFileList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const buildShopUploadFileList = async (ids: string[], fileNamePrefix: string) => {
const fileList = []
for (const [index, id] of ids.entries()) {
try {
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
fileList.push({
uid: id,
fileId: id,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url: imageIdCache.value[id]
})
} catch (error) {
console.error('获取签名链接失败:', error)
fileList.push({
uid: id,
fileId: id,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url: ''
})
}
}
return fileList
return buildAdminUploadFileList(ids, fileNamePrefix, DEFAULT_SHOP_IMAGE)
}
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -2298,37 +2299,8 @@ const handleDeleteCustomThemeTemplate = (id: string) => {
message.success('已删除配色模板')
}
/** getUploadResponse is a local helper used by this page script. */
const getUploadResponse = (file: any) => {
if (!file || typeof file !== 'object') {
return null
}
return file.response || null
}
/** resolveUploadedFileId is a local helper used by this page script. */
const resolveUploadedFileId = (file: any) => {
const response = getUploadResponse(file)
const responseId = response?.id ?? response?.data?.id ?? file?.fileId
if (responseId !== undefined && responseId !== null && responseId !== '') {
return String(responseId)
}
const fileUid = String(file?.uid || '')
if (/^\d+$/.test(fileUid)) {
return fileUid
}
const fileUrl = String(file?.url || '')
if (/^\d+$/.test(fileUrl)) {
return fileUrl
}
return ''
}
/** getPreviewUrlFromFile is a local helper used by this page script. */
const getPreviewUrlFromFile = (file: any) => {
const getPreviewUrlFromFile = (file: AdminUploadFileLike) => {
const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) {
return fileUrl
@@ -2427,6 +2399,45 @@ onMounted(async () => {
gap: 4px;
}
.shop-image-frame {
position: relative;
display: inline-grid;
width: 50px;
height: 50px;
place-items: center;
overflow: hidden;
border-radius: 4px;
background: var(--theme-primary-soft);
}
.shop-image-frame--banner {
width: 80px;
height: 40px;
}
.shop-image-frame :deep(.ant-spin) {
position: absolute;
z-index: 1;
}
.shop-table-image {
display: block;
object-fit: cover;
border-radius: 4px;
}
.shop-mobile-cover-frame {
position: relative;
}
.shop-mobile-cover-frame :deep(.ant-spin) {
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.map-picker-card {
display: flex;
align-items: center;
@@ -169,6 +169,7 @@ import SystemMessageCard from '@/components/SystemMessageCard.vue'
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { adminFileApi, adminSystemMessageApi, type SystemMessageCreateRequest, type SystemMessageVO } from '@/api/admin'
import { createChunkUploadTask } from '@/utils/chunk-upload'
import type { IdType } from '@/utils/id'
/**
@@ -395,20 +396,34 @@ const handleImageUpload = async (options: any) => {
options.onError?.(new Error('invalid image'))
return
}
if (file.size > 5 * 1024 * 1024) {
message.warning('图片不能超过 5MB')
options.onError?.(new Error('image too large'))
return
}
imageUploading.value = true
const task = createChunkUploadTask({
file,
scene: 'admin-system-message-image',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
options.onProgress?.({ percent })
}
})
try {
const uploaded = await adminFileApi.uploadFile(file)
const { response: uploaded } = await task.promise
form.imageFileId = uploaded.id
imagePreviewUrl.value = await adminFileApi.getSignedUrl(uploaded.id)
options.onSuccess?.(uploaded)
} catch (error: any) {
message.error(error?.message || '图片上传失败')
options.onError?.(error)
const errorMessage = error?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
message.error(errorMessage)
options.onError?.(error)
}
} finally {
imageUploading.value = false
}
+27 -12
View File
@@ -550,7 +550,7 @@
*/
import { computed, h, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { FormInstance, UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import { DEFAULT_AVATAR } from '@/constants'
@@ -578,6 +578,7 @@ import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { createChunkUploadTask } from '@/utils/chunk-upload'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
@@ -888,30 +889,44 @@ const handlePhoneInput = () => {
/** beforeUploadWechatQr validates QR image files before upload. */
const beforeUploadWechatQr = (file: File) => {
const isImage = file.type.startsWith('image/')
const isLt10M = file.size / 1024 / 1024 < 10
if (!isImage) {
message.error('只能上传图片文件')
}
if (!isLt10M) {
message.error('图片大小不能超过 10MB')
}
return isImage && isLt10M
return isImage
}
/** handleWechatQrUpload uploads a QR image through admin object storage and stores the signed URL. */
const handleWechatQrUpload = async (options: any) => {
const { file, onSuccess, onError } = options
const handleWechatQrUpload: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
wechatQrUploading.value = true
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-user-wechat-qr',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
try {
const uploaded = await adminFileApi.uploadFile(file as File)
const { response: uploaded } = await task.promise
const signedUrl = await adminFileApi.getSignedUrl(uploaded.id)
formState.wechatQrCode = signedUrl as unknown as string
onSuccess?.(uploaded)
message.success('微信二维码上传成功')
} catch (error) {
console.error('微信二维码上传失败:', error)
message.error((error as Error)?.message || '微信二维码上传失败')
onError?.(error)
const errorMessage = (error as Error)?.message || '微信二维码上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('微信二维码上传失败:', error)
message.error(errorMessage)
onError?.(error as Error)
}
} finally {
wechatQrUploading.value = false
}
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'
import { join } from 'node:path'
const sourceRoot = join(process.cwd(), 'src')
const coreRoot = join(process.cwd(), '..', 'YumiNail-Core', 'src', 'main', 'java')
const coreRoot = join(process.cwd(), '..', 'FD-Core', 'src', 'main', 'java')
function readSource(relativePath: string) {
return readFileSync(join(sourceRoot, relativePath), 'utf-8')
@@ -68,7 +68,7 @@ describe('web theme governance', () => {
it('keeps frontend and backend platform overview permission allowlists aligned', () => {
const frontend = readSource('utils/platform-admin-permissions.ts')
const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'yuminailcore', 'support', 'PermissionCatalog.java'), 'utf-8')
const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'yuminailcore', 'modules', 'security', 'support', 'PermissionCatalog.java'), 'utf-8')
expect(backend).toContain('"security:audit:view"')
expect(frontend).toContain("'security:audit:view'")