功能:完善门店能力与用户安全配置

This commit is contained in:
xiaowang
2026-05-18 10:04:57 +08:00
parent 4563dd2538
commit 3797938616
356 changed files with 24983 additions and 1858 deletions
+185 -2
View File
@@ -14,17 +14,24 @@
</template>
<script setup lang="ts">
import { computed, onMounted, provide, ref, watch } from 'vue'
/**
* App page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, h, onMounted, provide, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ConfigProvider } from 'ant-design-vue'
import { ConfigProvider, Modal } from 'ant-design-vue'
import BottomNav from './components/BottomNav.vue'
import { cartApi } from './api/cart'
import { userApi, type SystemMessageVO } from './api/user'
import antdLocale from './config/antdv-locale'
const route = useRoute()
const router = useRouter()
/** routerReady is a reactive state variable used by the template and event handlers. */
const routerReady = ref(false)
/** isHiddenNav is a reactive state variable used by the template and event handlers. */
const isHiddenNav = computed(() => {
if (!routerReady.value) {
return true
@@ -38,9 +45,13 @@ const isHiddenNav = computed(() => {
})
// 全局购物车数量状态
/** cartCount is a reactive state variable used by the template and event handlers. */
const cartCount = ref(0)
/** checkingPopupMessages is a reactive state variable used by the template and event handlers. */
const checkingPopupMessages = ref(false)
// 加载购物车数量
/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartCount = async () => {
try {
// 检查用户是否已登录
@@ -61,10 +72,61 @@ const loadCartCount = async () => {
}
// 提供更新购物车数量的方法
/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const updateCartCount = async () => {
await loadCartCount()
}
/** showPopupMessage is a local helper used by this page script. */
const showPopupMessage = (item: SystemMessageVO) => {
return new Promise<void>((resolve) => {
let settled = false
/** markShownAndResolve is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const markShownAndResolve = async () => {
if (settled) {
return
}
settled = true
await userApi.markMessagePopupShown(item.id)
resolve()
}
Modal.info({
title: item.title,
content: h('div', { class: 'popup-message-body' }, [
item.content ? h('div', { class: 'popup-message-content' }, item.content) : null,
item.imageUrl ? h('img', { class: 'popup-message-image', src: item.imageUrl, alt: '消息图片' }) : null
]),
okText: '我知道了',
async onOk() {
await markShownAndResolve()
},
async afterClose() {
await markShownAndResolve()
}
})
})
}
/** checkPopupMessages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkPopupMessages = async () => {
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
const isAdminPage = route.matched.some(r => r.meta.isAdmin)
if (!token || isAdminPage || checkingPopupMessages.value) {
return
}
checkingPopupMessages.value = true
try {
const messages = await userApi.listMyPopupMessages()
for (const item of messages || []) {
await showPopupMessage(item)
}
} catch (error) {
console.error('加载待弹窗消息失败:', error)
} finally {
checkingPopupMessages.value = false
}
}
provide('updateCartCount', updateCartCount)
provide('cartCount', cartCount)
@@ -74,6 +136,7 @@ watch(() => route.path, async () => {
const isAdminPage = route.matched.some(r => r.meta.isAdmin)
if (!isAdminPage) {
await loadCartCount()
await checkPopupMessages()
}
})
@@ -83,6 +146,7 @@ loadCartCount()
onMounted(async () => {
await router.isReady()
routerReady.value = true
await checkPopupMessages()
})
</script>
@@ -112,4 +176,123 @@ onMounted(async () => {
.page-content.no-nav-padding {
padding-bottom: 0;
}
.yumi-date-picker-panel {
padding: 6px;
}
.yumi-date-picker-panel .ant-picker-panel-container {
overflow: hidden;
border-radius: 12px;
box-shadow: 0 18px 44px rgba(34, 40, 49, 0.18);
}
.yumi-date-picker-panel .ant-picker-panel {
border: 0;
}
.yumi-date-picker-panel .ant-picker-header {
padding: 8px 12px;
border-bottom-color: #eef1f5;
}
.yumi-date-picker-panel .ant-picker-header button {
min-width: 34px;
height: 34px;
border-radius: 8px;
}
.yumi-date-picker-panel .ant-picker-header-view {
line-height: 34px;
font-weight: 700;
}
.yumi-date-picker-panel .ant-picker-content th {
height: 34px;
color: #7b8494;
font-weight: 600;
}
.yumi-date-picker-panel .ant-picker-cell {
padding: 4px 0;
}
.yumi-date-picker-panel .ant-picker-cell-inner {
min-width: 34px;
height: 34px !important;
line-height: 34px !important;
border-radius: 8px !important;
transition: background .18s ease, color .18s ease, transform .18s ease;
}
.yumi-date-picker-panel .ant-picker-cell:hover .ant-picker-cell-inner {
background: #eef6ff;
transform: translateY(-1px);
}
.yumi-date-picker-panel .ant-picker-cell-selected .ant-picker-cell-inner,
.yumi-date-picker-panel .ant-picker-cell-range-start .ant-picker-cell-inner,
.yumi-date-picker-panel .ant-picker-cell-range-end .ant-picker-cell-inner {
background: #1677ff;
color: #fff;
font-weight: 700;
}
.yumi-date-picker-panel .ant-picker-footer {
border-top-color: #eef1f5;
}
.yumi-date-time-panel .ant-picker-time-panel,
.yumi-time-panel .ant-picker-time-panel {
min-width: 150px;
}
.yumi-date-time-panel .ant-picker-time-panel-column,
.yumi-time-panel .ant-picker-time-panel-column {
width: 76px;
padding: 8px 6px;
}
.yumi-date-time-panel .ant-picker-time-panel-cell-inner,
.yumi-time-panel .ant-picker-time-panel-cell-inner {
height: 34px !important;
line-height: 34px !important;
border-radius: 8px !important;
text-align: center;
}
.yumi-date-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner,
.yumi-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner {
background: #eef6ff;
color: #1677ff;
font-weight: 700;
}
.ant-picker {
border-radius: 8px;
}
.ant-picker-focused,
.ant-picker:hover {
border-color: #1677ff;
box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.12);
}
.popup-message-body {
display: grid;
gap: 12px;
}
.popup-message-content {
white-space: pre-wrap;
line-height: 1.8;
}
.popup-message-image {
width: 100%;
max-height: 360px;
object-fit: contain;
border-radius: 8px;
background: #fff7f8;
}
</style>
File diff suppressed because it is too large Load Diff
+93
View File
@@ -1,8 +1,13 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
export interface SendVerificationCodeRequest {
phone: string
sceneCode?: string
}
export interface LoginRequest {
@@ -10,12 +15,18 @@ export interface LoginRequest {
password: string
rememberMe?: boolean
shopId?: string | number
agreementAccepted?: boolean
agreementVersions?: Record<string, string>
clientType?: string
}
export interface PhoneLoginRequest {
phone: string
verificationCode: string
shopId?: string | number
agreementAccepted?: boolean
agreementVersions?: Record<string, string>
clientType?: string
}
export interface RegisterRequest {
@@ -23,8 +34,24 @@ export interface RegisterRequest {
password: string
nickname: string
shopId?: string | number
inviteCode?: string
phone?: string
verificationCode?: string
agreementAccepted?: boolean
agreementVersions?: Record<string, string>
clientType?: string
}
export interface LegalAgreement {
id: IdType
agreementType: 'USER_TERMS' | 'PRIVACY_POLICY'
agreementTypeName: string
title: string
version: string
content: string
status: number
statusText?: string
effectiveTime?: string
}
export interface LoginResponse {
@@ -42,6 +69,8 @@ export interface UserInfo {
type?: number
shopId?: IdType
shopName?: string
shopAuthorizationExpireTime?: string
shopAuthorizationExpired?: boolean
shopIds?: IdType[]
shopNames?: string[]
createTime: string
@@ -67,44 +96,108 @@ export interface SwitchShopRequest {
shopId?: string | number
}
/**
* authApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const authApi = {
/**
* `sendVerificationCode` 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.
* @param data: SendVerificationCodeRequest caller-supplied value for `data: SendVerificationCodeRequest`
*/
sendVerificationCode: (data: SendVerificationCodeRequest) => {
return api.post('/user/send-verification-code', data)
},
/**
* `login` 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.
* @param data: LoginRequest caller-supplied value for `data: LoginRequest`
*/
login: (data: LoginRequest) => {
return api.post<LoginResponse>('/user/login', data)
},
/**
* `phoneLogin` 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.
* @param data: PhoneLoginRequest caller-supplied value for `data: PhoneLoginRequest`
*/
phoneLogin: (data: PhoneLoginRequest) => {
return api.post<LoginResponse>('/user/phone-login', data)
},
/**
* `adminLogin` 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.
* @param data: LoginRequest caller-supplied value for `data: LoginRequest`
*/
adminLogin: (data: LoginRequest) => {
return api.post<LoginResponse>('/admin/auth/login', data)
},
/**
* `register` 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.
* @param data: RegisterRequest caller-supplied value for `data: RegisterRequest`
*/
register: (data: RegisterRequest) => {
return api.post('/user/register', data)
},
/**
* `refreshToken` 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.
* @param data: RefreshTokenRequest caller-supplied value for `data: RefreshTokenRequest`
*/
refreshToken: (data: RefreshTokenRequest) => {
return api.post<RefreshTokenResponse>('/user/refresh-token', data)
},
/**
* `logout` 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.
*/
logout: () => {
return api.post('/user/logout')
},
/**
* `switchShop` 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.
* @param data: SwitchShopRequest caller-supplied value for `data: SwitchShopRequest`
*/
switchShop: (data: SwitchShopRequest) => {
return api.post<LoginResponse>('/user/switch-shop', data)
},
/**
* `getUserInfo` 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.
*/
getUserInfo: () => {
return api.get<UserInfo>('/user/info')
},
/**
* `resetPasswordByPhone` 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.
* @param data: ResetPasswordRequest caller-supplied value for `data: ResetPasswordRequest`
*/
resetPasswordByPhone: (data: ResetPasswordRequest) => {
return api.post('/user/reset-password-by-phone', data)
}
}
export const legalAgreementApi = {
listCurrent: () => {
return api.get<LegalAgreement[]>('/legal-agreement/current')
},
getCurrent: (type: 'USER_TERMS' | 'PRIVACY_POLICY') => {
return api.get<LegalAgreement>(`/legal-agreement/current/${type}`)
},
getMyConsent: () => {
return api.get<{ consentVersions: Record<string, string> }>('/user/agreement-consent/me')
}
}
+36
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -6,33 +10,65 @@ interface CartItem {
quantity: number
}
/**
* cartApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const cartApi = {
// 添加作品到购物车
/**
* `addToCart` 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.
* @param item: CartItem caller-supplied value for `item: CartItem`
*/
addToCart: (item: CartItem) => {
return api.post('/cart/add', item)
},
// 从购物车移除作品
/**
* `removeFromCart` 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.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
removeFromCart: (productId: IdType) => {
return api.delete(`/cart/remove/${productId}`)
},
// 批量从购物车移除作品
/**
* `batchRemoveFromCart` 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.
* @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]`
*/
batchRemoveFromCart: (cartItemIds: IdType[]) => {
return api.post('/cart/batch-remove', cartItemIds)
},
// 更新购物车作品数量
/**
* `updateCartQuantity` 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.
* @param item: CartItem caller-supplied value for `item: CartItem`
*/
updateCartQuantity: (item: CartItem) => {
return api.put('/cart/update', item)
},
// 获取购物车列表
/**
* `getCartList` 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.
*/
getCartList: () => {
return api.get('/cart/list')
},
// 清空购物车
/**
* `clearCart` 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.
*/
clearCart: () => {
return api.delete('/cart/clear')
}
+23
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -18,13 +22,32 @@ export interface CommentVO {
replies?: CommentVO[]
}
/**
* commentApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const commentApi = {
/**
* `listByProduct` 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.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
listByProduct: (productId: IdType) => {
return api.get<CommentVO[]>(`/comment/list/product/${productId}`) as unknown as Promise<CommentVO[]>
},
/**
* `create` 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.
* @param data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string } caller-supplied value for `data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }`
*/
create: (data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }) => {
return api.post<IdType>('/comment/create', data) as unknown as Promise<IdType>
},
/**
* `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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
delete: (id: IdType) => {
return api.delete<boolean>(`/comment/delete/${id}`) as unknown as Promise<boolean>
}
+45
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import request from './index'
import type { IdType } from '@/utils/id'
@@ -74,8 +78,17 @@ export interface CouponListResponse {
size: number
}
/**
* couponApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const couponApi = {
// 创建优惠券
/**
* `createCoupon` 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.
* @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest`
*/
createCoupon: (data: CreateCouponRequest) => {
return request({
url: '/coupon/create',
@@ -85,6 +98,12 @@ export const couponApi = {
},
// 更新优惠券
/**
* `updateCoupon` 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.
* @param id: IdType caller-supplied value for `id: IdType`
* @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest`
*/
updateCoupon: (id: IdType, data: CreateCouponRequest) => {
return request({
url: `/coupon/update/${id}`,
@@ -94,6 +113,11 @@ export const couponApi = {
},
// 删除优惠券
/**
* `deleteCoupon` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
deleteCoupon: (id: IdType) => {
return request({
url: `/coupon/delete/${id}`,
@@ -102,6 +126,11 @@ export const couponApi = {
},
// 获取优惠券详情
/**
* `getCouponById` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
getCouponById: (id: IdType) => {
return request({
url: `/coupon/detail/${id}`,
@@ -110,6 +139,11 @@ export const couponApi = {
},
// 获取优惠券列表
/**
* `listCoupons` 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.
* @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }`
*/
listCoupons: (params: { page: number; size: number; shopId?: IdType }) => {
return request({
url: '/coupon/list',
@@ -119,6 +153,12 @@ export const couponApi = {
},
// 为用户分配优惠券
/**
* `assignCouponToUser` 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.
* @param userId: IdType caller-supplied value for `userId: IdType`
* @param couponId: IdType caller-supplied value for `couponId: IdType`
*/
assignCouponToUser: (userId: IdType, couponId: IdType) => {
return request({
url: '/coupon/assign',
@@ -137,6 +177,11 @@ export const couponApi = {
},
// 使用优惠券
/**
* `useCoupon` 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.
* @param userCouponId: IdType caller-supplied value for `userCouponId: IdType`
*/
useCoupon: (userCouponId: IdType) => {
return request({
url: '/coupon/use',
+34
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import type { AxiosProgressEvent } from 'axios'
import api from './index'
import type { IdType } from '@/utils/id'
@@ -17,7 +21,16 @@ export interface ChunkUploadSessionVO {
uploadedChunks: number[]
}
/**
* fileApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const fileApi = {
/**
* `uploadAvatar` 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.
* @param file: File caller-supplied value for `file: File`
*/
uploadAvatar: (file: File) => {
const formData = new FormData()
formData.append('file', file)
@@ -27,6 +40,11 @@ export const fileApi = {
}
})
},
/**
* `initAvatarChunkUpload` 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.
* @param data: ChunkUploadInitRequest caller-supplied value for `data: ChunkUploadInitRequest`
*/
initAvatarChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-avatar/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
@@ -47,13 +65,29 @@ export const fileApi = {
onUploadProgress: config?.onUploadProgress
})
},
/**
* `completeAvatarChunkUpload` 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.
* @param uploadId: string caller-supplied value for `uploadId: string`
*/
completeAvatarChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-avatar/complete', { uploadId }) as unknown as Promise<string>
},
/**
* `cancelAvatarChunkUpload` 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.
* @param uploadId: string caller-supplied value for `uploadId: string`
*/
cancelAvatarChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-avatar/${uploadId}`)
},
/**
* `getSignedUrl` 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.
* @param fileId: IdType caller-supplied value for `fileId: IdType`
* @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number`
*/
getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
params: { expiryTimeInMinutes }
+17
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { adminAuthApi } from './admin'
@@ -58,6 +62,8 @@ const isAuthFreePath = (url?: string) => {
'/user/phone-login',
'/user/wechat-mini/',
'/user/reset-password-by-phone',
'/legal-agreement/current',
'/api/legal-agreement/current',
'/product/get/',
'/product/list/',
'/comment/list/product/',
@@ -149,6 +155,7 @@ api.interceptors.response.use(
url?.includes('/user/refresh-token') ||
url?.includes('/user/send-verification-code') ||
url?.includes('/user/phone-login') ||
url?.includes('/legal-agreement/current') ||
url?.includes('/product/get/') ||
url?.includes('/product/list/') ||
url?.includes('/comment/list/product/') ||
@@ -235,7 +242,17 @@ api.interceptors.response.use(
}
)
/**
* fileApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const fileApi = {
/**
* `getSignedUrl` 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.
* @param fileId: IdType caller-supplied value for `fileId: IdType`
* @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number`
*/
getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
params: { expiryTimeInMinutes }
+77
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -14,8 +18,39 @@ interface CreateOrderRequest {
items: OrderItem[]
}
export interface ArtistCalendarAppointment {
orderId: IdType
orderNo: string
totalAmount?: number
actualAmount?: number
orderStatus: number
orderStatusText: string
orderItemId: IdType
productId: IdType
productTitle: string
artistId: IdType
artistName?: string
customerNickname?: string
customerPhoneMasked?: string
shopId?: IdType
shopName?: string
appointmentStartTime: string
appointmentEndTime: string
quantity: number
durationMinutes: number
}
/**
* orderApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const orderApi = {
// 创建订单
/**
* `createOrder` 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.
* @param data: CreateOrderRequest caller-supplied value for `data: CreateOrderRequest`
*/
createOrder: (data: CreateOrderRequest) => {
return api.post('/order/create', data)
},
@@ -26,21 +61,41 @@ export const orderApi = {
},
// 获取订单详情
/**
* `getOrderDetail` 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.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
*/
getOrderDetail: (orderId: IdType) => {
return api.get(`/order/detail/${orderId}`)
},
// 取消订单
/**
* `cancelOrder` 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.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
*/
cancelOrder: (orderId: IdType) => {
return api.put(`/order/cancel/${orderId}`)
},
// 后台获取所有订单
/**
* `getAllOrders` 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.
*/
getAllOrders: () => {
return api.get('/order/admin/list')
},
// 后台处理订单
/**
* `processOrder` 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.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
* @param status: number caller-supplied value for `status: number`
*/
processOrder: (orderId: IdType, status: number) => {
return api.put(`/order/admin/process/${orderId}`, {}, {
params: { status }
@@ -48,11 +103,33 @@ export const orderApi = {
},
// 美甲师查看自己的订单
/**
* `getArtistOrders` 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.
*/
getArtistOrders: () => {
return api.get('/order/artist/list')
},
// 预约日历:recent 取未来 7 天概览,day 传 yyyy-MM-dd 查某天明细。
/**
* `completeArtistOrder` 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.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
*/
completeArtistOrder: (orderId: IdType) => {
return api.put(`/order/artist/complete/${orderId}`)
},
getArtistCalendarRecent: async (days = 7): Promise<ArtistCalendarAppointment[]> => {
return await api.get<ArtistCalendarAppointment[]>('/order/artist/calendar/recent', {
params: { days }
}) as unknown as ArtistCalendarAppointment[]
},
getArtistCalendarDay: async (date: string): Promise<ArtistCalendarAppointment[]> => {
return await api.get<ArtistCalendarAppointment[]>('/order/artist/calendar/day', {
params: { date }
}) as unknown as ArtistCalendarAppointment[]
}
}
+44
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import { adminApi } from './admin'
import type { IdType } from '@/utils/id'
@@ -25,7 +29,16 @@ export interface UpdatePermissionRequest {
description?: string
}
/**
* permissionApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const permissionApi = {
/**
* `getUserPermissions` 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.
* @param userId?: IdType caller-supplied value for `userId?: IdType`
*/
getUserPermissions: (userId?: IdType) => {
if (userId) {
return adminApi.get<PermissionVO[]>(`/permission/user/${userId}`)
@@ -33,26 +46,57 @@ export const permissionApi = {
return adminApi.get<PermissionVO[]>('/permission/user/current')
},
/**
* `getAssignablePermissionIds` 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.
* @param userId: IdType caller-supplied value for `userId: IdType`
*/
getAssignablePermissionIds: (userId: IdType) => {
return adminApi.get<IdType[]>(`/permission/assignable/${userId}`)
},
/**
* `listAllPermissions` 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.
*/
listAllPermissions: () => {
return adminApi.get<PermissionVO[]>('/permission/list/all')
},
/**
* `createPermission` 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.
* @param data: CreatePermissionRequest caller-supplied value for `data: CreatePermissionRequest`
*/
createPermission: (data: CreatePermissionRequest) => {
return adminApi.post('/permission/create', data)
},
/**
* `updatePermission` 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.
* @param id: IdType caller-supplied value for `id: IdType`
* @param data: UpdatePermissionRequest caller-supplied value for `data: UpdatePermissionRequest`
*/
updatePermission: (id: IdType, data: UpdatePermissionRequest) => {
return adminApi.put(`/permission/update/${id}`, data)
},
/**
* `deletePermission` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
deletePermission: (id: IdType) => {
return adminApi.delete(`/permission/delete/${id}`)
},
/**
* `assignUserPermissions` 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.
* @param userId: IdType caller-supplied value for `userId: IdType`
* @param permissionIds: IdType[] caller-supplied value for `permissionIds: IdType[]`
*/
assignUserPermissions: (userId: IdType, permissionIds: IdType[]) => {
return adminApi.post(`/permission/assign/${userId}`, { permissionIds })
}
+8
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -65,6 +69,10 @@ export interface UpdateProductRequest {
shopId?: IdType | null
}
/**
* productApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const productApi = {
getAllProducts: async (): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>('/product/list/all') as unknown as ProductVO[]
+23
View File
@@ -1,11 +1,24 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* productLikeApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const productLikeApi = {
/**
* 点赞作品
* @param productId 作品ID
*/
/**
* `likeProduct` 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.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
likeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/like/${productId}`)
},
@@ -14,6 +27,11 @@ export const productLikeApi = {
* 取消点赞作品
* @param productId 作品ID
*/
/**
* `unlikeProduct` 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.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
unlikeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/unlike/${productId}`)
},
@@ -22,6 +40,11 @@ export const productLikeApi = {
* 检查用户是否已点赞作品
* @param productId 作品ID
*/
/**
* `checkLikeStatus` 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.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
checkLikeStatus: (productId: IdType) => {
return api.get<boolean>(`/product-like/check/${productId}`)
}
+17
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -6,8 +10,15 @@ export interface ShopVO {
shopName: string
description: string
address: string
mapProvider?: string
longitude?: number | string
latitude?: number | string
navigationUrls?: Record<string, string>
businessHours: string
status?: number
authorizationExpireTime?: string
authorizationExpired?: boolean
authorizationStatusText?: string
coverImageFileId?: string
coverImageUrls?: string[]
imageFileIds: string
@@ -36,6 +47,7 @@ export interface CreateShopRequest {
address: string
businessHours: string
status: number
authorizationExpireTime?: string
}
export interface UpdateShopRequest {
@@ -46,8 +58,13 @@ export interface UpdateShopRequest {
address?: string
businessHours?: string
status?: number
authorizationExpireTime?: string
}
/**
* shopApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const shopApi = {
getAllShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/all') as unknown as ShopVO[]
+33
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -18,23 +22,52 @@ export interface TagDTO {
borderColor: string
}
/**
* tagApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const tagApi = {
/**
* `getAllTags` 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.
*/
getAllTags: () => {
return api.get<TagVO[]>('/tag/list/all')
},
/**
* `getTagById` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
getTagById: (id: IdType) => {
return api.get<TagVO>(`/tag/get/${id}`)
},
/**
* `createTag` 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.
* @param data: TagDTO caller-supplied value for `data: TagDTO`
*/
createTag: (data: TagDTO) => {
return api.post<TagVO>('/tag/add', data)
},
/**
* `updateTag` 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.
* @param id: IdType caller-supplied value for `id: IdType`
* @param data: TagDTO caller-supplied value for `data: TagDTO`
*/
updateTag: (id: IdType, data: TagDTO) => {
return api.put<TagVO>(`/tag/update/${id}`, data)
},
/**
* `deleteTag` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
deleteTag: (id: IdType) => {
return api.delete(`/tag/delete/${id}`)
}
+223 -1
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { UserInfo } from './auth'
import type { IdType } from '@/utils/id'
@@ -19,6 +23,15 @@ export interface UserVO extends UserInfo {
updateTime: string
status: number
phone?: string
email?: string
maskedPhone?: string
maskedEmail?: string
shopRoleId?: IdType
shopRoleName?: string
parentUserId?: IdType
parentUserName?: string
parentUserTypeName?: string
relationSourceType?: string
}
export interface UpdateUserInfoRequest {
@@ -84,25 +97,160 @@ export interface LoginShopSelectionResponse {
}>
}
export interface UserRelationVO {
userId: IdType
shopId?: IdType
shopName?: string
parentUserId?: IdType
parentUserName?: string
parentRoleType?: number
parentRoleTypeName?: string
sourceType?: string
sourceTypeName?: string
}
// 用户端常用接口约定:
// - relation 表示当前用户的门店和直属上级归属;
// - announcement 只用于首页滚动公告,不进入消息通知历史;
// - system-message 才是站内消息,popup/read 分开记录。
export interface InviteCodeVO {
id: IdType
inviteCode: string
ownerUserId?: IdType
ownerUserName?: string
shopId?: IdType
shopName?: string
status?: number
useCount?: number
expireTime?: string
createTime?: string
}
export interface UpdatePhoneRequest {
oldPhone: string
newPhone: string
verificationCode: string
}
export interface UserAssetVO {
userId: IdType
nickname: string
balance: number
totalRechargeAmount: number
lastRechargeTime?: string
vipInfoId?: IdType
vipLevel: string
benefitId?: IdType
benefitInfo?: string
manualOverride?: boolean
vipStartTime?: string
vipExpireTime?: string
}
export interface BalanceHistoryItem {
id: IdType
userId: IdType
userNickname?: string
amount: number
type?: string
currentBalance?: number
beforeBalance?: number
afterBalance?: number
changeScene?: string
relatedOrderId?: IdType
relatedOrderNo?: string
externalOrderNo?: string
remark?: string
changeTime?: string
}
export interface SystemMessageVO {
id: IdType
title: string
content: string
imageFileId?: IdType
imageUrl?: string
publisherName?: string
targetType?: string
targetTypeName?: string
popupEnabled?: number
popupShown?: number
readStatus?: number
publishTime?: string
createTime?: string
}
export interface AnnouncementVO {
id: IdType
title: string
content: string
publisherName?: string
targetType?: string
status?: number
sortOrder?: number
publishTime?: string
}
export interface VipRechargePlanVO {
id: IdType
shopId: IdType
shopName?: string
title: string
rechargeAmount: number
giftAmount: number
vipLevel: string
description?: string
sortOrder?: number
status: number
}
export interface ContactInfoVO {
contactUserId?: IdType
contactName?: string
roleLabel?: string
phone?: string
phoneAvailable?: boolean
platformContactAvailable?: boolean
platformContactText?: string
}
/**
* userApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const userApi = {
getUserInfo: async (): Promise<UserVO> => {
return await api.get<UserVO>('/user/info') as unknown as UserVO
},
/**
* `updateUserInfo` 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.
* @param data: UpdateUserInfoRequest caller-supplied value for `data: UpdateUserInfoRequest`
*/
updateUserInfo: (data: UpdateUserInfoRequest) => {
return api.put('/user/update', data)
},
/**
* `updatePassword` 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.
* @param data: UpdatePasswordRequest caller-supplied value for `data: UpdatePasswordRequest`
*/
updatePassword: (data: UpdatePasswordRequest) => {
return api.put('/user/password', data)
},
/**
* `bindPhone` 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.
* @param data: BindPhoneRequest caller-supplied value for `data: BindPhoneRequest`
*/
bindPhone: (data: BindPhoneRequest) => {
return api.post('/user/bind-phone', data)
},
/**
* `updatePhone` 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.
* @param data: UpdatePhoneRequest caller-supplied value for `data: UpdatePhoneRequest`
*/
updatePhone: (data: UpdatePhoneRequest) => {
return api.put('/user/phone', data)
},
@@ -127,12 +275,86 @@ export const userApi = {
listUsersByType: async (type: number): Promise<UserVO[]> => {
return await api.get<UserVO[]>(`/user/list/type/${type}`) as unknown as UserVO[]
},
sendVerificationCode: (data: { phone: string }) => {
/**
* `sendVerificationCode` 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.
* @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }`
*/
sendVerificationCode: (data: { phone: string; sceneCode?: string }) => {
return api.post('/user/send-verification-code', data)
},
/**
* `switchShop` 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.
* @param shopId?: string | number caller-supplied value for `shopId?: string | number`
*/
switchShop: (shopId?: string | number) => {
return api.post('/user/switch-shop', { shopId })
},
getMyAsset: async (): Promise<UserAssetVO> => {
return await api.get<UserAssetVO>('/user/asset/me') as unknown as UserAssetVO
},
getMyBalanceHistory: async (): Promise<BalanceHistoryItem[]> => {
return await api.get<BalanceHistoryItem[]>('/user/balance/history/me') as unknown as BalanceHistoryItem[]
},
listMyMessages: async (): Promise<SystemMessageVO[]> => {
return await api.get<SystemMessageVO[]>('/system-message/my/list') as unknown as SystemMessageVO[]
},
listMyPopupMessages: async (): Promise<SystemMessageVO[]> => {
return await api.get<SystemMessageVO[]>('/system-message/my/popup') as unknown as SystemMessageVO[]
},
getMyUnreadMessageCount: async (): Promise<{ unreadCount: number }> => {
return await api.get<{ unreadCount: number }>('/system-message/my/unread-count') as unknown as { unreadCount: number }
},
getMyMessage: async (id: IdType): Promise<SystemMessageVO> => {
return await api.get<SystemMessageVO>(`/system-message/my/${id}`) as unknown as SystemMessageVO
},
/**
* `markMessagePopupShown` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
markMessagePopupShown: (id: IdType) => {
return api.put(`/system-message/my/${id}/popup-shown`, {})
},
/**
* `markMessageRead` 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.
* @param id: IdType caller-supplied value for `id: IdType`
*/
markMessageRead: (id: IdType) => {
return api.put(`/system-message/my/${id}/read`, {})
},
listMyAnnouncements: async (): Promise<AnnouncementVO[]> => {
return await api.get<AnnouncementVO[]>('/announcement/my/list') as unknown as AnnouncementVO[]
},
listMyVipRechargePlans: async (): Promise<VipRechargePlanVO[]> => {
return await api.get<VipRechargePlanVO[]>('/vip-recharge-plan/my/list') as unknown as VipRechargePlanVO[]
},
getMyRelation: async (): Promise<UserRelationVO> => {
return await api.get<UserRelationVO>('/user/relation/me') as unknown as UserRelationVO
},
// 注册页输入邀请码时先解析,给用户展示“将归属到谁/哪个店铺”。
resolveInviteCode: async (code: string): Promise<InviteCodeVO> => {
return await api.get<InviteCodeVO>('/user/invite-code/resolve', { params: { code } }) as unknown as InviteCodeVO
},
getShopManagerContact: async (shopId: IdType): Promise<ContactInfoVO> => {
return await api.get<ContactInfoVO>(`/contact-info/shop/${shopId}/manager`) as unknown as ContactInfoVO
},
getProductArtistContact: async (productId: IdType, artistId: IdType): Promise<ContactInfoVO> => {
return await api.get<ContactInfoVO>(`/contact-info/product/${productId}/artist/${artistId}`) as unknown as ContactInfoVO
},
getOrderArtistContact: async (orderId: IdType, artistId?: IdType): Promise<ContactInfoVO> => {
const params = artistId ? { artistId } : {}
return await api.get<ContactInfoVO>(`/contact-info/order/${orderId}/artist`, { params }) as unknown as ContactInfoVO
},
getPlatformContact: async (): Promise<ContactInfoVO> => {
return await api.get<ContactInfoVO>('/contact-info/platform') as unknown as ContactInfoVO
},
/**
* `deactivateAccount` 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.
*/
deactivateAccount: () => {
return api.delete('/user/deactivate')
}
+8
View File
@@ -1,3 +1,7 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
@@ -27,6 +31,10 @@ export interface WishlistItem {
}
}
/**
* wishlistApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const wishlistApi = {
addToWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add', { productId }) as unknown as boolean
@@ -45,6 +45,10 @@
</template>
<script setup lang="ts">
/**
* BottomNav page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, inject, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { HomeOutlined, ShoppingOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons-vue'
@@ -59,9 +63,11 @@ const cartCount = inject('cartCount', ref(0))
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
// 是否有未读通知
/** hasNotification is a reactive state variable used by the template and event handlers. */
const hasNotification = computed(() => true)
// 加载购物车数量
/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartCount = async () => {
// 这里我们不需要做任何事情,因为全局状态会自动更新
// 但我们仍然需要这个方法,因为 App.vue 会调用它
@@ -83,6 +89,7 @@ defineExpose({
})
// 根据当前路由判断激活的导航项
/** currentRoute is a reactive state variable used by the template and event handlers. */
const currentRoute = computed(() => {
if (!route || !route.path) return 'home'
const path = route.path
@@ -96,6 +103,7 @@ const currentRoute = computed(() => {
})
// 处理导航点击事件
/** handleNavClick is a local helper used by this page script. */
const handleNavClick = (tab: string) => {
if (tab === 'home') {
router.push('/home')
@@ -18,6 +18,10 @@
</template>
<script setup lang="ts">
/**
* DraftActions page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed } from 'vue'
const props = withDefaults(defineProps<{
@@ -35,6 +39,7 @@ defineEmits<{
(event: 'clear'): void
}>()
/** formattedSavedAt is a reactive state variable used by the template and event handlers. */
const formattedSavedAt = computed(() => {
if (!props.savedAt) {
return ''
@@ -8,6 +8,10 @@
</template>
<script setup lang="ts">
/**
* TableEllipsisText page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed } from 'vue'
const props = withDefaults(defineProps<{
@@ -19,6 +23,7 @@ const props = withDefaults(defineProps<{
emptyText: '--'
})
/** displayText is a reactive state variable used by the template and event handlers. */
const displayText = computed(() => {
if (props.text === undefined || props.text === null) {
return ''
@@ -27,6 +32,7 @@ const displayText = computed(() => {
return value
})
/** lineClass is a reactive state variable used by the template and event handlers. */
const lineClass = computed(() => {
return props.lines > 1 ? `lines-${props.lines}` : ''
})
@@ -14,6 +14,10 @@
</template>
<script setup lang="ts">
/**
* AdminMobileCardList page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
const props = withDefaults(defineProps<{
items?: any[]
emptyDescription?: string
@@ -24,6 +28,7 @@ const props = withDefaults(defineProps<{
itemKey: 'id'
})
/** resolveItemKey is a local helper used by this page script. */
const resolveItemKey = (item: Record<string, any> | undefined, index: number) => {
if (item && props.itemKey in item && item[props.itemKey] !== undefined) {
return item[props.itemKey]
@@ -12,6 +12,10 @@
</template>
<script setup lang="ts">
/**
* AdminMobileFab page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { PlusOutlined } from '@ant-design/icons-vue'
withDefaults(defineProps<{
@@ -20,6 +20,10 @@
</template>
<script setup lang="ts">
/**
* AdminResponsiveModal page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import type { CSSProperties } from 'vue'
import { computed } from 'vue'
import { useAdminViewport } from '@/composables/useAdminViewport'
@@ -43,7 +47,9 @@ const emit = defineEmits<{
const { isMobile } = useAdminViewport()
/** mergedWidth is a reactive state variable used by the template and event handlers. */
const mergedWidth = computed(() => (isMobile.value ? '100vw' : props.desktopWidth))
/** mergedStyle is a reactive state variable used by the template and event handlers. */
const mergedStyle = computed(() => (
isMobile.value
? {
@@ -53,6 +59,7 @@ const mergedStyle = computed(() => (
}
: undefined
))
/** mergedBodyStyle is a reactive state variable used by the template and event handlers. */
const mergedBodyStyle = computed(() => (
isMobile.value
? ({
@@ -63,15 +70,18 @@ const mergedBodyStyle = computed(() => (
: undefined
))
/** handleOpenChange is a local helper used by this page script. */
const handleOpenChange = (value: boolean) => {
emit('update:open', value)
}
/** handleCancel is a local helper used by this page script. */
const handleCancel = (event?: unknown) => {
emit('update:open', false)
emit('cancel', event)
}
/** handleOk is a local helper used by this page script. */
const handleOk = (event?: unknown) => {
emit('ok', event)
}
+48
View File
@@ -70,6 +70,12 @@ const router = createRouter({
component: () => import('../views/ArtistOrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
},
{
path: '/artist-calendar',
name: 'artist-calendar',
component: () => import('../views/ArtistCalendarView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
},
{
path: '/settings',
name: 'settings',
@@ -94,6 +100,18 @@ const router = createRouter({
component: () => import('../views/CouponView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/vip-center',
name: 'vip-center',
component: () => import('../views/VipCenterView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/notifications',
name: 'notifications',
component: () => import('../views/NotificationsView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/admin/login',
name: 'admin-login',
@@ -182,6 +200,36 @@ const router = createRouter({
name: 'admin-nail-artists',
component: () => import('../views/admin/NailArtistsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'nail_artist:view' }
},
{
path: 'messages',
name: 'admin-messages',
component: () => import('../views/admin/SystemMessagesView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'message:view' }
},
{
path: 'announcements',
name: 'admin-announcements',
component: () => import('../views/admin/AnnouncementsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'announcement:view' }
},
{
path: 'vip-recharge-plans',
name: 'admin-vip-recharge-plans',
component: () => import('../views/admin/VipRechargePlansView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:vip:manage' }
},
{
path: 'messagehub-push-configs',
name: 'admin-messagehub-push-configs',
component: () => import('../views/admin/MessageHubPushConfigsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'messagehub:config:manage' }
},
{
path: 'legal-agreements',
name: 'admin-legal-agreements',
component: () => import('../views/admin/LegalAgreementsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'legal_agreement:manage' }
}
]
},
@@ -67,6 +67,9 @@ export const hasAdminPermission = (permissionCode?: string) => {
export const resolveAdminLandingPath = () => {
const snapshot = getAdminBootstrapSnapshot()
if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) {
return '/admin'
}
if (snapshot.isBootstrapAdmin) {
return '/admin/shops'
}
@@ -77,6 +80,9 @@ export const resolveAdminLandingPath = () => {
export const canAccessAdminRoute = (path: string, permissionCode?: string) => {
const snapshot = getAdminBootstrapSnapshot()
if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) {
return path === '/admin' || path === '/admin/profile'
}
if (snapshot.isBootstrapAdmin) {
return path === '/admin' || path === '/admin/shops'
}
@@ -8,6 +8,8 @@ export interface AdminCachedUserInfo {
avatar?: string
shopId?: IdType
shopName?: string
shopAuthorizationExpireTime?: string
shopAuthorizationExpired?: boolean
shopIds?: IdType[]
shopNames?: string[]
}
@@ -174,6 +174,10 @@
</template>
<script setup lang="ts">
/**
* AccountSettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, RightOutlined, LockOutlined, PhoneOutlined } from '@ant-design/icons-vue'
@@ -199,11 +203,15 @@ const userInfo = ref<UserVO>({
})
// 状态标识
/** hasPassword is a reactive state variable used by the template and event handlers. */
const hasPassword = ref(false)
/** hasPhone is a reactive state variable used by the template and event handlers. */
const hasPhone = ref(false)
// 绑定手机号表单
/** bindPhoneModalVisible is a reactive state variable used by the template and event handlers. */
const bindPhoneModalVisible = ref(false)
/** bindPhoneLoading is a reactive state variable used by the template and event handlers. */
const bindPhoneLoading = ref(false)
const bindPhoneDraftSavedAt = ref<number | null>(null)
const bindPhoneForm = reactive({
@@ -212,7 +220,9 @@ const bindPhoneForm = reactive({
})
// 修改手机号表单
/** changePhoneModalVisible is a reactive state variable used by the template and event handlers. */
const changePhoneModalVisible = ref(false)
/** changePhoneLoading is a reactive state variable used by the template and event handlers. */
const changePhoneLoading = ref(false)
const changePhoneDraftSavedAt = ref<number | null>(null)
const changePhoneForm = reactive({
@@ -221,7 +231,9 @@ const changePhoneForm = reactive({
})
// 修改密码表单
/** changePasswordModalVisible is a reactive state variable used by the template and event handlers. */
const changePasswordModalVisible = ref(false)
/** changePasswordLoading is a reactive state variable used by the template and event handlers. */
const changePasswordLoading = ref(false)
const changePasswordDraftSavedAt = ref<number | null>(null)
const changePasswordForm = reactive({
@@ -247,6 +259,7 @@ const saveSessionDraft = <T>(key: string, payload: T, savedAtRef: typeof bindPho
message.success(successMessage)
}
/** clearSessionDraft is a local helper used by this page script. */
const clearSessionDraft = (key: string, savedAtRef: typeof bindPhoneDraftSavedAt, showMessage = true) => {
clearDraftRecord(key, 'session')
savedAtRef.value = null
@@ -259,34 +272,42 @@ const bindPhoneDraftKey = buildDraftStorageKey('account-settings', 'bind-phone')
const changePhoneDraftKey = buildDraftStorageKey('account-settings', 'change-phone')
const changePasswordDraftKey = buildDraftStorageKey('account-settings', 'change-password')
/** handleSaveBindPhoneDraft is a local helper used by this page script. */
const handleSaveBindPhoneDraft = () => {
saveSessionDraft(bindPhoneDraftKey, { ...bindPhoneForm }, bindPhoneDraftSavedAt)
}
/** handleClearBindPhoneDraft is a local helper used by this page script. */
const handleClearBindPhoneDraft = (showMessage = true) => {
clearSessionDraft(bindPhoneDraftKey, bindPhoneDraftSavedAt, showMessage)
}
/** handleSaveChangePhoneDraft is a local helper used by this page script. */
const handleSaveChangePhoneDraft = () => {
saveSessionDraft(changePhoneDraftKey, { ...changePhoneForm }, changePhoneDraftSavedAt)
}
/** handleClearChangePhoneDraft is a local helper used by this page script. */
const handleClearChangePhoneDraft = (showMessage = true) => {
clearSessionDraft(changePhoneDraftKey, changePhoneDraftSavedAt, showMessage)
}
/** handleSaveChangePasswordDraft is a local helper used by this page script. */
const handleSaveChangePasswordDraft = () => {
saveSessionDraft(changePasswordDraftKey, { ...changePasswordForm }, changePasswordDraftSavedAt)
}
/** handleClearChangePasswordDraft is a local helper used by this page script. */
const handleClearChangePasswordDraft = (showMessage = true) => {
clearSessionDraft(changePasswordDraftKey, changePasswordDraftSavedAt, showMessage)
}
// 倒计时
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
// 账号设置选项
/** accountSettings is a reactive state variable used by the template and event handlers. */
const accountSettings = ref([
{
key: 'changePhone',
@@ -309,6 +330,7 @@ const accountSettings = ref([
])
// 根据用户状态动态更新账号设置选项
/** updateAccountSettings is a local helper used by this page script. */
const updateAccountSettings = () => {
const settings = []
@@ -358,6 +380,7 @@ const updateAccountSettings = () => {
}
// 获取用户信息
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const response = await userApi.getUserInfo() as any
@@ -375,11 +398,13 @@ const fetchUserInfo = async () => {
}
// 处理返回
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
// 处理设置项点击
/** handleSettingClick is a local helper used by this page script. */
const handleSettingClick = (key: string) => {
switch (key) {
case 'bindPhone':
@@ -406,11 +431,13 @@ const handleSettingClick = (key: string) => {
}
// 处理设置密码
/** handleSetPassword is a local helper used by this page script. */
const handleSetPassword = () => {
router.push('/settings/password')
}
// 发送绑定手机号验证码
/** handleSendVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendVerificationCode = async () => {
if (!bindPhoneForm.phone) {
message.error('请输入手机号')
@@ -424,7 +451,10 @@ const handleSendVerificationCode = async () => {
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: bindPhoneForm.phone }))
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: bindPhoneForm.phone,
sceneCode: 'USER_BIND_PHONE_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error) {
@@ -434,6 +464,7 @@ const handleSendVerificationCode = async () => {
}
// 发送修改手机号验证码
/** handleSendChangePhoneVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendChangePhoneVerificationCode = async () => {
if (!changePhoneForm.newPhone) {
message.error('请输入新手机号')
@@ -447,7 +478,10 @@ const handleSendChangePhoneVerificationCode = async () => {
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: changePhoneForm.newPhone }))
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: changePhoneForm.newPhone,
sceneCode: 'USER_CHANGE_PHONE_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error) {
@@ -457,6 +491,7 @@ const handleSendChangePhoneVerificationCode = async () => {
}
// 发送修改密码验证码
/** handleSendChangePasswordVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendChangePasswordVerificationCode = async () => {
if (!userInfo.value.phone) {
message.error('请先绑定手机号')
@@ -471,7 +506,10 @@ const handleSendChangePasswordVerificationCode = async () => {
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone }))
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error) {
@@ -481,6 +519,7 @@ const handleSendChangePasswordVerificationCode = async () => {
}
// 开始倒计时
/** startCountdown is a local helper used by this page script. */
const startCountdown = () => {
countdown.value = 60
const timer = setInterval(() => {
@@ -492,6 +531,7 @@ const startCountdown = () => {
}
// 处理绑定手机号提交
/** handleBindPhoneSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBindPhoneSubmit = async () => {
if (!bindPhoneForm.phone || !bindPhoneForm.verificationCode) {
message.error('请填写完整信息')
@@ -519,6 +559,7 @@ const handleBindPhoneSubmit = async () => {
}
// 处理绑定手机号取消
/** handleBindPhoneCancel is a local helper used by this page script. */
const handleBindPhoneCancel = () => {
bindPhoneModalVisible.value = false
bindPhoneForm.phone = ''
@@ -526,6 +567,7 @@ const handleBindPhoneCancel = () => {
}
// 处理修改手机号提交
/** handleChangePhoneSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleChangePhoneSubmit = async () => {
if (!changePhoneForm.newPhone || !changePhoneForm.verificationCode) {
message.error('请填写完整信息')
@@ -554,6 +596,7 @@ const handleChangePhoneSubmit = async () => {
}
// 处理修改手机号取消
/** handleChangePhoneCancel is a local helper used by this page script. */
const handleChangePhoneCancel = () => {
changePhoneModalVisible.value = false
changePhoneForm.newPhone = ''
@@ -561,6 +604,7 @@ const handleChangePhoneCancel = () => {
}
// 处理修改密码提交
/** handleChangePasswordSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleChangePasswordSubmit = async () => {
if (!changePasswordForm.verificationCode || !changePasswordForm.password || !changePasswordForm.confirmPassword) {
message.error('请填写完整信息')
@@ -594,6 +638,7 @@ const handleChangePasswordSubmit = async () => {
}
// 处理修改密码取消
/** handleChangePasswordCancel is a local helper used by this page script. */
const handleChangePasswordCancel = () => {
changePasswordModalVisible.value = false
changePasswordForm.verificationCode = ''
@@ -602,6 +647,7 @@ const handleChangePasswordCancel = () => {
}
// 处理注销账号
/** handleDeactivateAccount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDeactivateAccount = async () => {
Modal.confirm({
title: '确认注销账号',
@@ -0,0 +1,264 @@
<template>
<div class="artist-calendar-page">
<header class="calendar-header">
<a-button type="text" class="back-btn" @click="router.back()">
<LeftOutlined />
</a-button>
<div class="header-copy">
<span>预约日历</span>
<h1>未来 7 天</h1>
</div>
<a-button type="link" @click="openArtistOrders">订单</a-button>
</header>
<main class="calendar-content">
<section class="summary-strip">
<div>
<span>今日预约</span>
<strong>{{ todayCount }}</strong>
</div>
<div>
<span>下一单</span>
<strong>{{ nextAppointmentText }}</strong>
</div>
<div>
<span>7 天合计</span>
<strong>{{ appointments.length }}</strong>
</div>
</section>
<section class="toolbar">
<a-button type="primary" :loading="loading" @click="loadAppointments">刷新</a-button>
<a-button @click="openArtistOrders">查看我的相关订单</a-button>
</section>
<a-spin :spinning="loading">
<section v-if="groupedDays.length" class="timeline">
<article v-for="day in groupedDays" :key="day.dateKey" class="day-row">
<aside class="day-label">
<strong>{{ day.dayText }}</strong>
<span>{{ day.weekText }}</span>
<em>{{ day.items.length }} 单</em>
</aside>
<div class="day-line">
<button
v-for="item in day.items"
:key="String(item.orderItemId)"
type="button"
class="appointment-block"
:class="statusClass(item.orderStatus)"
@click="openDetail(item)"
>
<span class="time">{{ timeRange(item) }}</span>
<strong>{{ item.customerNickname || '用户' }} · {{ item.productTitle }}</strong>
<small>{{ item.orderStatusText }} · {{ item.shopName || '门店' }}</small>
</button>
</div>
</article>
</section>
<a-empty v-else description="未来 7 天暂无预约" />
</a-spin>
</main>
<a-drawer v-model:open="detailOpen" title="预约详情" placement="right" :width="420">
<div v-if="selected" class="detail-body">
<div class="detail-title">
<strong>{{ selected.productTitle }}</strong>
<a-tag :color="selected.orderStatus === 2 ? 'green' : 'orange'">{{ selected.orderStatusText }}</a-tag>
</div>
<dl>
<dt>预约时间</dt>
<dd>{{ formatDateTime(selected.appointmentStartTime) }} - {{ formatClock(selected.appointmentEndTime) }}</dd>
<dt>客户</dt>
<dd>{{ selected.customerNickname || '用户' }} {{ selected.customerPhoneMasked || '' }}</dd>
<dt>订单号</dt>
<dd>{{ selected.orderNo }}</dd>
<dt>订单金额</dt>
<dd>{{ formatMoney(selected.totalAmount) }} / 实付 {{ formatMoney(selected.actualAmount) }}</dd>
<dt>门店</dt>
<dd>{{ selected.shopName || '--' }}</dd>
<dt>数量 / 时长</dt>
<dd>{{ selected.quantity }} 件 · {{ selected.durationMinutes }} 分钟</dd>
</dl>
<a-space direction="vertical" style="width: 100%">
<a-button block @click="openSelectedProduct">查看客户选择的作品</a-button>
<a-button block @click="openSelectedOrder">查看对应订单</a-button>
<a-button
v-if="selected.orderStatus === 1"
type="primary"
block
:loading="completing"
@click="completeSelectedOrder"
>
完成服务
</a-button>
<a-button block @click="openArtistOrders">打开我的相关订单</a-button>
</a-space>
</div>
</a-drawer>
</div>
</template>
<script setup lang="ts">
/**
* ArtistCalendarView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { orderApi, type ArtistCalendarAppointment } from '@/api/order'
import { runWithGlobalLoading } from '@/utils/action-loading'
const router = useRouter()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** completing is a reactive state variable used by the template and event handlers. */
const completing = ref(false)
const appointments = ref<ArtistCalendarAppointment[]>([])
const selected = ref<ArtistCalendarAppointment | null>(null)
/** detailOpen is a reactive state variable used by the template and event handlers. */
const detailOpen = ref(false)
const todayKey = localDateKey(new Date())
/** todayCount is a reactive state variable used by the template and event handlers. */
const todayCount = computed(() => appointments.value.filter(item => dateKey(item.appointmentStartTime) === todayKey).length)
/** nextAppointmentText is a reactive state variable used by the template and event handlers. */
const nextAppointmentText = computed(() => {
const now = Date.now()
const next = appointments.value.find(item => new Date(item.appointmentStartTime).getTime() >= now)
return next ? formatClock(next.appointmentStartTime) : '--'
})
/** groupedDays is a reactive state variable used by the template and event handlers. */
const groupedDays = computed(() => {
const map = new Map<string, ArtistCalendarAppointment[]>()
appointments.value.forEach(item => {
const key = dateKey(item.appointmentStartTime)
map.set(key, [...(map.get(key) || []), item])
})
return Array.from(map.entries()).map(([key, items]) => ({
dateKey: key,
dayText: key.slice(5),
weekText: weekText(key),
items: items.sort((a, b) => a.appointmentStartTime.localeCompare(b.appointmentStartTime))
}))
})
/** loadAppointments is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadAppointments = async () => {
loading.value = true
try {
appointments.value = await orderApi.getArtistCalendarRecent(7)
} catch (error: any) {
message.error(error?.message || '获取预约日历失败')
} finally {
loading.value = false
}
}
/** openDetail is a local helper used by this page script. */
const openDetail = (item: ArtistCalendarAppointment) => {
selected.value = item
detailOpen.value = true
}
/** completeSelectedOrder is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const completeSelectedOrder = async () => {
if (!selected.value) return
completing.value = true
try {
await runWithGlobalLoading(() => orderApi.completeArtistOrder(selected.value!.orderId))
message.success('服务已完成')
detailOpen.value = false
await loadAppointments()
} catch (error: any) {
message.error(error?.message || '完成服务失败')
} finally {
completing.value = false
}
}
/** openSelectedProduct is a local helper used by this page script. */
const openSelectedProduct = () => {
if (!selected.value?.productId) return
const productId = selected.value.productId
detailOpen.value = false
router.push(`/product/${productId}`)
}
/** openArtistOrders is a local helper used by this page script. */
const openArtistOrders = () => {
detailOpen.value = false
router.push({ path: '/artist-orders' })
}
/** openSelectedOrder is a local helper used by this page script. */
const openSelectedOrder = () => {
if (!selected.value?.orderId) return
const orderId = selected.value.orderId
detailOpen.value = false
router.push({ path: '/artist-orders', query: { orderId: String(orderId) } })
}
/** dateKey is a local helper used by this page script. */
const dateKey = (value: string) => value ? value.slice(0, 10) : ''
function localDateKey(value: Date) {
const month = String(value.getMonth() + 1).padStart(2, '0')
const day = String(value.getDate()).padStart(2, '0')
return `${value.getFullYear()}-${month}-${day}`
}
/** formatDateTime is a local helper used by this page script. */
const formatDateTime = (value: string) => value ? value.replace('T', ' ').slice(0, 16) : '--'
/** formatClock is a local helper used by this page script. */
const formatClock = (value: string) => value ? value.replace('T', ' ').slice(11, 16) : '--'
/** formatMoney is a local helper used by this page script. */
const formatMoney = (value?: number) => value === undefined || value === null ? '--' : `¥${Number(value).toFixed(2)}`
/** timeRange is a local helper used by this page script. */
const timeRange = (item: ArtistCalendarAppointment) => `${formatClock(item.appointmentStartTime)} - ${formatClock(item.appointmentEndTime)}`
/** weekText is a local helper used by this page script. */
const weekText = (key: string) => ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][new Date(`${key}T00:00:00`).getDay()] || ''
/** statusClass is a local helper used by this page script. */
const statusClass = (status: number) => status === 2 ? 'is-completed' : 'is-pending'
onMounted(loadAppointments)
</script>
<style scoped>
.artist-calendar-page { min-height: 100vh; background: #f7f4f0; color: #2b2724; }
.calendar-header { position: sticky; top: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; background: rgba(255,255,255,.94); border-bottom: 1px solid #eee2d6; backdrop-filter: blur(12px); }
.back-btn { width: 40px; height: 40px; }
.header-copy { flex: 1; min-width: 0; }
.header-copy span { display: block; font-size: 12px; color: #8b7c72; }
.header-copy h1 { margin: 2px 0 0; font-size: 20px; }
.calendar-content { max-width: 1040px; margin: 0 auto; padding: 18px 16px 96px; }
.summary-strip { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; overflow: hidden; border-radius: 8px; background: #e7dbd1; }
.summary-strip div { padding: 16px; background: #fff; }
.summary-strip span { display: block; color: #8b7c72; font-size: 12px; }
.summary-strip strong { display: block; margin-top: 8px; font-size: 22px; }
.toolbar { display: flex; justify-content: space-between; gap: 12px; margin: 16px 0; }
.timeline { display: grid; gap: 14px; }
.day-row { display: grid; grid-template-columns: 92px minmax(0, 1fr); gap: 14px; }
.day-label { display: grid; align-content: start; gap: 4px; padding-top: 4px; }
.day-label strong { font-size: 20px; }
.day-label span, .day-label em { color: #8b7c72; font-style: normal; font-size: 12px; }
.day-line { position: relative; display: grid; gap: 10px; padding-left: 18px; border-left: 2px solid #e6d7ca; }
.appointment-block { width: 100%; display: grid; gap: 5px; padding: 14px 16px; border: 1px solid #efd7bd; border-radius: 8px; background: #fffaf5; text-align: left; color: #2b2724; box-shadow: 0 10px 22px rgba(120, 82, 58, 0.08); cursor: pointer; transition: transform .18s ease, border-color .18s ease; }
.appointment-block:hover { transform: translateY(-2px); border-color: #d9955d; }
.appointment-block.is-completed { background: #f5fff7; border-color: #c8ead1; }
.appointment-block .time { color: #b35c28; font-weight: 700; }
.appointment-block small { color: #7b7068; }
.detail-body { display: grid; gap: 18px; }
.detail-title { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.detail-title strong { font-size: 20px; }
dl { display: grid; gap: 10px; margin: 0; }
dt { color: #8b7c72; font-size: 12px; }
dd { margin: -6px 0 4px; color: #2b2724; font-weight: 600; }
@media (max-width: 720px) {
.summary-strip { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.summary-strip div { min-width: 0; padding: 12px 10px; }
.summary-strip strong { font-size: 18px; }
.day-row { grid-template-columns: 1fr; gap: 8px; }
.day-label { grid-template-columns: auto auto 1fr; align-items: baseline; }
}
</style>
+147 -6
View File
@@ -5,17 +5,58 @@
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>美甲师订单</h1>
<div class="placeholder" />
<a-button type="link" @click="router.push('/artist-calendar')">日历</a-button>
</header>
<main class="content">
<section v-if="orders.length" class="filter-panel">
<a-input v-model:value="filters.keyword" allow-clear placeholder="搜索订单号、客户、作品" />
<div class="filter-row">
<a-select v-model:value="filters.source" class="filter-select" placeholder="订单来源">
<a-select-option value="all">全部来源</a-select-option>
<a-select-option value="SERVICE">客户预约我的订单</a-select-option>
<a-select-option value="SELF">我下的订单</a-select-option>
<a-select-option value="BOTH">两者都有</a-select-option>
</a-select>
<a-select v-model:value="filters.status" class="filter-select" placeholder="订单状态">
<a-select-option value="all">全部状态</a-select-option>
<a-select-option :value="1">待使用</a-select-option>
<a-select-option :value="2">已完成</a-select-option>
<a-select-option :value="3">已取消</a-select-option>
</a-select>
</div>
<div class="filter-row">
<a-date-picker v-model:value="filters.date" class="filter-date" popup-class-name="yumi-date-picker-panel" placeholder="预约日期" />
<a-input-number v-model:value="filters.minAmount" class="filter-number" :min="0" placeholder="最低金额" />
<a-input-number v-model:value="filters.maxAmount" class="filter-number" :min="0" placeholder="最高金额" />
</div>
<div class="filter-actions">
<span>共 {{ filteredOrders.length }} / {{ orders.length }} 个订单</span>
<a-button @click="resetFilters">重置</a-button>
</div>
</section>
<a-empty v-if="!orders.length" description="暂无订单">
<a-button type="primary" @click="handleRefreshClick">刷新</a-button>
</a-empty>
<a-empty v-else-if="!filteredOrders.length" description="没有符合条件的订单">
<a-button @click="resetFilters">清空筛选</a-button>
</a-empty>
<a-card v-for="order in orders" :key="order.id" class="order-card">
<a-card
v-for="order in filteredOrders"
:key="order.id"
:ref="el => setOrderRef(order.id, el)"
class="order-card"
:class="{ 'is-target': isTargetOrder(order.id) }"
>
<div class="order-head">
<span>订单号:{{ order.orderNo }}</span>
<div class="order-title">
<span>订单号:{{ order.orderNo }}</span>
<span v-if="order.artistOrderSourceText" class="source-tag" :class="sourceClass(order.artistOrderSource)">
{{ order.artistOrderSourceText }}
</span>
</div>
<span class="status" :class="statusClass(order.status)">{{ order.statusText }}</span>
</div>
@@ -38,7 +79,7 @@
<div class="footer">
<span>当前项目合计:¥{{ order.actualAmount.toFixed(2) }}</span>
<a-button v-if="order.status === 1" size="small" type="primary" @click="completeOrder(order.id)">
<a-button v-if="canComplete(order)" size="small" type="primary" @click="completeOrder(order.id)">
完成服务
</a-button>
</div>
@@ -48,8 +89,12 @@
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
/**
* ArtistOrderView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { fileApi } from '../api/index'
@@ -58,15 +103,98 @@ import type { IdType } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
const router = useRouter()
const route = useRoute()
const orders = ref<any[]>([])
const imageIdCache = ref<Record<string, string>>({})
const orderRefs = ref<Record<string, any>>({})
const filters = reactive({
keyword: '',
source: 'all',
status: 'all' as 'all' | number,
date: null as any,
minAmount: undefined as number | undefined,
maxAmount: undefined as number | undefined
})
/** filteredOrders is a reactive state variable used by the template and event handlers. */
const filteredOrders = computed(() => {
const keyword = filters.keyword.trim().toLowerCase()
const targetDate = filters.date?.format?.('YYYY-MM-DD')
return orders.value.filter(order => {
if (filters.source !== 'all' && order.artistOrderSource !== filters.source) return false
if (filters.status !== 'all' && order.status !== filters.status) return false
const amount = Number(order.actualAmount || 0)
if (filters.minAmount !== undefined && amount < filters.minAmount) return false
if (filters.maxAmount !== undefined && amount > filters.maxAmount) return false
const items = order.items || []
if (targetDate && !items.some((item: any) => String(item.appointmentTime || '').slice(0, 10) === targetDate)) {
return false
}
if (keyword) {
const haystack = [
order.orderNo,
order.statusText,
order.artistOrderSourceText,
order.customerNickname,
order.customerPhoneMasked,
...items.flatMap((item: any) => [item.productTitle, item.appointmentTime])
].filter(Boolean).join(' ').toLowerCase()
if (!haystack.includes(keyword)) return false
}
return true
})
})
/** targetOrderId is a local helper used by this page script. */
const targetOrderId = () => String(route.query.orderId || '')
/** isTargetOrder is a local helper used by this page script. */
const isTargetOrder = (orderId: IdType) => targetOrderId() === String(orderId)
/** setOrderRef is a local helper used by this page script. */
const setOrderRef = (orderId: IdType, el: any) => {
if (!el) return
orderRefs.value[String(orderId)] = el
}
/** scrollToTargetOrder is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const scrollToTargetOrder = async () => {
const id = targetOrderId()
if (!id) return
await nextTick()
const target = orderRefs.value[id]?.$el || orderRefs.value[id]
target?.scrollIntoView?.({ behavior: 'smooth', block: 'center' })
}
/** statusClass is a local helper used by this page script. */
const statusClass = (status: number) => {
if (status === 1) return 'pending'
if (status === 2) return 'completed'
return 'cancelled'
}
/** sourceClass is a local helper used by this page script. */
const sourceClass = (source?: string) => {
if (source === 'SELF') return 'source-self'
if (source === 'BOTH') return 'source-both'
return 'source-service'
}
/** canComplete is a local helper used by this page script. */
const canComplete = (order: any) => {
return order.status === 1 && order.artistOrderSource !== 'SELF'
}
/** resetFilters is a local helper used by this page script. */
const resetFilters = () => {
filters.keyword = ''
filters.source = 'all'
filters.status = 'all'
filters.date = null
filters.minAmount = undefined
filters.maxAmount = undefined
}
/** loadOrders is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadOrders = async () => {
try {
orders.value = (await orderApi.getArtistOrders() as unknown as any[]) || []
@@ -83,15 +211,18 @@ const loadOrders = async () => {
}
}
}
await scrollToTargetOrder()
} catch {
message.error('获取订单列表失败')
}
}
/** handleRefreshClick is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRefreshClick = async () => {
await runWithGlobalLoading(() => loadOrders())
}
/** completeOrder is a local helper used by this page script. */
const completeOrder = (orderId: IdType) => {
Modal.confirm({
title: '确认完成服务',
@@ -119,9 +250,19 @@ onMounted(loadOrders)
.header h1 { margin: 0; font-size: 18px; }
.placeholder { width: 40px; height: 40px; }
.content { padding: 15px; }
.filter-panel { display: grid; gap: 10px; margin-bottom: 12px; padding: 12px; border-radius: 8px; background: #fff; }
.filter-row { display: flex; gap: 8px; align-items: center; }
.filter-select, .filter-date, .filter-number { flex: 1; min-width: 0; }
.filter-actions { display: flex; align-items: center; justify-content: space-between; color: #888; font-size: 12px; }
.order-card { margin-bottom: 12px; border-radius: 12px; }
.order-card.is-target { border-color: #d9955d; box-shadow: 0 0 0 2px rgba(217, 149, 93, .22); }
.order-head, .footer { display: flex; align-items: center; justify-content: space-between; }
.order-head { margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0; }
.order-title { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.source-tag { padding: 3px 8px; border-radius: 999px; font-size: 12px; font-weight: 600; }
.source-service { background: #e6f4ff; color: #1677ff; }
.source-self { background: #f9f0ff; color: #722ed1; }
.source-both { background: #fff7e6; color: #d46b08; }
.customer-meta { display: flex; flex-wrap: wrap; gap: 8px 16px; margin-bottom: 12px; color: #666; font-size: 13px; }
.status { padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
.pending { background: #fff7e6; color: #fa8c16; }
+150 -6
View File
@@ -245,6 +245,14 @@
</a-input-password>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="inviteCode" label="邀请码">
<a-input
v-model:value="formData.inviteCode"
placeholder="可不填,不填默认归属所选店铺店长"
size="large"
/>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="shopId" label="选择店铺">
<a-select
v-model:value="formData.shopId"
@@ -276,6 +284,15 @@
</div>
</a-form-item>
<a-form-item style="margin-bottom: 12px">
<a-checkbox v-model:checked="agreementAccepted">
我已阅读并同意
<a @click.stop.prevent="openAgreement('USER_TERMS')">《用户协议》</a>
和
<a @click.stop.prevent="openAgreement('PRIVACY_POLICY')">《隐私政策》</a>
</a-checkbox>
</a-form-item>
<a-form-item>
<a-button
type="primary"
@@ -283,6 +300,7 @@
size="large"
block
:loading="loading"
:disabled="!agreementAccepted"
>
{{ activeTab === 'login' ? '登录' : '注册' }}
</a-button>
@@ -380,16 +398,32 @@
</a-form-item>
</a-form>
</a-modal>
<a-modal
v-model:open="agreementModalOpen"
:title="selectedAgreement?.title || '协议内容'"
:footer="null"
width="90%"
>
<div class="agreement-content">
<div class="agreement-version">版本:{{ selectedAgreement?.version || '--' }}</div>
<pre>{{ selectedAgreement?.content || '暂无协议内容' }}</pre>
</div>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* AuthView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { InfoCircleOutlined, LockOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { authApi } from '@/api/auth'
import { authApi, legalAgreementApi, type LegalAgreement } from '@/api/auth'
import { shopApi } from '@/api/shop'
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
import { runWithGlobalLoading } from '@/utils/action-loading'
@@ -405,20 +439,32 @@ const router = useRouter()
const activeTab = ref<'login' | 'register'>('login')
const loginType = ref<'password' | 'phone'>('password')
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
const shops = ref<any[]>([])
const loginShops = ref<Array<{ id: IdType; shopName: string }>>([])
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
const loginAccountStatus = ref<LoginAccountCheckResponse | null>(null)
const registerAccountStatus = ref<AvailabilityCheckResponse | null>(null)
const registerPhoneStatus = ref<AvailabilityCheckResponse | null>(null)
/** loginShopMessage is a reactive state variable used by the template and event handlers. */
const loginShopMessage = ref('')
/** allowLoginShopless is a reactive state variable used by the template and event handlers. */
const allowLoginShopless = ref(false)
/** forgotPasswordVisible is a reactive state variable used by the template and event handlers. */
const forgotPasswordVisible = ref(false)
/** forgotCountdown is a reactive state variable used by the template and event handlers. */
const forgotCountdown = ref(0)
/** resettingPassword is a reactive state variable used by the template and event handlers. */
const resettingPassword = ref(false)
const agreementAccepted = ref(false)
const agreements = ref<LegalAgreement[]>([])
const agreementModalOpen = ref(false)
const selectedAgreement = ref<LegalAgreement | null>(null)
const forgotPasswordForm = reactive({
phone: '',
@@ -432,17 +478,32 @@ const formData = reactive({
confirmPassword: '',
nickname: '',
shopId: undefined as string | undefined,
inviteCode: '',
phone: '',
verificationCode: '',
rememberMe: false
})
const agreementVersions = computed<Record<string, string>>(() => {
return agreements.value.reduce((result, agreement) => {
result[agreement.agreementType] = agreement.version
return result
}, {} as Record<string, string>)
})
const agreementPayload = () => ({
agreementAccepted: agreementAccepted.value,
agreementVersions: agreementVersions.value,
clientType: 'WEB'
})
let loginAccountCheckTimer: number | undefined
let loginPhoneShopCheckTimer: number | undefined
const phoneRegex = /^1[3-9]\d{9}$/
const verificationCodeRegex = /^\d{6}$/
const loginShopUnsupportedMessage = '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。'
/** loginShopPlaceholder is a reactive state variable used by the template and event handlers. */
const loginShopPlaceholder = computed(() => {
if (allowLoginShopless.value) {
return '当前暂无启用店铺,可直接登录'
@@ -453,6 +514,7 @@ const loginShopPlaceholder = computed(() => {
return loginShops.value.length ? '请选择登录店铺' : '请先输入账号或手机号'
})
/** validateLoginShopRequired is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validateLoginShopRequired = async () => {
if (allowLoginShopless.value || !loginShops.value.length || formData.shopId) {
return Promise.resolve()
@@ -460,6 +522,7 @@ const validateLoginShopRequired = async () => {
return Promise.reject('请选择登录店铺')
}
/** validatePassword is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validatePassword = async (_rule: Rule, value: string) => {
if (!value || value.length < 6) {
return Promise.reject('密码长度不能少于 6 位')
@@ -478,6 +541,7 @@ const validatePassword = async (_rule: Rule, value: string) => {
return Promise.resolve()
}
/** validateConfirmPassword is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validateConfirmPassword = async (_rule: Rule, value: string) => {
if (!value) {
return Promise.reject('请确认密码')
@@ -488,6 +552,7 @@ const validateConfirmPassword = async (_rule: Rule, value: string) => {
return Promise.resolve()
}
/** handleAccountInput is a local helper used by this page script. */
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formData.account)
if (normalized !== formData.account) {
@@ -574,6 +639,7 @@ const currentRules = computed<Record<string, Rule[]>>(() => {
return loginType.value === 'phone' ? loginPhoneRules : loginPasswordRules
})
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
loadingShops.value = true
try {
@@ -587,6 +653,7 @@ const fetchShops = async () => {
}
}
/** resetLoginAccountStatus is a local helper used by this page script. */
const resetLoginAccountStatus = () => {
if (loginAccountCheckTimer !== undefined) {
window.clearTimeout(loginAccountCheckTimer)
@@ -595,6 +662,7 @@ const resetLoginAccountStatus = () => {
loginAccountStatus.value = null
}
/** resetPhoneLoginShopCheck is a local helper used by this page script. */
const resetPhoneLoginShopCheck = () => {
if (loginPhoneShopCheckTimer !== undefined) {
window.clearTimeout(loginPhoneShopCheckTimer)
@@ -602,6 +670,7 @@ const resetPhoneLoginShopCheck = () => {
}
}
/** resetLoginShopState is a local helper used by this page script. */
const resetLoginShopState = (clearSelectedShop = activeTab.value === 'login') => {
resetPhoneLoginShopCheck()
loginShops.value = []
@@ -612,6 +681,7 @@ const resetLoginShopState = (clearSelectedShop = activeTab.value === 'login') =>
}
}
/** normalizeShopOptionValue is a local helper used by this page script. */
const normalizeShopOptionValue = (shopId?: string | number | null) => {
if (shopId === undefined || shopId === null || shopId === '') {
return undefined
@@ -619,11 +689,13 @@ const normalizeShopOptionValue = (shopId?: string | number | null) => {
return String(shopId)
}
/** isLoginShopPrefetchUnsupported is a local helper used by this page script. */
const isLoginShopPrefetchUnsupported = (error: unknown) => {
const status = (error as any)?.response?.status
return status === 404
}
/** applyLoginShopSelection is a local helper used by this page script. */
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
loginShops.value = selection?.shops || []
allowLoginShopless.value = Boolean(selection?.allowShoplessLogin)
@@ -657,6 +729,7 @@ const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null)
formData.shopId = undefined
}
/** loadLoginShopsByAccount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadLoginShopsByAccount = async (account = formData.account) => {
const trimmedAccount = account.trim()
if (activeTab.value !== 'login' || loginType.value !== 'password' || !trimmedAccount) {
@@ -693,6 +766,7 @@ const loadLoginShopsByAccount = async (account = formData.account) => {
}
}
/** loadLoginShopsByPhone is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadLoginShopsByPhone = async (phone = formData.phone) => {
const trimmedPhone = phone.trim()
if (activeTab.value !== 'login' || loginType.value !== 'phone' || !phoneRegex.test(trimmedPhone)) {
@@ -729,6 +803,7 @@ const loadLoginShopsByPhone = async (phone = formData.phone) => {
}
}
/** checkLoginAccountAvailability is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkLoginAccountAvailability = async (account = formData.account) => {
const trimmedAccount = account.trim()
if (activeTab.value !== 'login' || loginType.value !== 'password' || !trimmedAccount) {
@@ -755,6 +830,7 @@ const checkLoginAccountAvailability = async (account = formData.account) => {
}
}
/** checkRegisterAccountAvailability is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkRegisterAccountAvailability = async (showWarning = true) => {
const trimmedAccount = formData.account.trim()
if (activeTab.value !== 'register' || !trimmedAccount) {
@@ -770,6 +846,7 @@ const checkRegisterAccountAvailability = async (showWarning = true) => {
return response.available
}
/** checkRegisterPhoneAvailability is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkRegisterPhoneAvailability = async (showWarning = true) => {
const trimmedPhone = formData.phone.trim()
if (activeTab.value !== 'register' || !trimmedPhone) {
@@ -785,7 +862,36 @@ const checkRegisterPhoneAvailability = async (showWarning = true) => {
return response.available
}
const loadAgreements = async () => {
try {
agreements.value = await legalAgreementApi.listCurrent() as unknown as LegalAgreement[]
} catch (error) {
console.error('加载协议失败:', error)
message.warning('协议内容加载失败,请稍后重试')
}
}
const openAgreement = async (type: 'USER_TERMS' | 'PRIVACY_POLICY') => {
const cached = agreements.value.find(item => item.agreementType === type)
if (cached) {
selectedAgreement.value = cached
agreementModalOpen.value = true
return
}
selectedAgreement.value = await legalAgreementApi.getCurrent(type) as unknown as LegalAgreement
agreementModalOpen.value = true
}
/** handleSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSubmit = async () => {
if (!agreementAccepted.value) {
message.warning('请先阅读并同意用户协议和隐私政策')
return
}
if (!agreementVersions.value.USER_TERMS || !agreementVersions.value.PRIVACY_POLICY) {
message.warning('协议内容未加载完成,请稍后再试')
return
}
loading.value = true
try {
await runWithGlobalLoading(async () => {
@@ -796,14 +902,16 @@ const handleSubmit = async () => {
response = await authApi.phoneLogin({
phone: formData.phone,
verificationCode: formData.verificationCode,
shopId: formData.shopId
shopId: formData.shopId,
...agreementPayload()
})
} else {
response = await authApi.login({
account: formData.account,
password: formData.password,
rememberMe: formData.rememberMe,
shopId: formData.shopId
shopId: formData.shopId,
...agreementPayload()
})
}
@@ -846,7 +954,9 @@ const handleSubmit = async () => {
nickname: formData.nickname,
phone: formData.phone,
verificationCode: formData.verificationCode,
shopId: formData.shopId!
shopId: formData.shopId!,
inviteCode: formData.inviteCode,
...agreementPayload()
})
message.success('注册成功,请登录')
@@ -865,10 +975,12 @@ const handleSubmit = async () => {
}
}
/** handleForgotPassword is a local helper used by this page script. */
const handleForgotPassword = () => {
forgotPasswordVisible.value = true
}
/** handleSendForgotCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendForgotCode = async () => {
if (!forgotPasswordForm.phone) {
message.error('请输入手机号')
@@ -880,7 +992,10 @@ const handleSendForgotCode = async () => {
}
try {
await runWithGlobalLoading(() => authApi.sendVerificationCode({ phone: forgotPasswordForm.phone }))
await runWithGlobalLoading(() => authApi.sendVerificationCode({
phone: forgotPasswordForm.phone,
sceneCode: 'USER_RESET_PASSWORD_SMS_CODE'
}))
message.success('验证码已发送')
forgotCountdown.value = 60
const timer = window.setInterval(() => {
@@ -894,6 +1009,7 @@ const handleSendForgotCode = async () => {
}
}
/** handleResetPassword is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleResetPassword = async () => {
resettingPassword.value = true
try {
@@ -914,6 +1030,7 @@ const handleResetPassword = async () => {
}
}
/** handleRegisterAccountBlur is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRegisterAccountBlur = async () => {
if (activeTab.value !== 'register' || !formData.account.trim()) {
registerAccountStatus.value = null
@@ -928,6 +1045,7 @@ const handleRegisterAccountBlur = async () => {
}
}
/** handleRegisterPhoneBlur is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRegisterPhoneBlur = async () => {
if (activeTab.value !== 'register' || !formData.phone.trim()) {
registerPhoneStatus.value = null
@@ -946,6 +1064,7 @@ const handleRegisterPhoneBlur = async () => {
}
}
/** handleSendVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendVerificationCode = async () => {
if (!formData.phone) {
message.error('请输入手机号')
@@ -965,7 +1084,10 @@ const handleSendVerificationCode = async () => {
}
}
await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: formData.phone }))
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: formData.phone,
sceneCode: activeTab.value === 'register' ? 'USER_REGISTER_SMS_CODE' : 'USER_LOGIN_SMS_CODE'
}))
message.success('验证码已发送')
countdown.value = 60
const timer = window.setInterval(() => {
@@ -979,6 +1101,7 @@ const handleSendVerificationCode = async () => {
}
}
/** handleAdminLogin is a local helper used by this page script. */
const handleAdminLogin = () => {
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
@@ -1058,6 +1181,7 @@ watch(
onMounted(() => {
fetchShops()
loadAgreements()
})
onBeforeUnmount(() => {
@@ -1258,4 +1382,24 @@ onBeforeUnmount(() => {
display: flex;
align-items: center;
}
.agreement-content {
max-height: 60vh;
overflow: auto;
}
.agreement-version {
margin-bottom: 12px;
color: #8c8c8c;
font-size: 13px;
}
.agreement-content pre {
white-space: pre-wrap;
word-break: break-word;
margin: 0;
font-family: inherit;
line-height: 1.7;
color: #333;
}
</style>
+174 -2
View File
@@ -31,7 +31,7 @@
<a-card
v-for="item in cartItems"
:key="item.id"
:ref="element => setItemRef(item.id, element)"
:ref="(element: unknown) => setItemRef(item.id, element)"
class="item-card"
:class="{ 'issue-card': item.selected && hasItemIssue(item) }"
>
@@ -150,6 +150,7 @@
>
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" />
<span>{{ artist.name }}</span>
<em v-if="artist.roleLabel">{{ artist.roleLabel }}</em>
</button>
</div>
<a-empty v-else description="暂无可预约美甲师" />
@@ -160,6 +161,7 @@
<a-date-picker
v-model:value="draftAppointmentTime"
class="time-picker"
popup-class-name="yumi-date-picker-panel yumi-date-time-panel"
style="width: 100%"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
@@ -169,6 +171,19 @@
:show-time="{ minuteStep: 30, secondStep: 60, hideDisabledOptions: true }"
placeholder="请选择预约时间"
/>
<div class="quick-time-grid">
<button
v-for="slot in quickAppointmentSlots"
:key="slot.value"
type="button"
class="quick-time"
:class="{ active: draftAppointmentTime === slot.value }"
@click="draftAppointmentTime = slot.value"
>
<span>{{ slot.label }}</span>
<strong>{{ slot.time }}</strong>
</button>
</div>
<div class="helper">{{ bookingHelperText }}</div>
</div>
</a-modal>
@@ -176,6 +191,10 @@
</template>
<script setup lang="ts">
/**
* CartView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, inject, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
@@ -198,6 +217,9 @@ interface ArtistOption {
id: IdType
name: string
avatar?: string
userType?: number
roleLabel?: string
participateProduction?: boolean
}
interface CartItem {
@@ -234,32 +256,73 @@ const imageIdCache = ref<Record<string, string>>({})
const itemRefs = ref<Record<string, HTMLElement>>({})
const availableCoupons = ref<UserCoupon[]>([])
const selectedCoupon = ref<UserCoupon | null>(null)
/** couponSelectionKey is a reactive state variable used by the template and event handlers. */
const couponSelectionKey = ref(NO_COUPON_KEY)
/** couponSelectionTouched is a reactive state variable used by the template and event handlers. */
const couponSelectionTouched = ref(false)
/** showCouponModal is a reactive state variable used by the template and event handlers. */
const showCouponModal = ref(false)
/** showBookingModal is a reactive state variable used by the template and event handlers. */
const showBookingModal = ref(false)
const currentItem = ref<CartItem | null>(null)
const availableArtists = ref<ArtistOption[]>([])
const draftArtistId = ref<IdType>()
/** draftAppointmentTime is a reactive state variable used by the template and event handlers. */
const draftAppointmentTime = ref('')
/** currentShopHours is a reactive state variable used by the template and event handlers. */
const currentShopHours = ref('')
/** editing is a reactive state variable used by the template and event handlers. */
const editing = ref(false)
/** submittingOrder is a reactive state variable used by the template and event handlers. */
const submittingOrder = ref(false)
/** selectedItems is a reactive state variable used by the template and event handlers. */
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
/** selectedCount is a reactive state variable used by the template and event handlers. */
const selectedCount = computed(() => selectedItems.value.length)
/** totalQuantity is a reactive state variable used by the template and event handlers. */
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
/** subtotal is a reactive state variable used by the template and event handlers. */
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
/** discountAmount is a reactive state variable used by the template and event handlers. */
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
/** totalAmount is a reactive state variable used by the template and event handlers. */
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
/** bookingTitle is a reactive state variable used by the template and event handlers. */
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
/** bookingHelperText is a reactive state variable used by the template and event handlers. */
const bookingHelperText = computed(() => {
const texts: string[] = []
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
})
/** quickAppointmentSlots is a reactive state variable used by the template and event handlers. */
const quickAppointmentSlots = computed(() => {
const now = getMinAppointmentDate()
const today = new Date(now)
const nextHour = new Date(now)
nextHour.setMinutes(now.getMinutes() > 30 ? 0 : 30, 0, 0)
if (nextHour.getTime() < now.getTime()) {
nextHour.setHours(nextHour.getHours() + 1)
}
const tomorrowMorning = buildAppointmentDate(1, 10, 0)
const tomorrowAfternoon = buildAppointmentDate(1, 14, 0)
const afterTomorrowAfternoon = buildAppointmentDate(2, 15, 0)
const weekendMorning = nextWeekendMorning(today)
return [nextHour, tomorrowMorning, tomorrowAfternoon, afterTomorrowAfternoon, weekendMorning]
.filter((date, index, list) => date.getTime() >= now.getTime() && list.findIndex(item => item.getTime() === date.getTime()) === index)
.slice(0, 5)
.map(date => ({
value: formatAppointmentValue(date),
label: quickDateLabel(date),
time: `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}))
})
/** getMinAppointmentDate is a local helper used by this page script. */
const getMinAppointmentDate = () => {
const date = new Date()
date.setSeconds(0, 0)
@@ -267,14 +330,52 @@ const getMinAppointmentDate = () => {
return date
}
/** getDayBoundary is a local helper used by this page script. */
const getDayBoundary = (date: Date) => {
const boundary = new Date(date)
boundary.setHours(0, 0, 0, 0)
return boundary.getTime()
}
/** buildAppointmentDate is a local helper used by this page script. */
const buildAppointmentDate = (daysFromToday: number, hour: number, minute: number) => {
const date = new Date()
date.setDate(date.getDate() + daysFromToday)
date.setHours(hour, minute, 0, 0)
return date
}
/** nextWeekendMorning is a local helper used by this page script. */
const nextWeekendMorning = (fromDate: Date) => {
const date = new Date(fromDate)
const day = date.getDay()
const offset = day === 0 ? 6 : 6 - day
date.setDate(date.getDate() + Math.max(1, offset))
date.setHours(10, 0, 0, 0)
return date
}
/** formatAppointmentValue is a local helper used by this page script. */
const formatAppointmentValue = (date: Date) => {
/** pad is a local helper used by this page script. */
const pad = (value: number) => String(value).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:00`
}
/** quickDateLabel is a local helper used by this page script. */
const quickDateLabel = (date: Date) => {
const today = new Date()
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
if (date.toDateString() === today.toDateString()) return '今天'
if (date.toDateString() === tomorrow.toDateString()) return '明天'
return `${date.getMonth() + 1}月${date.getDate()}日`
}
/** getCouponKey is a local helper used by this page script. */
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
/** setItemRef is a local helper used by this page script. */
const setItemRef = (itemId: IdType, element: unknown) => {
const refKey = toOptionalIdString(itemId)
if (!refKey) {
@@ -291,6 +392,7 @@ const setItemRef = (itemId: IdType, element: unknown) => {
delete itemRefs.value[refKey]
}
/** formatCouponDisplay is a local helper used by this page script. */
const formatCouponDisplay = (coupon: UserCoupon) => {
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
const benefit = coupon.couponType === 1
@@ -299,6 +401,7 @@ const formatCouponDisplay = (coupon: UserCoupon) => {
return `${badge} ${coupon.couponName} ${benefit}`
}
/** calculateCouponDiscount is a local helper used by this page script. */
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
if (!coupon || amount <= 0) {
return 0
@@ -313,14 +416,18 @@ const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
return 0
}
/** findBestCoupon is a local helper used by this page script. */
const findBestCoupon = (coupons: UserCoupon[]) => {
return coupons
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
}
/** formatAppointmentDisplay is a local helper used by this page script. */
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
/** isPastAppointment is a local helper used by this page script. */
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
/** hasItemIssue is a local helper used by this page script. */
const hasItemIssue = (item: CartItem) => !item.artistId || !item.appointmentTime || isPastAppointment(item.appointmentTime)
// 购物车结算口径要求单店铺、单美甲师、完整预约信息,避免后端拆单和排班出现歧义。
@@ -363,6 +470,7 @@ const checkoutIssues = computed<CheckoutIssue[]>(() => {
return issues
})
/** scrollToIssue is a local helper used by this page script. */
const scrollToIssue = (issue?: CheckoutIssue) => {
const itemId = toOptionalIdString(issue?.itemId)
if (!itemId) {
@@ -374,10 +482,12 @@ const scrollToIssue = (issue?: CheckoutIssue) => {
}
}
/** focusFirstIssue is a local helper used by this page script. */
const focusFirstIssue = () => {
scrollToIssue(checkoutIssues.value[0])
}
/** loadCartItems is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartItems = async () => {
const response = await cartApi.getCartList() as unknown as any[]
cartItems.value = (response || []).map(item => ({
@@ -394,6 +504,7 @@ const loadCartItems = async () => {
await Promise.all([loadProductImages(), loadAvailableCoupons()])
}
/** loadProductImages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadProductImages = async () => {
for (const item of cartItems.value) {
if (!item.originalProductImage) continue
@@ -411,6 +522,7 @@ const loadProductImages = async () => {
}
}
/** loadAvailableCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadAvailableCoupons = async () => {
if (editing.value) {
return
@@ -470,10 +582,12 @@ 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())
}
/** changeQuantity is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const changeQuantity = async (item: CartItem, delta: number) => {
const next = item.quantity + delta
if (next < 1 || next > 99) return
@@ -490,6 +604,7 @@ const changeQuantity = async (item: CartItem, delta: number) => {
}
}
/** removeItem is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const removeItem = async (item: CartItem) => {
try {
await runWithGlobalLoading(async () => {
@@ -504,6 +619,7 @@ const removeItem = async (item: CartItem) => {
}
}
/** removeSelectedItems is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const removeSelectedItems = async () => {
if (!selectedItems.value.length) {
message.warning('请先勾选要删除的作品')
@@ -523,10 +639,12 @@ const removeSelectedItems = async () => {
}
}
/** openProduct is a local helper used by this page script. */
const openProduct = (item: CartItem) => {
router.push('/product/' + item.productId)
}
/** openBookingModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const openBookingModal = async (item: CartItem) => {
currentItem.value = item
draftArtistId.value = item.artistId
@@ -535,6 +653,7 @@ const openBookingModal = async (item: CartItem) => {
await runWithGlobalLoading(() => Promise.all([loadArtists(item), loadShopHours(item.shopId)]))
}
/** 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)
@@ -543,7 +662,10 @@ const loadArtists = async (item: CartItem) => {
.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
}))
: []
@@ -552,6 +674,7 @@ const loadArtists = async (item: CartItem) => {
}
}
/** loadShopHours is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadShopHours = async (shopId?: IdType) => {
currentShopHours.value = ''
if (!shopId) return
@@ -563,11 +686,13 @@ const loadShopHours = async (shopId?: IdType) => {
}
}
/** disablePastAppointmentDate is a local helper used by this page script. */
const disablePastAppointmentDate = (current: any) => {
if (!current) return false
return current.valueOf() < getDayBoundary(new Date())
}
/** disablePastAppointmentTime is a local helper used by this page script. */
const disablePastAppointmentTime = (current: any) => {
if (!current || typeof current.format !== 'function') {
return {}
@@ -592,6 +717,7 @@ const disablePastAppointmentTime = (current: any) => {
}
}
/** closeBookingModal is a local helper used by this page script. */
const closeBookingModal = () => {
showBookingModal.value = false
currentItem.value = null
@@ -601,6 +727,7 @@ const closeBookingModal = () => {
currentShopHours.value = ''
}
/** confirmBooking is a local helper used by this page script. */
const confirmBooking = () => {
if (!currentItem.value) return closeBookingModal()
if (!draftArtistId.value) return message.warning('请先选择美甲师')
@@ -612,11 +739,13 @@ const confirmBooking = () => {
closeBookingModal()
}
/** openCouponModal is a local helper used by this page script. */
const openCouponModal = () => {
couponSelectionKey.value = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : NO_COUPON_KEY
showCouponModal.value = true
}
/** applyCouponSelection is a local helper used by this page script. */
const applyCouponSelection = () => {
couponSelectionTouched.value = true
if (couponSelectionKey.value === NO_COUPON_KEY) {
@@ -627,6 +756,7 @@ const applyCouponSelection = () => {
showCouponModal.value = false
}
/** checkout is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkout = async () => {
if (submittingOrder.value) {
return
@@ -822,6 +952,42 @@ onMounted(async () => {
font-size: 12px;
}
.quick-time-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(104px, 1fr));
gap: 8px;
margin: 10px 0;
}
.quick-time {
display: grid;
gap: 2px;
padding: 10px 12px;
border: 1px solid #e6ecf5;
border-radius: 8px;
background: #f8fbff;
color: #273142;
text-align: left;
cursor: pointer;
transition: border-color .18s ease, background .18s ease, transform .18s ease;
}
.quick-time:hover,
.quick-time.active {
border-color: #1677ff;
background: #eef6ff;
transform: translateY(-1px);
}
.quick-time span {
color: #7a8699;
font-size: 12px;
}
.quick-time strong {
font-size: 16px;
}
.actions,
.qty,
.coupon-row,
@@ -903,6 +1069,12 @@ onMounted(async () => {
object-fit: cover;
}
.artist-option em {
color: #8a6a34;
font-size: 12px;
font-style: normal;
}
@media (max-width: 767px) {
.content {
padding: 15px 15px 140px;
@@ -58,6 +58,10 @@
</template>
<script setup lang="ts">
/**
* CouponView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
@@ -66,8 +70,10 @@ import { couponApi } from '@/api/coupon'
const router = useRouter()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const coupons = ref<any[]>([])
/** activeFilter is a reactive state variable used by the template and event handlers. */
const activeFilter = ref('all')
const filterOptions = [
@@ -77,6 +83,7 @@ const filterOptions = [
{ label: '已过期', value: 'expired' }
]
/** filteredCoupons is a reactive state variable used by the template and event handlers. */
const filteredCoupons = computed(() => {
if (activeFilter.value === 'all') {
return coupons.value
@@ -90,6 +97,7 @@ const filteredCoupons = computed(() => {
return coupons.value
})
/** loadCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCoupons = async () => {
loading.value = true
try {
@@ -103,6 +111,7 @@ const loadCoupons = async () => {
}
}
/** getStatusClass is a local helper used by this page script. */
const getStatusClass = (status: number) => {
switch (status) {
case 1:
@@ -116,6 +125,7 @@ const getStatusClass = (status: number) => {
}
}
/** formatDate is a local helper used by this page script. */
const formatDate = (dateString: string) => {
if (!dateString) return ''
const date = new Date(dateString)
+83 -1
View File
@@ -26,6 +26,14 @@
/>
</div>
<div v-if="announcements.length" class="announcement-bar">
<div class="announcement-track">
<span v-for="item in announcementLoop" :key="`${item.id}-${item.loopKey}`">
<b>{{ item.publisherName || '平台' }}</b>:{{ item.content }}
</span>
</div>
</div>
<a-alert
v-if="!isLoggedIn"
class="guest-alert"
@@ -82,6 +90,7 @@
</div>
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p v-if="item.shopName" class="meta">所属店铺:{{ item.shopName }}</p>
<p class="meta">{{ item.meta }}</p>
<p class="price">¥{{ item.price }}</p>
</div>
@@ -109,6 +118,7 @@
</div>
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p v-if="item.shopName" class="meta">所属店铺:{{ item.shopName }}</p>
<p class="meta">{{ item.meta }}</p>
<p class="price">¥{{ item.price }}</p>
</div>
@@ -130,10 +140,14 @@
</template>
<script setup lang="ts">
/**
* HomeView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { userApi, type UserVO } from '../api/user'
import { userApi, type AnnouncementVO, type UserVO } from '../api/user'
import { productApi, type ProductVO } from '../api/product'
import { shopApi, type ShopVO } from '../api/shop'
import { fileApi } from '../api/file'
@@ -153,6 +167,7 @@ interface ProductCardItem {
name: string
price: string
meta: string
shopName?: string
coverUrl: string
bgColor: string
}
@@ -165,22 +180,34 @@ const bannerImages = ref<BannerImage[]>([])
const featuredItems = ref<ProductCardItem[]>([])
const popularSource = ref<ProductCardItem[]>([])
const popularItems = ref<ProductCardItem[]>([])
const announcements = ref<AnnouncementVO[]>([])
const productImageCache = ref<Record<string, string>>({})
/** searchQuery is a reactive state variable used by the template and event handlers. */
const searchQuery = ref('')
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** hasMore is a reactive state variable used by the template and event handlers. */
const hasMore = ref(true)
/** page is a reactive state variable used by the template and event handlers. */
const page = ref(1)
const pageSize = 8
/** isLoggedIn is a reactive state variable used by the template and event handlers. */
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
/** greeting is a reactive state variable used by the template and event handlers. */
const greeting = computed(() => (isLoggedIn.value ? '欢迎回来' : '游客模式'))
/** displayName is a reactive state variable used by the template and event handlers. */
const displayName = computed(() => userInfo.value?.nickname || (isLoggedIn.value ? '用户' : '先看看门店和作品'))
/** announcementLoop is a reactive state variable used by the template and event handlers. */
const announcementLoop = computed(() => [...announcements.value, ...announcements.value].map((item, index) => ({ ...item, loopKey: index })))
/** getRandomColor is a local helper used by this page script. */
const getRandomColor = (): string => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)] ?? '#ffe4d6'
}
/** 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) {
@@ -197,16 +224,19 @@ const getProductCoverUrl = async (product: ProductVO): Promise<string> => {
return productImageCache.value[firstImageId] || 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[]> =>
Promise.all(products.map(async item => ({
id: item.id,
name: item.title || item.name || '未命名作品',
price: Number(item.price || 0).toFixed(2),
meta: item.approximateDuration || item.shopName || '支持预约',
shopName: item.shopName,
coverUrl: await getProductCoverUrl(item),
bgColor: getRandomColor()
})))
/** appendPopularItems is a local helper used by this page script. */
const appendPopularItems = (loadMore = false) => {
const nextItems = popularSource.value.slice(0, page.value * pageSize)
popularItems.value = nextItems
@@ -216,6 +246,7 @@ const appendPopularItems = (loadMore = false) => {
}
}
/** loadUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadUserInfo = async () => {
if (!isLoggedIn.value) {
userInfo.value = null
@@ -230,6 +261,7 @@ const loadUserInfo = async () => {
}
}
/** loadPublicShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadPublicShops = async () => {
try {
const shops = await shopApi.getPublicShops()
@@ -242,6 +274,7 @@ const loadPublicShops = async () => {
}
}
/** loadBannerImages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadBannerImages = async () => {
const banners: BannerImage[] = []
for (const shop of publicShops.value) {
@@ -269,6 +302,7 @@ const loadBannerImages = async () => {
bannerImages.value = banners.slice(0, 8)
}
/** loadFeaturedProducts is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadFeaturedProducts = async () => {
try {
let products = await productApi.getProductsByTag('精选')
@@ -282,6 +316,7 @@ const loadFeaturedProducts = async () => {
}
}
/** loadPopularProducts is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadPopularProducts = async () => {
loading.value = true
try {
@@ -302,6 +337,21 @@ const loadPopularProducts = async () => {
}
}
/** loadAnnouncements is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadAnnouncements = async () => {
if (!isLoggedIn.value) {
announcements.value = []
return
}
try {
announcements.value = (await userApi.listMyAnnouncements()) || []
} catch (error) {
console.error('加载公告失败:', error)
announcements.value = []
}
}
/** handleScroll is a local helper used by this page script. */
const handleScroll = () => {
if (loading.value || !hasMore.value) {
return
@@ -315,6 +365,7 @@ const handleScroll = () => {
}
}
/** handleUserClick is a local helper used by this page script. */
const handleUserClick = () => {
if (isLoggedIn.value) {
router.push('/profile')
@@ -324,11 +375,13 @@ const handleUserClick = () => {
router.push('/')
}
/** handleSearch is a local helper used by this page script. */
const handleSearch = () => {
const keyword = searchQuery.value.trim()
router.push(keyword ? { path: '/products', query: { keyword } } : '/products')
}
/** handleSeeAll is a local helper used by this page script. */
const handleSeeAll = (type: 'featured' | 'popular') => {
router.push({
path: '/products',
@@ -336,10 +389,12 @@ const handleSeeAll = (type: 'featured' | 'popular') => {
})
}
/** handleProductClick is a local helper used by this page script. */
const handleProductClick = (item: ProductCardItem) => {
router.push(`/product/${item.id}`)
}
/** openShopById is a local helper used by this page script. */
const openShopById = (shopId: IdType) => {
router.push(`/shop/${shopId}`)
}
@@ -347,6 +402,7 @@ const openShopById = (shopId: IdType) => {
onMounted(async () => {
await Promise.all([
loadUserInfo(),
loadAnnouncements(),
loadPublicShops(),
loadFeaturedProducts(),
loadPopularProducts()
@@ -395,6 +451,32 @@ onUnmounted(() => {
padding: 8px 20px 0;
}
.announcement-bar {
margin: 12px 20px 0;
overflow: hidden;
border-radius: 8px;
background: #fff7ed;
border: 1px solid #fed7aa;
}
.announcement-track {
display: flex;
width: max-content;
gap: 32px;
padding: 9px 14px;
color: #7c2d12;
animation: announcement-scroll 22s linear infinite;
}
.announcement-track span {
white-space: nowrap;
}
@keyframes announcement-scroll {
from { transform: translateX(0); }
to { transform: translateX(-50%); }
}
.guest-alert {
margin: 16px 20px 0;
border-radius: 16px;
@@ -13,13 +13,19 @@
</template>
<script setup lang="ts">
/**
* NotFoundView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(5)
let timer: number | null = null
/** redirectToHome is a local helper used by this page script. */
const redirectToHome = () => {
if (timer) {
clearInterval(timer)
@@ -0,0 +1,179 @@
<template>
<div class="notifications-page">
<header class="page-header">
<button class="back-btn" type="button" @click="router.back()">‹</button>
<div>
<h1>消息通知</h1>
<p>{{ unreadCount }} 条未读消息</p>
</div>
</header>
<main class="message-list">
<button
v-for="item in messages"
:key="item.id"
class="message-item"
:class="{ unread: item.readStatus !== 1 }"
type="button"
@click="openMessage(item)"
>
<span class="dot"></span>
<span class="message-main">
<strong>{{ item.title }}</strong>
<small>{{ item.publisherName || '系统消息' }} · {{ item.publishTime || item.createTime }}</small>
<em v-if="item.imageUrl">含图片</em>
</span>
</button>
<a-empty v-if="!loading && messages.length === 0" description="暂无消息" />
</main>
<a-modal v-model:open="detailVisible" title="消息详情" @ok="detailVisible = false">
<h3>{{ currentMessage?.title }}</h3>
<p class="message-meta">{{ currentMessage?.publisherName || '系统消息' }} · {{ currentMessage?.publishTime }}</p>
<div v-if="currentMessage?.content" class="message-content">{{ currentMessage?.content }}</div>
<img v-if="currentMessage?.imageUrl" class="message-image" :src="currentMessage.imageUrl" alt="消息图片" />
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* NotificationsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { userApi, type SystemMessageVO } from '@/api/user'
const router = useRouter()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const messages = ref<SystemMessageVO[]>([])
/** detailVisible is a reactive state variable used by the template and event handlers. */
const detailVisible = ref(false)
const currentMessage = ref<SystemMessageVO | null>(null)
/** unreadCount is a reactive state variable used by the template and event handlers. */
const unreadCount = computed(() => messages.value.filter(item => item.readStatus !== 1).length)
/** loadMessages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadMessages = async () => {
loading.value = true
try {
messages.value = await userApi.listMyMessages()
} catch (error: any) {
message.error(error?.message || '消息加载失败')
} finally {
loading.value = false
}
}
/** openMessage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const openMessage = async (item: SystemMessageVO) => {
currentMessage.value = item
detailVisible.value = true
if (item.readStatus !== 1) {
await userApi.markMessageRead(item.id)
item.readStatus = 1
}
}
onMounted(loadMessages)
</script>
<style scoped>
.notifications-page {
min-height: 100vh;
background: #fff7f8;
padding: 18px;
}
.page-header {
display: flex;
gap: 14px;
align-items: center;
margin-bottom: 18px;
}
.page-header h1 {
margin: 0;
font-size: 24px;
}
.page-header p {
margin: 4px 0 0;
color: #8a7b83;
}
.back-btn {
width: 40px;
height: 40px;
border: 0;
border-radius: 20px;
background: #fff;
font-size: 28px;
}
.message-list {
display: grid;
gap: 10px;
}
.message-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 16px;
border: 0;
border-radius: 8px;
background: #fff;
text-align: left;
}
.message-item .dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #d7c9cf;
}
.message-item.unread .dot {
background: #ff5c8a;
}
.message-main {
display: grid;
gap: 4px;
}
.message-main em {
width: fit-content;
padding: 2px 8px;
border-radius: 999px;
background: #fff0f4;
color: #d74270;
font-size: 12px;
font-style: normal;
}
.message-main small,
.message-meta {
color: #8a7b83;
}
.message-content {
white-space: pre-wrap;
line-height: 1.8;
}
.message-image {
display: block;
width: 100%;
max-height: 420px;
margin-top: 14px;
object-fit: contain;
border-radius: 8px;
background: #fff7f8;
}
</style>
+85 -2
View File
@@ -9,15 +9,38 @@
</header>
<main class="content">
<section v-if="orders.length" class="filter-panel">
<a-input v-model:value="filters.keyword" allow-clear placeholder="搜索订单号、作品、美甲师" />
<div class="filter-row">
<a-select v-model:value="filters.status" class="filter-select" placeholder="订单状态">
<a-select-option value="all">全部状态</a-select-option>
<a-select-option :value="1">待使用</a-select-option>
<a-select-option :value="2">已完成</a-select-option>
<a-select-option :value="3">已取消</a-select-option>
</a-select>
<a-date-picker v-model:value="filters.date" class="filter-date" popup-class-name="yumi-date-picker-panel" placeholder="预约日期" />
</div>
<div class="filter-row">
<a-input-number v-model:value="filters.minAmount" class="filter-number" :min="0" placeholder="最低金额" />
<a-input-number v-model:value="filters.maxAmount" class="filter-number" :min="0" placeholder="最高金额" />
<a-button @click="resetFilters">重置</a-button>
</div>
<div class="filter-summary">共 {{ filteredOrders.length }} / {{ orders.length }} 个订单</div>
</section>
<a-empty v-if="!orders.length" description="暂无订单">
<a-button type="primary" @click="router.push('/products')">去逛逛</a-button>
</a-empty>
<a-empty v-else-if="!filteredOrders.length" description="没有符合条件的订单">
<a-button @click="resetFilters">清空筛选</a-button>
</a-empty>
<a-card v-for="order in orders" :key="order.id" class="order-card">
<a-card v-for="order in filteredOrders" :key="order.id" class="order-card">
<div class="order-head">
<span>订单号:{{ order.orderNo }}</span>
<span class="status" :class="statusClass(order.status)">{{ order.statusText }}</span>
</div>
<div v-if="order.shopName" class="order-shop">所属店铺:{{ order.shopName }}</div>
<div v-for="item in order.items" :key="item.id" class="item">
<div class="thumb">
@@ -42,27 +65,81 @@
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
/**
* OrderView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { fileApi } from '../api/index'
import { orderApi } from '../api/order'
import { userApi } from '@/api/user'
import type { IdType } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
const router = useRouter()
const orders = ref<any[]>([])
const imageIdCache = ref<Record<string, string>>({})
const filters = reactive({
keyword: '',
status: 'all' as 'all' | number,
date: null as any,
minAmount: undefined as number | undefined,
maxAmount: undefined as number | undefined
})
/** filteredOrders is a reactive state variable used by the template and event handlers. */
const filteredOrders = computed(() => {
const keyword = filters.keyword.trim().toLowerCase()
const targetDate = filters.date?.format?.('YYYY-MM-DD')
return orders.value.filter(order => {
if (filters.status !== 'all' && order.status !== filters.status) return false
const amount = Number(order.actualAmount || 0)
if (filters.minAmount !== undefined && amount < filters.minAmount) return false
if (filters.maxAmount !== undefined && amount > filters.maxAmount) return false
const items = order.items || []
if (targetDate && !items.some((item: any) => String(item.appointmentTime || '').slice(0, 10) === targetDate)) {
return false
}
if (keyword) {
const haystack = [
order.orderNo,
order.shopName,
order.statusText,
...items.flatMap((item: any) => [item.productTitle, item.artistName, item.appointmentTime])
].filter(Boolean).join(' ').toLowerCase()
if (!haystack.includes(keyword)) return false
}
return true
})
})
/** statusClass is a local helper used by this page script. */
const statusClass = (status: number) => {
if (status === 1) return 'pending'
if (status === 2) return 'completed'
return 'cancelled'
}
/** resetFilters is a local helper used by this page script. */
const resetFilters = () => {
filters.keyword = ''
filters.status = 'all'
filters.date = null
filters.minAmount = undefined
filters.maxAmount = undefined
}
/** loadOrders is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadOrders = async () => {
try {
const userInfo = await userApi.getUserInfo()
if (userInfo.type === 2 || userInfo.type === 3) {
router.replace('/artist-orders')
return
}
orders.value = (await orderApi.getOrderList() as unknown as any[]) || []
for (const order of orders.value) {
for (const item of order.items || []) {
@@ -82,6 +159,7 @@ const loadOrders = async () => {
}
}
/** cancelOrder is a local helper used by this page script. */
const cancelOrder = (orderId: IdType) => {
Modal.confirm({
title: '确认取消订单',
@@ -107,9 +185,14 @@ onMounted(loadOrders)
.header h1 { margin: 0; font-size: 18px; }
.placeholder { width: 40px; height: 40px; }
.content { padding: 15px; }
.filter-panel { display: grid; gap: 10px; margin-bottom: 12px; padding: 12px; border-radius: 8px; background: #fff; }
.filter-row { display: flex; gap: 8px; align-items: center; }
.filter-select, .filter-date, .filter-number { flex: 1; min-width: 0; }
.filter-summary { color: #888; font-size: 12px; text-align: right; }
.order-card { margin-bottom: 12px; border-radius: 12px; }
.order-head, .footer { display: flex; align-items: center; justify-content: space-between; }
.order-head { margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0; }
.order-shop { margin: -4px 0 12px; color: #7a5262; font-size: 13px; }
.status { padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
.pending { background: #fff7e6; color: #fa8c16; }
.completed { background: #f6ffed; color: #52c41a; }
@@ -91,6 +91,10 @@
</template>
<script setup lang="ts">
/**
* PasswordSettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, LockOutlined } from '@ant-design/icons-vue'
@@ -104,7 +108,9 @@ import { runWithGlobalLoading } from '@/utils/action-loading'
const router = useRouter()
const formRef = ref<FormInstance>()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
const userInfo = ref<{ phone?: string } | null>(null)
const draftSavedAt = ref<number | null>(null)
@@ -118,6 +124,7 @@ const formState = reactive({
const draftKey = buildDraftStorageKey('password-settings', 'set-password')
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<typeof formState>(draftKey, 'session')
if (!draft) {
@@ -129,12 +136,14 @@ const restoreDraft = () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(draftKey, { ...formState }, 'session')
draftSavedAt.value = draft.savedAt
message.success('已暂存到当前会话')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(draftKey, 'session')
draftSavedAt.value = null
@@ -143,8 +152,10 @@ const handleClearDraft = (showMessage = true) => {
}
}
/** userPhone is a reactive state variable used by the template and event handlers. */
const userPhone = computed(() => userInfo.value?.phone || '')
/** validateConfirmPassword is a local helper used by this page script. */
const validateConfirmPassword = (_rule: any, value: string) => {
if (value !== formState.password) {
return Promise.reject(new Error('两次输入的密码不一致'))
@@ -168,6 +179,7 @@ const formRules: Record<string, Rule[]> = {
]
}
/** startCountdown is a local helper used by this page script. */
const startCountdown = () => {
countdown.value = 60
if (countdownTimer) {
@@ -182,6 +194,7 @@ const startCountdown = () => {
}, 1000)
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const res = await userApi.getUserInfo()
@@ -192,6 +205,7 @@ const fetchUserInfo = async () => {
}
}
/** handleSendVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendVerificationCode = async () => {
if (!userPhone.value) {
message.error('请先绑定手机号')
@@ -199,7 +213,10 @@ const handleSendVerificationCode = async () => {
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: userPhone.value }))
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: userPhone.value,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error: any) {
@@ -208,6 +225,7 @@ const handleSendVerificationCode = async () => {
}
}
/** handleSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSubmit = async () => {
if (!formRef.value) return
@@ -236,6 +254,7 @@ const handleSubmit = async () => {
}
}
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
@@ -116,6 +116,10 @@
</template>
<script setup lang="ts">
/**
* ProductDetailView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
@@ -152,22 +156,33 @@ const shopInfo = ref<ShopVO | null>(null)
const productImages = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const comments = ref<CommentVO[]>([])
/** commentText is a reactive state variable used by the template and event handlers. */
const commentText = ref('')
const replyTarget = ref<CommentVO | null>(null)
/** submittingComment is a reactive state variable used by the template and event handlers. */
const submittingComment = ref(false)
/** isFavorite is a reactive state variable used by the template and event handlers. */
const isFavorite = ref(false)
/** isLiked is a reactive state variable used by the template and event handlers. */
const isLiked = ref(false)
/** loadError is a reactive state variable used by the template and event handlers. */
const loadError = ref('')
/** isLoggedIn is a reactive state variable used by the template and event handlers. */
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
/** productTitle is a reactive state variable used by the template and event handlers. */
const productTitle = computed(() => product.value.title || product.value.name || '作品详情')
/** artistCount is a reactive state variable used by the template and event handlers. */
const artistCount = computed(() => {
if (typeof product.value.availableBookableArtistCount === 'number') return product.value.availableBookableArtistCount
return String(product.value.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean).length
})
/** artistCountText is a reactive state variable used by the template and event handlers. */
const artistCountText = computed(() => artistCount.value > 0 ? `${artistCount.value} 位` : (product.value.bookableArtistRestricted ? '暂无可约' : '门店安排'))
/** earliestBookableText is a reactive state variable used by the template and event handlers. */
const earliestBookableText = computed(() => shopInfo.value?.businessHours || '以门店安排为准')
/** requireLogin is a local helper used by this page script. */
const requireLogin = (actionText: string) => {
if (isLoggedIn.value) return true
message.info(`${actionText}前请先登录`)
@@ -175,6 +190,7 @@ const requireLogin = (actionText: string) => {
return false
}
/** loadProductImages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadProductImages = async () => {
const fileIds = product.value.imageFileIds?.split(',').map(id => id.trim()).filter(Boolean) || []
if (!fileIds.length) {
@@ -191,15 +207,18 @@ const loadProductImages = async () => {
productImages.value = urls.length ? urls : [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
}
/** 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(() => [])
}
/** 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) {
isFavorite.value = false
@@ -214,6 +233,7 @@ const checkInteractionStatus = async () => {
isLiked.value = Boolean(liked)
}
/** fetchProductDetail is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchProductDetail = async () => {
loadError.value = ''
try {
@@ -228,10 +248,12 @@ const fetchProductDetail = async () => {
}
}
/** openShopDetail is a local helper used by this page script. */
const openShopDetail = () => {
if (shopInfo.value?.id) router.push(`/shop/${shopInfo.value.id}`)
}
/** handleFavoriteClick is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleFavoriteClick = async () => {
if (!product.value.id || !requireLogin('收藏作品')) return
await runWithGlobalLoading(async () => {
@@ -248,6 +270,7 @@ const handleFavoriteClick = async () => {
}).catch((error: any) => message.error(error?.message || '收藏操作失败'))
}
/** handleLikeClick is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleLikeClick = async () => {
if (!product.value.id || !requireLogin('点赞作品')) return
await runWithGlobalLoading(async () => {
@@ -264,6 +287,7 @@ const handleLikeClick = async () => {
}).catch((error: any) => message.error(error?.message || '点赞操作失败'))
}
/** handleAddToCart is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleAddToCart = async () => {
if (!product.value.id || !requireLogin('加入购物车')) return
await runWithGlobalLoading(() => cartApi.addToCart({ productId: product.value.id, quantity: 1 }))
@@ -271,12 +295,14 @@ const handleAddToCart = async () => {
message.success('已加入购物车')
}
/** handleBuyNow is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBuyNow = async () => {
if (!product.value.id || !requireLogin('预约下单')) return
await handleAddToCart()
router.push('/cart')
}
/** submitComment is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submitComment = async () => {
if (!product.value.id || !requireLogin('发表评论')) return
const content = commentText.value.trim()
@@ -300,6 +326,7 @@ const submitComment = async () => {
}
}
/** formatTime is a local helper used by this page script. */
const formatTime = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : ''
onMounted(() => {
@@ -64,6 +64,7 @@
<div class="product-info">
<p class="name">{{ item.title || item.name }}</p>
<p v-if="item.shopName" class="shop-name">所属店铺:{{ item.shopName }}</p>
<div class="product-meta">
<span class="duration">{{ item.approximateDuration || '时长待定' }}</span>
<div class="stats">
@@ -128,6 +129,10 @@
</template>
<script setup lang="ts">
/**
* ProductListView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { onMounted, ref, watch, inject, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { CheckOutlined, LeftOutlined, SearchOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue'
@@ -149,17 +154,24 @@ const updateCartCount = inject<() => Promise<void>>('updateCartCount', async ()
const allTags = ref<TagVO[]>([])
const categories = ref<string[]>(['全部'])
/** selectedCategory is a reactive state variable used by the template and event handlers. */
const selectedCategory = ref('全部')
const products = ref<ProductListItem[]>([])
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** showSearch is a reactive state variable used by the template and event handlers. */
const showSearch = ref(false)
/** searchKeyword is a reactive state variable used by the template and event handlers. */
const searchKeyword = ref('')
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<string, string[]>>({})
/** cartProductIdSet is a reactive state variable used by the template and event handlers. */
const cartProductIdSet = ref(new Set<string>())
let useGlobalLoadingForNextRouteSync = false
/** isLoggedIn is a reactive state variable used by the template and event handlers. */
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
/** activeBannerText is a reactive state variable used by the template and event handlers. */
const activeBannerText = computed(() => {
if (searchKeyword.value.trim()) {
return `当前显示“${searchKeyword.value.trim()}”的匹配结果`
@@ -172,6 +184,7 @@ const activeBannerText = computed(() => {
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCBmaWxsPSIjZjVmNWY1IiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmaWxsPSIjYmZiZmJmIiBmb250LXNpemU9IjI0IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+YWFhPC90ZXh0Pjwvc3ZnPg=='
/** ensureLoginForAction is a local helper used by this page script. */
const ensureLoginForAction = (actionText: string) => {
if (isLoggedIn.value) {
return true
@@ -181,6 +194,7 @@ const ensureLoginForAction = (actionText: string) => {
return false
}
/** 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) {
@@ -208,8 +222,10 @@ const loadImageUrls = async (productList: ProductVO[]) => {
}
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: ProductVO): string[] => imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
/** markProductsInCart is a local helper used by this page script. */
const markProductsInCart = (productList: ProductVO[]) => {
return (Array.isArray(productList) ? productList : []).map(item => ({
...item,
@@ -217,6 +233,7 @@ const markProductsInCart = (productList: ProductVO[]) => {
}))
}
/** syncCartProductState is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const syncCartProductState = async () => {
if (!isLoggedIn.value) {
cartProductIdSet.value = new Set()
@@ -225,6 +242,7 @@ const syncCartProductState = async () => {
cartProductIdSet.value = await fetchCartProductIdSet()
}
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async () => {
try {
const response = await tagApi.getAllTags() as unknown as TagVO[]
@@ -236,6 +254,7 @@ const fetchTags = async () => {
}
}
/** fetchProducts is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchProducts = async () => {
loading.value = true
try {
@@ -261,6 +280,7 @@ const fetchProducts = async () => {
}
}
/** syncRouteFilters is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const syncRouteFilters = async () => {
await syncCartProductState()
const keyword = typeof route.query.keyword === 'string' ? route.query.keyword.trim() : ''
@@ -277,10 +297,12 @@ const syncRouteFilters = async () => {
await fetchProducts()
}
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.push('/home')
}
/** handleCategoryClick is a local helper used by this page script. */
const handleCategoryClick = (category: string) => {
selectedCategory.value = category
searchKeyword.value = ''
@@ -292,10 +314,12 @@ const handleCategoryClick = (category: string) => {
})
}
/** handleProductClick is a local helper used by this page script. */
const handleProductClick = (item: ProductVO) => {
router.push(`/product/${item.id}`)
}
/** handleAddToCart is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleAddToCart = async (item: ProductListItem) => {
if (!ensureLoginForAction('加入购物车')) {
return
@@ -316,6 +340,7 @@ const handleAddToCart = async (item: ProductListItem) => {
}
}
/** handleSearch is a local helper used by this page script. */
const handleSearch = () => {
const keyword = searchKeyword.value.trim()
useGlobalLoadingForNextRouteSync = true
@@ -325,6 +350,7 @@ const handleSearch = () => {
})
}
/** toggleSearch is a local helper used by this page script. */
const toggleSearch = () => {
showSearch.value = !showSearch.value
if (!showSearch.value) {
@@ -334,6 +360,7 @@ const toggleSearch = () => {
}
}
/** resetFilters is a local helper used by this page script. */
const resetFilters = () => {
selectedCategory.value = '全部'
searchKeyword.value = ''
@@ -483,6 +510,15 @@ onMounted(async () => {
text-overflow: ellipsis;
}
.shop-name {
margin: 0 0 6px;
font-size: 12px;
color: #7a5262;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-meta {
display: flex;
justify-content: space-between;
+98 -7
View File
@@ -59,7 +59,7 @@
<a-card :bordered="false" class="stats-card">
<a-row :gutter="16">
<a-col :span="8">
<div class="stat-item" @click="router.push('/orders')">
<div class="stat-item" @click="openOrders">
<div class="stat-icon orders">
<ShoppingOutlined />
</div>
@@ -88,7 +88,7 @@
<div class="menu-section">
<a-card :bordered="false" class="menu-card">
<a-list :data-source="coreMenuItems" :split="false">
<a-list :data-source="profileMenuItems" :split="false">
<template #renderItem="{ item }">
<a-list-item class="menu-item" @click="handleMenuClick(item.key)">
<template #actions>
@@ -190,9 +190,15 @@
</template>
<script setup lang="ts">
/**
* ProfileView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
BellOutlined,
CalendarOutlined,
CreditCardOutlined,
HeartOutlined,
RightOutlined,
@@ -227,17 +233,30 @@ const userInfo = ref<UserVO>({
updateTime: ''
})
/** editModalVisible is a reactive state variable used by the template and event handlers. */
const editModalVisible = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** needSetPassword is a reactive state variable used by the template and event handlers. */
const needSetPassword = ref(false)
/** hasNotification is a reactive state variable used by the template and event handlers. */
const hasNotification = ref(false)
/** unreadMessageCount is a reactive state variable used by the template and event handlers. */
const unreadMessageCount = ref(0)
/** orderCount is a reactive state variable used by the template and event handlers. */
const orderCount = ref(0)
/** couponCount is a reactive state variable used by the template and event handlers. */
const couponCount = ref(0)
/** wishlistCount is a reactive state variable used by the template and event handlers. */
const wishlistCount = ref(0)
/** shopSwitchVisible is a reactive state variable used by the template and event handlers. */
const shopSwitchVisible = ref(false)
/** shopSwitchLoading is a reactive state variable used by the template and event handlers. */
const shopSwitchLoading = ref(false)
const selectedShopId = ref<string>()
/** avatarUploadProgress is a reactive state variable used by the template and event handlers. */
const avatarUploadProgress = ref(0)
/** avatarUploadPending is a reactive state variable used by the template and event handlers. */
const avatarUploadPending = ref(false)
let avatarUploadTask: ChunkUploadTask<string> | null = null
const draftSavedAt = ref<number | null>(null)
@@ -248,14 +267,17 @@ const editForm = reactive({
signature: ''
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('profile-edit')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
nickname: editForm.nickname,
avatar: editForm.avatar,
signature: editForm.signature
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -267,6 +289,7 @@ const restoreDraft = () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
if (avatarUploadPending.value) {
message.warning('头像上传完成后才能暂存')
@@ -277,6 +300,7 @@ const handleSaveDraft = () => {
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -285,6 +309,7 @@ const handleClearDraft = (showMessage = true) => {
}
}
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => {
const ids = userInfo.value.shopIds || []
const names = userInfo.value.shopNames || []
@@ -294,7 +319,9 @@ const shopOptions = computed(() => {
}))
})
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => userInfo.value.shopName || '当前暂无可用门店')
/** shopSwitchTip is a reactive state variable used by the template and event handlers. */
const shopSwitchTip = computed(() => {
if (shopOptions.value.length > 1) {
return `可切换 ${shopOptions.value.length} 家门店`
@@ -313,6 +340,14 @@ const coreMenuItems = [
icon: ShoppingOutlined,
bgColor: '#e6f7ff'
},
{
key: 'artist-calendar',
title: '预约日历',
desc: '查看未来 7 天属于自己的预约',
icon: CalendarOutlined,
bgColor: '#fff7ed',
serviceOnly: true
},
{
key: 'wishlist',
title: '我的收藏',
@@ -327,6 +362,20 @@ const coreMenuItems = [
icon: CreditCardOutlined,
bgColor: '#fff7e6'
},
{
key: 'vip',
title: 'VIP 中心',
desc: '查看会员等级、余额和变动记录',
icon: CreditCardOutlined,
bgColor: '#f6f1e8'
},
{
key: 'notifications',
title: '消息通知',
desc: '查看店铺通知和系统消息',
icon: BellOutlined,
bgColor: '#eaf6ff'
},
{
key: 'settings',
title: '设置中心',
@@ -336,6 +385,19 @@ const coreMenuItems = [
}
]
/** profileMenuItems is a reactive state variable used by the template and event handlers. */
const profileMenuItems = computed(() => {
const userType = userInfo.value.type
return coreMenuItems.filter((item: any) => !item.serviceOnly || userType === 2 || userType === 3)
})
/** isServiceUser is a reactive state variable used by the template and event handlers. */
const isServiceUser = computed(() => {
const userType = userInfo.value.type
return userType === 2 || userType === 3
})
/** persistUserSession is a local helper used by this page script. */
const persistUserSession = (payload: any) => {
localStorage.setItem('accessToken', payload.accessToken)
localStorage.setItem('refreshToken', payload.refreshToken)
@@ -348,6 +410,7 @@ const persistUserSession = (payload: any) => {
}
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const response = await userApi.getUserInfo()
@@ -360,21 +423,32 @@ const fetchUserInfo = async () => {
}
}
/** loadCounts is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCounts = async () => {
try {
const [orders, coupons, wishlist] = await Promise.all([
orderApi.getOrderList(),
const orderListRequest = isServiceUser.value ? orderApi.getArtistOrders() : orderApi.getOrderList()
const [orders, coupons, wishlist, unreadMessages] = await Promise.all([
orderListRequest,
couponApi.listUserCoupons(),
wishlistApi.getWishlist()
wishlistApi.getWishlist(),
userApi.getMyUnreadMessageCount()
])
orderCount.value = Array.isArray(orders) ? orders.length : 0
couponCount.value = Array.isArray(coupons) ? coupons.length : 0
wishlistCount.value = Array.isArray(wishlist) ? wishlist.length : 0
unreadMessageCount.value = Number(unreadMessages?.unreadCount || 0)
hasNotification.value = unreadMessageCount.value > 0
} catch (error) {
console.error('加载个人中心统计失败:', error)
}
}
/** openOrders is a local helper used by this page script. */
const openOrders = () => {
router.push(isServiceUser.value ? '/artist-orders' : '/orders')
}
/** handleEditProfile is a local helper used by this page script. */
const handleEditProfile = () => {
avatarUploadTask?.cancel()
avatarUploadTask = null
@@ -400,6 +474,7 @@ const beforeUploadAvatar: UploadProps['beforeUpload'] = file => {
return isImage && isLt20M
}
/** handleAvatarUpload is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleAvatarUpload = async (options: any) => {
const { file, onProgress, onSuccess, onError } = options
@@ -445,6 +520,7 @@ const handleAvatarUpload = async (options: any) => {
}
}
/** handleDeleteAvatar is a local helper used by this page script. */
const handleDeleteAvatar = () => {
Modal.confirm({
title: '确认删除头像',
@@ -465,6 +541,7 @@ const handleDeleteAvatar = () => {
})
}
/** handleSaveProfile is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSaveProfile = async () => {
if (!editForm.nickname.trim()) {
message.error('请输入昵称')
@@ -497,6 +574,7 @@ const handleSaveProfile = async () => {
}
}
/** handleCancelEdit is a local helper used by this page script. */
const handleCancelEdit = () => {
avatarUploadTask?.cancel()
avatarUploadTask = null
@@ -505,6 +583,7 @@ const handleCancelEdit = () => {
editModalVisible.value = false
}
/** handleShopCardClick is a local helper used by this page script. */
const handleShopCardClick = () => {
if (shopOptions.value.length > 1) {
shopSwitchVisible.value = true
@@ -517,6 +596,7 @@ const handleShopCardClick = () => {
message.info('当前暂无可用门店')
}
/** handleConfirmSwitchShop is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleConfirmSwitchShop = async () => {
if (!selectedShopId.value) {
message.warning('请选择要切换的门店')
@@ -544,18 +624,26 @@ const handleConfirmSwitchShop = async () => {
}
}
/** handleMenuClick is a local helper used by this page script. */
const handleMenuClick = (key: string) => {
if (key === 'orders') {
router.push('/orders')
openOrders()
} else if (key === 'artist-calendar') {
router.push('/artist-calendar')
} else if (key === 'wishlist') {
router.push('/wishlist')
} else if (key === 'coupons') {
router.push('/coupons')
} else if (key === 'vip') {
router.push('/vip-center')
} else if (key === 'notifications') {
router.push('/notifications')
} else if (key === 'settings') {
router.push('/settings')
}
}
/** handleLogout is a local helper used by this page script. */
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
@@ -582,16 +670,19 @@ const handleLogout = () => {
})
}
/** handleSettingsClick is a local helper used by this page script. */
const handleSettingsClick = () => {
router.push('/settings')
}
/** handleSetPassword is a local helper used by this page script. */
const handleSetPassword = () => {
router.push('/settings/password')
}
onMounted(async () => {
await Promise.all([fetchUserInfo(), loadCounts()])
await fetchUserInfo()
await loadCounts()
})
</script>
@@ -46,6 +46,10 @@
</template>
<script setup lang="ts">
/**
* SettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
@@ -56,6 +60,7 @@ import {
const router = useRouter()
/** settingsSections is a reactive state variable used by the template and event handlers. */
const settingsSections = ref([
{
type: 'title',
@@ -70,10 +75,12 @@ const settingsSections = ref([
}
])
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
/** handleSettingClick is a local helper used by this page script. */
const handleSettingClick = (key: string) => {
if (key === 'account') {
router.push('/settings/account')
+119 -1
View File
@@ -24,6 +24,7 @@
{{ shopInfo.address }}
<span class="copy-icon">📋</span>
</p>
<p v-if="distanceText" class="shop-distance">{{ distanceText }}</p>
</div>
</div>
<div class="shop-details">
@@ -36,6 +37,14 @@
<div class="detail-value">{{ shopInfo.description }}</div>
</div>
</div>
<a-button class="contact-btn" type="primary" block @click="openManagerContact">
一键联系店长
</a-button>
<div v-if="hasLocation" class="map-actions">
<a-button block @click="openMapPreview">查看地图位置</a-button>
<a-button block @click="openNavigation('TENCENT')">腾讯地图导航</a-button>
<a-button block @click="openNavigation('AMAP')">高德地图导航</a-button>
</div>
<!-- 店铺环境图轮播 -->
<div class="shop-images" v-if="shopImages.length > 0">
<h3 class="section-title">店铺环境图</h3>
@@ -57,6 +66,14 @@
>
<img :src="selectedImage" alt="店铺环境图" class="modal-image" />
</a-modal>
<a-modal v-model:open="contactOpen" title="一键联系" :footer="null">
<div class="contact-box">
<p><strong>{{ contactInfo.contactName || contactInfo.roleLabel || '联系人' }}</strong></p>
<p>电话联系:{{ contactInfo.phoneAvailable ? contactInfo.phone : '暂无电话' }}</p>
<a-button v-if="contactInfo.phoneAvailable" type="primary" block :href="`tel:${contactInfo.phone}`">拨打电话</a-button>
<a-button block disabled>{{ contactInfo.platformContactText || '平台联系暂未接入' }}</a-button>
</div>
</a-modal>
</div>
</a-card>
</div>
@@ -64,12 +81,17 @@
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
/**
* ShopDetailView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { LeftOutlined, ShopOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { shopApi, type ShopVO } from '@/api/shop'
import { fileApi } from '@/api/file'
import { userApi, type ContactInfoVO } from '@/api/user'
import { toOptionalIdString } from '@/utils/id'
const router = useRouter()
@@ -80,6 +102,9 @@ const shopInfo = ref<ShopVO>({
shopName: '',
description: '',
address: '',
mapProvider: 'TENCENT',
longitude: '',
latitude: '',
businessHours: '',
imageFileIds: '',
createTime: '',
@@ -89,26 +114,94 @@ const shopInfo = ref<ShopVO>({
const shopImages = ref<string[]>([])
// 图片模态框
/** imageModalVisible is a reactive state variable used by the template and event handlers. */
const imageModalVisible = ref(false)
/** selectedImage is a reactive state variable used by the template and event handlers. */
const selectedImage = ref('')
/** contactOpen is a reactive state variable used by the template and event handlers. */
const contactOpen = ref(false)
const contactInfo = ref<ContactInfoVO>({})
const hasLocation = computed(() => Boolean(shopInfo.value.longitude && shopInfo.value.latitude))
const distanceText = ref('')
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
// 显示图片模态框
/** showImageModal is a local helper used by this page script. */
const showImageModal = (imageUrl: string) => {
selectedImage.value = imageUrl
imageModalVisible.value = true
}
// 关闭图片模态框
/** handleCancel is a local helper used by this page script. */
const handleCancel = () => {
imageModalVisible.value = false
selectedImage.value = ''
}
/** openManagerContact is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const openManagerContact = async () => {
try {
contactInfo.value = await userApi.getShopManagerContact(shopInfo.value.id)
contactOpen.value = true
} catch (error: any) {
message.error(error?.message || '获取联系方式失败')
}
}
const openMapPreview = () => {
const url = shopInfo.value.navigationUrls?.BROWSER || shopInfo.value.navigationUrls?.TENCENT
if (!url) {
message.warning('店铺暂未设置地图位置')
return
}
window.open(url, '_blank')
}
const openNavigation = (provider: 'TENCENT' | 'AMAP') => {
const url = shopInfo.value.navigationUrls?.[provider]
if (!url) {
message.warning('店铺暂未设置地图位置')
return
}
window.open(url, '_blank')
}
const calculateDistanceText = (currentLat: number, currentLng: number) => {
const shopLat = Number(shopInfo.value.latitude)
const shopLng = Number(shopInfo.value.longitude)
if (!Number.isFinite(currentLat) || !Number.isFinite(currentLng) || !Number.isFinite(shopLat) || !Number.isFinite(shopLng)) {
distanceText.value = ''
return
}
const toRad = (value: number) => value * Math.PI / 180
const earthRadius = 6371000
const dLat = toRad(shopLat - currentLat)
const dLng = toRad(shopLng - currentLng)
const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(currentLat)) * Math.cos(toRad(shopLat)) * Math.sin(dLng / 2) ** 2
const meters = 2 * earthRadius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
distanceText.value = meters >= 1000 ? `距你约 ${(meters / 1000).toFixed(1)} km` : `距你约 ${Math.round(meters)} m`
}
const loadCurrentDistance = () => {
if (!hasLocation.value || !navigator.geolocation) {
return
}
navigator.geolocation.getCurrentPosition(
position => calculateDistanceText(position.coords.latitude, position.coords.longitude),
() => {
distanceText.value = ''
},
{ enableHighAccuracy: false, timeout: 8000, maximumAge: 300000 }
)
}
// 复制到剪贴板
/** copyToClipboard is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const copyToClipboard = async (text: string, type: string) => {
try {
await navigator.clipboard.writeText(text)
@@ -119,6 +212,7 @@ const copyToClipboard = async (text: string, type: string) => {
}
}
/** loadShopImages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadShopImages = async () => {
try {
const imageFileIds = shopInfo.value.imageFileIds
@@ -147,6 +241,7 @@ const loadShopImages = async () => {
}
}
/** fetchShopDetail is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShopDetail = async () => {
try {
// 从路由参数或本地存储获取店铺ID
@@ -162,6 +257,7 @@ const fetchShopDetail = async () => {
// 加载店铺图片
await loadShopImages()
loadCurrentDistance()
} catch (error) {
message.error('获取店铺详情失败')
}
@@ -284,6 +380,12 @@ onMounted(() => {
margin: 0;
}
.shop-distance {
margin: 6px 0 0;
color: #7a5262;
font-size: 13px;
}
.copy-icon {
font-size: 12px;
margin-left: 6px;
@@ -303,6 +405,22 @@ onMounted(() => {
gap: 16px;
}
.contact-btn {
margin-top: 18px;
border-radius: 8px;
}
.map-actions {
display: grid;
gap: 10px;
margin-top: 12px;
}
.contact-box {
display: grid;
gap: 12px;
}
.detail-item {
display: flex;
flex-direction: column;
@@ -0,0 +1,171 @@
<template>
<div class="vip-center">
<header class="vip-header">
<button class="back-btn" type="button" @click="router.back()">‹</button>
<div>
<p>VIP 中心</p>
<h1>{{ asset?.vipLevel || '普通' }}</h1>
</div>
</header>
<main class="vip-main">
<section class="balance-panel">
<div>
<span>当前余额</span>
<strong>¥{{ money(asset?.balance) }}</strong>
</div>
<div>
<span>累计充值</span>
<strong>¥{{ money(asset?.totalRechargeAmount) }}</strong>
</div>
</section>
<a-button type="primary" size="large" block @click="rechargeOpen = true">
去充值 / 查看充值说明
</a-button>
<section class="vip-section">
<h2>会员信息</h2>
<div class="info-grid">
<div>
<span>等级</span>
<strong>{{ asset?.vipLevel || '普通' }}</strong>
</div>
<div>
<span>最近充值</span>
<strong>{{ formatTime(asset?.lastRechargeTime) }}</strong>
</div>
<div>
<span>生效时间</span>
<strong>{{ formatTime(asset?.vipStartTime) }}</strong>
</div>
<div>
<span>等级来源</span>
<strong>{{ asset?.manualOverride ? '后台指定' : '自动计算' }}</strong>
</div>
</div>
<p class="benefit">{{ asset?.benefitInfo || '暂无额外权益说明' }}</p>
</section>
<section class="vip-section">
<h2>余额变动</h2>
<a-spin :spinning="loading">
<div v-if="history.length" class="history-list">
<article v-for="item in history" :key="String(item.id)" class="history-row">
<div>
<strong>{{ sceneText(item.changeScene || item.type) }}</strong>
<span>{{ formatTime(item.changeTime) }}</span>
<em v-if="item.remark">{{ item.remark }}</em>
</div>
<b :class="{ income: Number(item.amount) > 0 }">
{{ Number(item.amount) > 0 ? '+' : '' }}¥{{ money(item.amount) }}
</b>
</article>
</div>
<a-empty v-else description="暂无余额变动" />
</a-spin>
</section>
</main>
<a-modal v-model:open="rechargeOpen" title="充值档位展示" :footer="null">
<div v-if="plans.length" class="plan-list">
<article v-for="plan in plans" :key="String(plan.id)" class="plan-card">
<div>
<strong>{{ plan.title }}</strong>
<span>{{ plan.vipLevel }}</span>
</div>
<b>充 {{ money(plan.rechargeAmount) }} 送 {{ money(plan.giftAmount) }}</b>
<p>{{ plan.description || '该档位仅展示,暂不发起支付。' }}</p>
</article>
</div>
<a-empty v-else description="暂无可展示充值档位" />
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* VipCenterView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { userApi, type BalanceHistoryItem, type UserAssetVO, type VipRechargePlanVO } from '@/api/user'
const router = useRouter()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const asset = ref<UserAssetVO | null>(null)
const history = ref<BalanceHistoryItem[]>([])
const plans = ref<VipRechargePlanVO[]>([])
/** rechargeOpen is a reactive state variable used by the template and event handlers. */
const rechargeOpen = ref(false)
/** money is a local helper used by this page script. */
const money = (value?: number | string) => Number(value || 0).toFixed(2)
/** formatTime is a local helper used by this page script. */
const formatTime = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '--'
/** sceneText is a local helper used by this page script. */
const sceneText = (scene?: string) => {
const map: Record<string, string> = {
MANUAL_RECHARGE: '手工充值',
MANUAL_DEDUCT: '手工扣减',
ORDER_PAY: '订单消费',
ORDER_REFUND: '订单退款',
RECHARGE: '充值',
CONSUME: '消费'
}
return map[scene || ''] || scene || '余额变动'
}
/** loadData is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadData = async () => {
loading.value = true
try {
const [assetRes, historyRes] = await Promise.all([
userApi.getMyAsset(),
userApi.getMyBalanceHistory()
])
asset.value = assetRes
history.value = historyRes || []
plans.value = await userApi.listMyVipRechargePlans().catch(() => [])
} catch (error: any) {
message.error(error?.message || '获取 VIP 信息失败')
} finally {
loading.value = false
}
}
onMounted(loadData)
</script>
<style scoped>
.vip-center { min-height: 100vh; background: #f6f7f9; color: #24242a; }
.vip-header { display: flex; gap: 16px; align-items: center; padding: 18px 18px 28px; color: #fff; background: linear-gradient(135deg, #2b2522, #896b48); }
.vip-header p { margin: 0 0 4px; opacity: .78; }
.vip-header h1 { margin: 0; font-size: 30px; font-weight: 700; }
.back-btn { width: 36px; height: 36px; border: 0; border-radius: 18px; background: rgba(255,255,255,.18); color: #fff; font-size: 28px; line-height: 1; }
.vip-main { padding: 16px; display: grid; gap: 14px; }
.balance-panel { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; overflow: hidden; border-radius: 8px; background: #e5e0d7; }
.balance-panel > div { padding: 18px; background: #fff; }
.balance-panel span, .info-grid span, .history-row span { display: block; color: #7a7d85; font-size: 12px; }
.balance-panel strong { display: block; margin-top: 8px; font-size: 24px; }
.vip-section { padding: 18px; border-radius: 8px; background: #fff; }
.vip-section h2 { margin: 0 0 14px; font-size: 17px; }
.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.info-grid strong { display: block; margin-top: 5px; font-size: 14px; }
.benefit { margin: 16px 0 0; padding-top: 14px; border-top: 1px solid #eef0f3; color: #5f626a; }
.history-list { display: grid; gap: 12px; }
.history-row { display: flex; justify-content: space-between; gap: 12px; padding-bottom: 12px; border-bottom: 1px solid #f0f1f3; }
.history-row:last-child { border-bottom: 0; padding-bottom: 0; }
.history-row em { display: block; margin-top: 4px; color: #9699a1; font-style: normal; font-size: 12px; }
.history-row b { color: #2f333a; white-space: nowrap; }
.history-row b.income { color: #0f8f63; }
.plan-list { display: grid; gap: 12px; }
.plan-card { padding: 14px; border-radius: 8px; border: 1px solid #eee2d6; background: #fffaf5; }
.plan-card div { display: flex; justify-content: space-between; gap: 12px; }
.plan-card span { color: #9a6a3b; }
.plan-card b { display: block; margin-top: 8px; font-size: 18px; }
.plan-card p { margin: 8px 0 0; color: #777; }
</style>
@@ -48,6 +48,10 @@
</template>
<script setup lang="ts">
/**
* WishlistView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, onMounted, inject } from 'vue'
import { ArrowLeft, Delete, StarFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
@@ -67,13 +71,16 @@ const updateCartCount = inject<() => Promise<void>>('updateCartCount', async ()
const wishlistItems = ref<WishlistItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<string, string[]>>({})
/** cartProductIdSet is a reactive state variable used by the template and event handlers. */
const cartProductIdSet = ref(new Set<string>())
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
/** fetchWishlist is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchWishlist = async () => {
try {
const [response, nextCartProductIdSet] = await Promise.all([
@@ -89,6 +96,7 @@ 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) {
@@ -119,12 +127,15 @@ const loadImageUrls = async (items: WishlistItem[]) => {
}
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: any): string[] => {
return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
}
/** isProductInCart is a local helper used by this page script. */
const isProductInCart = (productId: IdType) => hasCartProduct(cartProductIdSet.value, productId)
/** handleAddToCart is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleAddToCart = async (productId: IdType) => {
if (isProductInCart(productId)) {
ElMessage.info('购物车已有')
@@ -142,6 +153,7 @@ const handleAddToCart = async (productId: IdType) => {
}
}
/** handleRemoveItem is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRemoveItem = async (productId: IdType) => {
try {
await runWithGlobalLoading(() => wishlistApi.removeFromWishlist(productId))
@@ -153,14 +165,17 @@ const handleRemoveItem = async (productId: IdType) => {
}
}
/** handleBrowseProducts is a local helper used by this page script. */
const handleBrowseProducts = () => {
router.push('/products')
}
/** handleProductClick is a local helper used by this page script. */
const handleProductClick = (productId: IdType) => {
router.push(`/product/${productId}`)
}
/** getRandomColor is a local helper used by this page script. */
const getRandomColor = () => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)]
@@ -200,6 +200,10 @@
</template>
<script setup lang="ts">
/**
* AdminLayout page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
@@ -245,11 +249,14 @@ const router = useRouter()
const route = useRoute()
const { isMobile } = useAdminViewport()
/** collapsed is a reactive state variable used by the template and event handlers. */
const collapsed = ref(false)
/** mobileDrawerOpen is a reactive state variable used by the template and event handlers. */
const mobileDrawerOpen = ref(false)
const userInfo = ref<UserVO | null>(null)
const selectedKeys = ref<string[]>([route.path])
const selectedShopId = ref<string>()
/** shopSwitchLoading is a reactive state variable used by the template and event handlers. */
const shopSwitchLoading = ref(false)
const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission()
@@ -265,6 +272,12 @@ const menuItems: AdminMenuItem[] = [
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' },
{ key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order: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 mobileTabs = [
@@ -274,11 +287,19 @@ const mobileTabs = [
{ key: 'profile', label: '我的', path: '/admin/profile', icon: UserOutlined }
]
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** isShopAuthorizationExpired is a reactive state variable used by the template and event handlers. */
const isShopAuthorizationExpired = computed(() => Boolean(userInfo.value?.shopAuthorizationExpired))
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => getAdminShopOptions(userInfo.value))
/** shopSelectOptions is a reactive state variable used by the template and event handlers. */
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
/** roleLabel is a reactive state variable used by the template and event handlers. */
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
/** shopScopeText is a reactive state variable used by the template and event handlers. */
const shopScopeText = computed(() => {
if (!shopOptions.value.length) {
return '游客模式'
@@ -286,6 +307,7 @@ const shopScopeText = computed(() => {
return `可登录门店:${shopOptions.value.map(shop => shop.name).join(' / ')}`
})
/** filteredMenuItems is a reactive state variable used by the template and event handlers. */
const filteredMenuItems = computed(() => {
userPermissions.value
let visibleItems = menuItems.filter(item => {
@@ -300,9 +322,13 @@ const filteredMenuItems = computed(() => {
if (isBootstrapAdmin.value) {
visibleItems = visibleItems.filter(item => item.key === '/admin' || item.key === '/admin/shops')
}
if (isShopAuthorizationExpired.value && userInfo.value?.type !== 4) {
visibleItems = visibleItems.filter(item => item.key === '/admin')
}
return visibleItems
})
/** activeMobileTab is a reactive state variable used by the template and event handlers. */
const activeMobileTab = computed(() => {
if (route.path === '/admin' || route.path === '/admin/dashboard') {
return 'workbench'
@@ -329,6 +355,7 @@ const activeMobileTab = computed(() => {
return 'workbench'
})
/** currentMobileSectionLabel is a reactive state variable used by the template and event handlers. */
const currentMobileSectionLabel = computed(() => {
switch (activeMobileTab.value) {
case 'orders':
@@ -342,6 +369,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)
if (currentMenu) {
@@ -356,6 +384,7 @@ const currentMobileTitle = computed(() => {
return '后台管理'
})
/** persistAdminSession is a local helper used by this page script. */
const persistAdminSession = (payload: any) => {
localStorage.setItem('adminAccessToken', payload.accessToken)
localStorage.setItem('adminRefreshToken', payload.refreshToken)
@@ -363,29 +392,47 @@ const persistAdminSession = (payload: any) => {
sessionStorage.setItem('adminAccessToken', payload.accessToken)
}
/** toggleCollapsed is a local helper used by this page script. */
const toggleCollapsed = () => {
collapsed.value = !collapsed.value
}
/** handleMenuClick is a local helper used by this page script. */
const handleMenuClick = (info: any) => {
if (isShopAuthorizationExpired.value && userInfo.value?.type !== 4 && info.key !== '/admin') {
message.warning('授权已到期,请联系管理员')
return
}
router.push(info.key)
}
/** openPathFromDrawer is a local helper used by this page script. */
const openPathFromDrawer = (path: string) => {
if (isShopAuthorizationExpired.value && userInfo.value?.type !== 4 && path !== '/admin' && path !== '/admin/profile') {
message.warning('授权已到期,请联系管理员')
return
}
mobileDrawerOpen.value = false
router.push(path)
}
/** openProfileFromDrawer is a local helper used by this page script. */
const openProfileFromDrawer = () => {
openPathFromDrawer('/admin/profile')
}
/** handleMobileTabClick is a local helper used by this page script. */
const handleMobileTabClick = (path: string) => {
if (isShopAuthorizationExpired.value && userInfo.value?.type !== 4 && path !== '/admin' && path !== '/admin/profile') {
message.warning('授权已到期,请联系管理员')
return
}
if (route.path !== path) {
router.push(path)
}
}
/** handleLogout is a local helper used by this page script. */
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
@@ -416,6 +463,7 @@ const handleLogout = () => {
})
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const cache = localStorage.getItem('adminUserInfo')
@@ -431,6 +479,7 @@ const fetchUserInfo = async () => {
}
}
/** handleShopChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleShopChange = async (shopId: unknown) => {
if (typeof shopId !== 'string' && typeof shopId !== 'number') {
return
@@ -77,6 +77,10 @@
</template>
<script setup lang="ts">
/**
* AdminLoginView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
@@ -90,10 +94,14 @@ import { runWithGlobalLoading } from '@/utils/action-loading'
const router = useRouter()
const formRef = ref<FormInstance>()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** shopLoading is a reactive state variable used by the template and event handlers. */
const shopLoading = ref(false)
const shops = ref<Array<{ id: IdType; shopName: string }>>([])
/** allowShoplessLogin is a reactive state variable used by the template and event handlers. */
const allowShoplessLogin = ref(false)
/** loginShopMessage is a reactive state variable used by the template and event handlers. */
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
@@ -104,6 +112,7 @@ const formState = reactive({
})
let loginShopTimer: number | undefined
/** handleAccountInput is a local helper used by this page script. */
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
@@ -111,17 +120,23 @@ const handleAccountInput = () => {
}
}
/** getShopIdValue is a local helper used by this page script. */
const getShopIdValue = (shop: { id: IdType; shopName: string }) => String(shop.id ?? '')
/** getShopLabel is a local helper used by this page script. */
const getShopLabel = (shop: { id: IdType; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() =>
shops.value.map(shop => ({
label: getShopLabel(shop),
value: getShopIdValue(shop)
}))
)
/** hasAvailableShops is a reactive state variable used by the template and event handlers. */
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
/** shouldRequireShop is a reactive state variable used by the template and event handlers. */
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
/** shopPlaceholder is a reactive state variable used by the template and event handlers. */
const shopPlaceholder = computed(() => {
if (allowShoplessLogin.value) {
return '当前无需选择店铺'
@@ -152,14 +167,17 @@ const formRules = {
}]
} as any
/** filterShopOption is a local helper used by this page script. */
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
/** isLoginShopPrefetchUnsupported is a local helper used by this page script. */
const isLoginShopPrefetchUnsupported = (error: unknown) => {
const status = (error as any)?.response?.status
return status === 404
}
/** resetLoginShopTimer is a local helper used by this page script. */
const resetLoginShopTimer = () => {
if (loginShopTimer !== undefined) {
window.clearTimeout(loginShopTimer)
@@ -167,6 +185,7 @@ const resetLoginShopTimer = () => {
}
}
/** restoreLoginShop is a local helper used by this page script. */
const restoreLoginShop = () => {
const cached = localStorage.getItem('adminUserInfo')
if (!cached) {
@@ -182,6 +201,7 @@ const restoreLoginShop = () => {
}
}
/** applyLoginShopSelection is a local helper used by this page script. */
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
shops.value = selection?.shops || []
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
@@ -210,6 +230,7 @@ const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null)
formState.shopId = undefined
}
/** loadLoginShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadLoginShops = async (account = formState.account) => {
const trimmedAccount = account.trim()
if (!trimmedAccount) {
@@ -244,6 +265,7 @@ const loadLoginShops = async (account = formState.account) => {
}
}
/** handleLogin is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleLogin = async () => {
try {
await formRef.value?.validate()
@@ -304,6 +326,7 @@ onBeforeUnmount(() => {
resetLoginShopTimer()
})
/** goToFrontend is a local helper used by this page script. */
const goToFrontend = () => {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
@@ -0,0 +1,156 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>公告管理</h2>
<p>发布后会在用户首页顶部持续滚动展示。</p>
</div>
<a-button type="primary" @click="openCreate">发布公告</a-button>
</div>
<a-table :columns="columns" :data-source="announcements" :loading="loading" row-key="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'content'">
<span class="ellipsis">{{ record.content }}</span>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'green' : 'default'">{{ record.status === 1 ? '已发布' : '已撤回' }}</a-tag>
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button size="small" @click="preview(record as AnnouncementVO)">查看</a-button>
<a-button v-if="record.status === 1" size="small" danger @click="revoke(record.id)">撤回</a-button>
</a-space>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" title="发布公告" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="标题">
<a-input v-model:value="form.title" :maxlength="100" />
</a-form-item>
<a-form-item label="内容">
<a-textarea v-model:value="form.content" :rows="4" :maxlength="1000" />
</a-form-item>
<a-form-item label="接收范围">
<a-select v-model:value="form.targetType" :options="targetOptions" />
</a-form-item>
<a-form-item v-if="needsShop" label="指定店铺">
<a-select v-model:value="form.shopIds" mode="multiple" :options="shopOptions" />
</a-form-item>
<a-form-item v-if="needsUser" label="指定用户">
<a-select v-model:value="form.userIds" mode="multiple" show-search option-filter-prop="label" :options="userOptions" />
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="form.sortOrder" style="width: 100%" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* AnnouncementsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { adminAnnouncementApi, type AnnouncementVO, type MessageTargetOptionsVO } from '@/api/admin'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
const announcements = ref<AnnouncementVO[]>([])
const options = ref<MessageTargetOptionsVO>({ shops: [], users: [] })
const form = reactive<any>({ title: '', content: '', targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 })
const columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '内容', dataIndex: 'content', key: 'content' },
{ title: '发布人', dataIndex: 'publisherName', key: 'publisherName' },
{ title: '范围', dataIndex: 'targetTypeName', key: 'targetTypeName' },
{ title: '状态', dataIndex: 'status', key: 'status' },
{ title: '发布时间', dataIndex: 'publishTime', key: 'publishTime' },
{ title: '操作', key: 'action', width: 150 }
]
const targetOptions = [
{ label: '全平台', value: 'PLATFORM_ALL' },
{ label: '当前门店全部用户', value: 'CURRENT_SHOP_ALL' },
{ label: '指定门店全部用户', value: 'SELECTED_SHOPS' },
{ label: '指定用户', value: 'SELECTED_USERS' }
]
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => options.value.shops.map(item => ({ label: item.shopName, value: item.id })))
/** userOptions is a reactive state variable used by the template and event handlers. */
const userOptions = computed(() => options.value.users.map(item => ({ label: `${item.nickname || item.account} ${item.shopName ? `(${item.shopName})` : ''}`, value: item.id })))
/** needsShop is a reactive state variable used by the template and event handlers. */
const needsShop = computed(() => ['SHOP_ALL', 'SELECTED_SHOPS'].includes(form.targetType))
/** needsUser is a reactive state variable used by the template and event handlers. */
const needsUser = computed(() => form.targetType === 'SELECTED_USERS')
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [list, target] = await Promise.all([
adminAnnouncementApi.listAnnouncements(),
adminAnnouncementApi.getTargetOptions().catch(() => ({ shops: [], users: [] }))
])
announcements.value = list || []
options.value = target
} finally {
loading.value = false
}
}
/** openCreate is a local helper used by this page script. */
const openCreate = () => {
Object.assign(form, { title: '', content: '', targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 })
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.title || !form.content) {
message.warning('请填写标题和内容')
return
}
saving.value = true
try {
await adminAnnouncementApi.createAnnouncement(form)
message.success('公告已发布')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** preview is a local helper used by this page script. */
const preview = (record: AnnouncementVO) => {
Modal.info({ title: record.title, content: record.content })
}
/** revoke is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const revoke = async (id: any) => {
await adminAnnouncementApi.revokeAnnouncement(id)
message.success('公告已撤回')
await load()
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p { margin: 0; color: #7a6f68; }
.ellipsis { display: inline-block; max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; }
</style>
@@ -33,12 +33,18 @@
</template>
<script setup lang="ts">
/**
* CommentsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminCommentApi, type AdminCommentVO } from '@/api/admin'
import type { IdType } from '@/utils/id'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** keyword is a reactive state variable used by the template and event handlers. */
const keyword = ref('')
const comments = ref<AdminCommentVO[]>([])
@@ -51,6 +57,7 @@ const columns = [
{ title: '操作', key: 'action', width: 100 }
]
/** loadComments is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadComments = async () => {
loading.value = true
try {
@@ -62,6 +69,7 @@ const loadComments = async () => {
}
}
/** deleteComment is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const deleteComment = async (id: IdType) => {
await adminCommentApi.deleteComment(id)
message.success('评论已删除')
@@ -240,11 +240,11 @@
</a-form-item>
<a-form-item label="开始时间" name="startTime">
<a-date-picker v-model:value="formState.startTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
<a-date-picker v-model:value="formState.startTime" show-time format="YYYY-MM-DD HH:mm:ss" popup-class-name="yumi-date-picker-panel yumi-date-time-panel" style="width: 100%" />
</a-form-item>
<a-form-item label="结束时间" name="endTime">
<a-date-picker v-model:value="formState.endTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
<a-date-picker v-model:value="formState.endTime" show-time format="YYYY-MM-DD HH:mm:ss" popup-class-name="yumi-date-picker-panel yumi-date-time-panel" style="width: 100%" />
</a-form-item>
<a-form-item label="可用标签" name="availableTagIds">
@@ -331,6 +331,10 @@
</template>
<script setup lang="ts">
/**
* CouponsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
@@ -358,6 +362,7 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** currentUserInfo is a local helper used by this page script. */
const currentUserInfo = (() => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
@@ -386,12 +391,19 @@ interface CouponFormState {
autoMatch: number
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
const formRef = ref<FormInstance>()
const distributeFormRef = ref<FormInstance>()
@@ -402,7 +414,9 @@ const tagList = ref<Tag[]>([])
const userList = ref<UserVO[]>([])
const shops = ref<Shop[]>([])
/** distributeModalVisible is a reactive state variable used by the template and event handlers. */
const distributeModalVisible = ref(false)
/** distributeLoading is a reactive state variable used by the template and event handlers. */
const distributeLoading = ref(false)
const currentDistributeCoupon = ref<Coupon | null>(null)
@@ -469,8 +483,10 @@ const columns = [
{ title: '操作', key: 'actions', width: 180, fixed: 'right' as const }
]
/** isVipAutoForm is a reactive state variable used by the template and event handlers. */
const isVipAutoForm = computed(() => formState.couponScene === 'VIP_AUTO' || formState.autoMatch === 1)
/** getStatusColor is a local helper used by this page script. */
const getStatusColor = (status: number) => {
switch (status) {
case 1:
@@ -484,6 +500,7 @@ const getStatusColor = (status: number) => {
}
}
/** getCouponSceneText is a local helper used by this page script. */
const getCouponSceneText = (scene?: string) => {
if (scene === 'VIP_AUTO') {
return 'VIP 自动券'
@@ -491,8 +508,10 @@ const getCouponSceneText = (scene?: string) => {
return '普通券'
}
/** isVipAutoCoupon is a local helper used by this page script. */
const isVipAutoCoupon = (coupon: any) => coupon?.couponScene === 'VIP_AUTO' || coupon?.autoMatch === 1
/** getCouponValueText is a local helper used by this page script. */
const getCouponValueText = (coupon: Coupon | null) => {
if (!coupon) {
return '-'
@@ -502,6 +521,7 @@ const getCouponValueText = (coupon: Coupon | null) => {
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
/** resetFormState is a local helper used by this page script. */
const resetFormState = () => {
Object.assign(formState, {
couponCode: '',
@@ -522,8 +542,10 @@ const resetFormState = () => {
})
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-coupons', isEdit.value ? 'edit' : 'create', currentCoupon.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
@@ -542,6 +564,7 @@ const buildDraftPayload = () => ({
autoMatch: formState.autoMatch
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -558,12 +581,14 @@ const restoreDraft = () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -587,11 +612,13 @@ watch(
}
)
/** handleAutoMatchChange is a local helper used by this page script. */
const handleAutoMatchChange = (checked: boolean) => {
formState.autoMatch = checked ? 1 : 0
formState.couponScene = checked ? 'VIP_AUTO' : 'GENERAL'
}
/** fetchCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCoupons = async () => {
loading.value = true
try {
@@ -611,6 +638,7 @@ const fetchCoupons = async () => {
}
}
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async () => {
try {
const tags = await adminTagApi.listAllTags() as unknown as Tag[]
@@ -620,6 +648,7 @@ const fetchTags = async () => {
}
}
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
loadingShops.value = true
try {
@@ -632,6 +661,7 @@ const fetchShops = async () => {
}
}
/** fetchUsers is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUsers = async () => {
try {
const params: Record<string, unknown> = { page: 1, size: 200 }
@@ -646,16 +676,19 @@ const fetchUsers = async () => {
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchCoupons())
}
/** handleTableChange is a local helper used by this page script. */
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentCoupon.value = null
@@ -664,6 +697,7 @@ const showAddModal = () => {
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentCoupon.value = record
@@ -688,11 +722,13 @@ const showEditModal = (record: any) => {
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
currentCoupon.value = record
viewModalVisible.value = true
}
/** buildCouponPayload is a local helper used by this page script. */
const buildCouponPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
@@ -711,6 +747,7 @@ const buildCouponPayload = () => ({
autoMatch: isVipAutoForm.value ? 1 : 0
})
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
@@ -739,12 +776,14 @@ const handleModalOk = async () => {
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
resetFormState()
}
/** handleDelete is a local helper used by this page script. */
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
@@ -764,6 +803,7 @@ const handleDelete = (record: any) => {
})
}
/** showDistributeModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showDistributeModal = async (record: any) => {
currentDistributeCoupon.value = record
distributeFormState.couponName = record.couponName
@@ -773,6 +813,7 @@ const showDistributeModal = async (record: any) => {
distributeModalVisible.value = true
}
/** handleDistributeOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDistributeOk = async () => {
if (!currentDistributeCoupon.value) {
return
@@ -803,6 +844,7 @@ const handleDistributeOk = async () => {
}
}
/** handleDistributeCancel is a local helper used by this page script. */
const handleDistributeCancel = () => {
distributeModalVisible.value = false
distributeFormRef.value?.resetFields()
@@ -106,6 +106,10 @@
</template>
<script setup lang="ts">
/**
* DashboardView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { HomeOutlined, ShopOutlined, ShoppingOutlined, UserOutlined } from '@ant-design/icons-vue'
@@ -113,6 +117,7 @@ import { adminDashboardApi, type DashboardStats } from '@/api/admin'
import { useAdminViewport } from '@/composables/useAdminViewport'
const { isMobile } = useAdminViewport()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const stats = reactive<DashboardStats>({
totalUsers: 0,
@@ -123,6 +128,7 @@ const stats = reactive<DashboardStats>({
recentActivities: []
})
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const cache = localStorage.getItem('adminUserInfo')
@@ -133,8 +139,11 @@ const getCurrentUserInfo = () => {
}
}
/** currentUser is a reactive state variable used by the template and event handlers. */
const currentUser = computed(() => getCurrentUserInfo())
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = computed(() => currentUser.value?.type === 4)
/** pageSubtitle is a reactive state variable used by the template and event handlers. */
const pageSubtitle = computed(() => {
if (isAdmin.value) {
return stats.totalShops > 0 ? '查看整体经营情况与各门店动态' : '当前还没有门店,先去店铺管理创建第一家门店'
@@ -142,6 +151,7 @@ const pageSubtitle = computed(() => {
return currentUser.value?.shopName ? `当前门店:${currentUser.value.shopName}` : '当前还没有选中门店'
})
/** insightItems is a reactive state variable used by the template and event handlers. */
const insightItems = computed(() => {
const items = []
if (isAdmin.value && stats.totalShops === 0) {
@@ -181,6 +191,7 @@ const insightItems = computed(() => {
return items
})
/** formatTime is a local helper used by this page script. */
const formatTime = (timeStr: string) => {
if (!timeStr) return ''
const time = new Date(timeStr)
@@ -198,6 +209,7 @@ const formatTime = (timeStr: string) => {
return time.toLocaleDateString('zh-CN')
}
/** fetchStats is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchStats = async () => {
loading.value = true
try {
@@ -12,6 +12,15 @@
description="系统里还没有可用店铺。当前账号已允许登录后台先创建第一家店铺,其他后台模块会保持不可用,创建完成后请重新登录并选择店铺。"
/>
<a-alert
v-if="isShopAuthorizationExpired"
class="bootstrap-alert"
type="error"
show-icon
message="授权已到期,请联系管理员"
description="当前店铺已超过授权有效期,后台业务功能已暂时禁用。"
/>
<a-card class="time-card">
<a-statistic title="当前时间" :value="currentTime" />
</a-card>
@@ -140,6 +149,10 @@
</template>
<script setup lang="ts">
/**
* HomeView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { DashboardOutlined, HomeOutlined, SafetyCertificateOutlined, ShopOutlined, UserOutlined } from '@ant-design/icons-vue'
@@ -152,11 +165,13 @@ import { isBootstrapAdminUser } from './admin-helpers'
const router = useRouter()
const { isMobile } = useAdminViewport()
/** currentTime is a reactive state variable used by the template and event handlers. */
const currentTime = ref('')
const userInfo = ref<UserVO | null>(null)
const userPermissions = ref<PermissionVO[]>([])
let timer: number | null = null
/** welcomeMessage is a reactive state variable used by the template and event handlers. */
const welcomeMessage = computed(() => {
const hour = new Date().getHours()
if (hour < 12) {
@@ -168,8 +183,12 @@ const welcomeMessage = computed(() => {
}
})
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** isShopAuthorizationExpired is a reactive state variable used by the template and event handlers. */
const isShopAuthorizationExpired = computed(() => Boolean(userInfo.value?.shopAuthorizationExpired) && userInfo.value?.type !== 4)
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
userPermissions.value.forEach(permission => {
@@ -182,7 +201,11 @@ const groupedPermissions = computed(() => {
return groups
})
/** quickActions is a reactive state variable used by the template and event handlers. */
const quickActions = computed(() => {
if (isShopAuthorizationExpired.value) {
return []
}
const actions = [
{
key: 'dashboard',
@@ -225,6 +248,7 @@ const quickActions = computed(() => {
return actions.filter(item => grantedPermissions.has(item.permissionCode))
})
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number | undefined) => {
switch (type) {
case 4:
@@ -238,6 +262,7 @@ const getUserTypeText = (type: number | undefined) => {
}
}
/** updateCurrentTime is a local helper used by this page script. */
const updateCurrentTime = () => {
const now = new Date()
currentTime.value = now.toLocaleString('zh-CN', {
@@ -250,6 +275,7 @@ const updateCurrentTime = () => {
})
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
@@ -264,6 +290,7 @@ const fetchUserInfo = async () => {
}
}
/** fetchUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserPermissions = async () => {
try {
const res = await permissionApi.getUserPermissions()
@@ -273,6 +300,7 @@ const fetchUserPermissions = async () => {
}
}
/** navigateTo is a local helper used by this page script. */
const navigateTo = (path: string, permissionCode?: string) => {
if (permissionCode) {
const hasPermission = userPermissions.value.some(p => p.permissionCode === permissionCode)
@@ -0,0 +1,153 @@
<template>
<div class="admin-page">
<div class="page-header">
<div>
<h2>协议管理</h2>
<p>维护用户登录/注册前需要阅读并同意的用户协议和隐私政策。</p>
</div>
<a-button type="primary" @click="openCreate">新增协议</a-button>
</div>
<a-table :columns="columns" :data-source="agreements" :loading="loading" row-key="id" bordered>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'green' : 'default'">{{ record.statusText || (record.status === 1 ? '已发布' : '草稿/停用') }}</a-tag>
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button size="small" @click="openEdit(record)">编辑</a-button>
<a-button size="small" type="primary" :disabled="record.status === 1" @click="publishAgreement(record.id)">发布</a-button>
<a-button size="small" danger :disabled="record.status !== 1" @click="disableAgreement(record.id)">停用</a-button>
</a-space>
</template>
</template>
</a-table>
<a-modal
v-model:open="modalOpen"
:title="editingId ? '编辑协议' : '新增协议'"
width="760px"
:confirm-loading="saving"
@ok="saveAgreement"
>
<a-form layout="vertical">
<a-form-item label="协议类型">
<a-select v-model:value="form.agreementType">
<a-select-option value="USER_TERMS">用户协议</a-select-option>
<a-select-option value="PRIVACY_POLICY">隐私政策</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="标题">
<a-input v-model:value="form.title" placeholder="例如:YumiNail 用户协议" />
</a-form-item>
<a-form-item label="版本">
<a-input v-model:value="form.version" placeholder="例如:2026-05-18" />
</a-form-item>
<a-form-item label="内容">
<a-textarea v-model:value="form.content" :rows="12" placeholder="请输入协议正文" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminLegalAgreementApi, type LegalAgreementAdminVO } from '@/api/admin'
import type { IdType } from '@/utils/id'
const loading = ref(false)
const saving = ref(false)
const modalOpen = ref(false)
const editingId = ref<IdType | null>(null)
const agreements = ref<LegalAgreementAdminVO[]>([])
const form = reactive({
agreementType: 'USER_TERMS' as 'USER_TERMS' | 'PRIVACY_POLICY',
title: '',
version: '',
content: ''
})
const columns = [
{ title: '类型', dataIndex: 'agreementTypeName', key: 'agreementTypeName' },
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '版本', dataIndex: 'version', key: 'version' },
{ title: '状态', dataIndex: 'status', key: 'status' },
{ title: '生效时间', dataIndex: 'effectiveTime', key: 'effectiveTime' },
{ title: '操作', key: 'action', width: 220 }
]
const loadAgreements = async () => {
loading.value = true
try {
agreements.value = await adminLegalAgreementApi.list() as unknown as LegalAgreementAdminVO[]
} finally {
loading.value = false
}
}
const resetForm = () => {
editingId.value = null
form.agreementType = 'USER_TERMS'
form.title = ''
form.version = ''
form.content = ''
}
const openCreate = () => {
resetForm()
modalOpen.value = true
}
const openEdit = (record: Record<string, any>) => {
const agreement = record as LegalAgreementAdminVO
editingId.value = agreement.id
form.agreementType = agreement.agreementType
form.title = agreement.title
form.version = agreement.version
form.content = agreement.content
modalOpen.value = true
}
const saveAgreement = async () => {
if (!form.title || !form.version || !form.content) {
message.warning('请填写完整协议信息')
return
}
saving.value = true
try {
if (editingId.value) {
await adminLegalAgreementApi.update(editingId.value, { ...form })
} else {
await adminLegalAgreementApi.create({ ...form })
}
message.success('保存成功')
modalOpen.value = false
await loadAgreements()
} finally {
saving.value = false
}
}
const publishAgreement = async (id: IdType) => {
await adminLegalAgreementApi.publish(id)
message.success('发布成功')
await loadAgreements()
}
const disableAgreement = async (id: IdType) => {
await adminLegalAgreementApi.disable(id)
message.success('已停用')
await loadAgreements()
}
onMounted(loadAgreements)
</script>
<style scoped>
.admin-page { padding: 16px; }
.page-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 16px; }
.page-header h2 { margin: 0 0 6px; }
.page-header p { margin: 0; color: #8c8c8c; }
</style>
@@ -40,6 +40,10 @@
</template>
<script setup lang="ts">
/**
* ManageView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
@@ -64,11 +68,16 @@ import {
const router = useRouter()
const { hasPermission, loadUserPermissions } = usePermission()
/** userInfo is a reactive state variable used by the template and event handlers. */
const userInfo = computed(() => loadCachedAdminUserInfo())
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
/** roleLabel is a reactive state variable used by the template and event handlers. */
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** visibleModules is a reactive state variable used by the template and event handlers. */
const visibleModules = computed(() => {
const definitions = [
{
@@ -160,6 +169,7 @@ const visibleModules = computed(() => {
})
})
/** openModule is a local helper used by this page script. */
const openModule = (module: any) => {
if (!module.allowed) {
message.warning(module.disabledReason || '当前无法进入该模块')
@@ -0,0 +1,292 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>参数管理</h2>
<p>统一维护地图 Key、短信 MessageHub 对接参数等平台级配置,仅平台管理员可修改。</p>
</div>
<a-button type="primary" @click="openCreate">新增配置</a-button>
</div>
<a-card title="地图服务配置" :bordered="false">
<a-form layout="vertical">
<a-form-item label="腾讯位置服务 Key">
<a-input-password v-model:value="mapForm.configValue" placeholder="请输入腾讯位置服务 Key" />
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="mapForm.remark" :rows="2" placeholder="例如:用于后台店铺选点和腾讯地图展示" />
</a-form-item>
<a-form-item>
<a-space>
<a-switch v-model:checked="mapEnabled" checked-children="启用" un-checked-children="停用" />
<a-button type="primary" :loading="savingMap" @click="saveMapConfig">保存地图配置</a-button>
</a-space>
</a-form-item>
</a-form>
</a-card>
<a-alert
type="info"
show-icon
message="这里不配置 Spug、阿里云等供应商密钥;真实短信通道仍在 MessageHub 中独立管理。"
/>
<a-table :columns="columns" :data-source="configs" :loading="loading" row-key="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'scene'">
<strong>{{ record.sceneName }}</strong>
<div class="muted">{{ record.sceneCode }}</div>
</template>
<template v-else-if="column.key === 'messagehub'">
<div>队列:{{ record.queueName }}</div>
<div class="muted">来源:{{ record.sourceSystem }}</div>
</template>
<template v-else-if="column.key === 'template'">
<div>{{ record.templateCode }}</div>
<div class="muted">通道ID:{{ record.channelId || '由 MessageHub 自动选择' }}</div>
</template>
<template v-else-if="column.key === 'enabled'">
<a-switch :checked="record.enabled === 1" @change="checked => toggleStatus(record as MessageHubPushConfigVO, Boolean(checked))" />
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button size="small" @click="openEdit(record as MessageHubPushConfigVO)">编辑</a-button>
<a-button size="small" @click="openTest(record as MessageHubPushConfigVO)">测试</a-button>
</a-space>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" :title="editingId ? '编辑配置' : '新增配置'" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="业务场景">
<a-select v-model:value="form.sceneCode" :options="sceneOptions" show-search @change="handleSceneChange" />
</a-form-item>
<a-form-item label="场景名称">
<a-input v-model:value="form.sceneName" />
</a-form-item>
<a-form-item label="MessageHub 队列">
<a-input v-model:value="form.queueName" placeholder="smsQueue" />
</a-form-item>
<a-form-item label="来源系统">
<a-input v-model:value="form.sourceSystem" placeholder="yuminail" />
</a-form-item>
<a-form-item label="模板编码">
<a-input v-model:value="form.templateCode" placeholder="MessageHub 中维护的模板编码" />
</a-form-item>
<a-form-item label="指定通道 ID">
<a-input-number v-model:value="form.channelId" :min="1" style="width: 100%" placeholder="不填则由 MessageHub 选择" />
</a-form-item>
<a-form-item label="发送方式">
<a-select v-model:value="form.sendMethod" allow-clear :options="sendMethodOptions" />
</a-form-item>
<a-form-item label="备注">
<a-textarea v-model:value="form.remark" :rows="3" />
</a-form-item>
</a-form>
</a-modal>
<a-modal v-model:open="testOpen" title="测试投递" @ok="submitTest" :confirm-loading="testing">
<a-form layout="vertical">
<a-form-item label="测试手机号">
<a-input v-model:value="testPhone" :maxlength="11" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* MessageHubPushConfigsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminMessageHubPushConfigApi, adminSystemParameterConfigApi, type MessageHubPushConfigVO } from '@/api/admin'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** testing is a reactive state variable used by the template and event handlers. */
const testing = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
/** testOpen is a reactive state variable used by the template and event handlers. */
const testOpen = ref(false)
const editingId = ref<any>()
const testingId = ref<any>()
/** testPhone is a reactive state variable used by the template and event handlers. */
const testPhone = ref('')
const configs = ref<MessageHubPushConfigVO[]>([])
const savingMap = ref(false)
const mapEnabled = ref(true)
const mapForm = reactive({
configGroup: 'MAP',
configKey: 'TENCENT_MAP_KEY',
configName: '腾讯位置服务 Key',
configValue: '',
enabled: 1,
remark: '用于后台店铺选点和腾讯地图展示'
})
const sceneOptions = [
{ label: '用户注册验证码', value: 'USER_REGISTER_SMS_CODE' },
{ label: '手机号登录验证码', value: 'USER_LOGIN_SMS_CODE' },
{ label: '找回密码验证码', value: 'USER_RESET_PASSWORD_SMS_CODE' },
{ label: '绑定手机号验证码', value: 'USER_BIND_PHONE_SMS_CODE' },
{ label: '修改手机号验证码', value: 'USER_CHANGE_PHONE_SMS_CODE' },
{ label: '修改密码验证码', value: 'USER_CHANGE_PASSWORD_SMS_CODE' }
]
const sendMethodOptions = [
{ label: 'SPUG', value: 'SPUG' },
{ label: 'OTHER', value: 'OTHER' }
]
const form = reactive<any>({
sceneCode: 'USER_LOGIN_SMS_CODE',
sceneName: '手机号登录验证码',
platform: 'SMS',
msgType: 'VERIFICATION',
queueName: 'smsQueue',
sourceSystem: 'yuminail',
templateCode: 'SPUG0001',
channelId: undefined,
sendMethod: 'SPUG',
enabled: 1,
remark: ''
})
const columns = [
{ title: '业务场景', key: 'scene' },
{ title: 'MessageHub', key: 'messagehub' },
{ title: '模板/通道', key: 'template' },
{ title: '消息类型', dataIndex: 'msgType', key: 'msgType', width: 110 },
{ title: '启用', key: 'enabled', width: 90 },
{ title: '操作', key: 'action', width: 150 }
]
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [messageConfigs, mapConfigs] = await Promise.all([
adminMessageHubPushConfigApi.listConfigs(),
adminSystemParameterConfigApi.listConfigs('MAP')
])
configs.value = messageConfigs
const tencentMapConfig = mapConfigs.find(item => item.configKey === 'TENCENT_MAP_KEY')
if (tencentMapConfig) {
Object.assign(mapForm, tencentMapConfig)
mapEnabled.value = tencentMapConfig.enabled === 1
}
} finally {
loading.value = false
}
}
const saveMapConfig = async () => {
savingMap.value = true
try {
await adminSystemParameterConfigApi.saveConfig({
...mapForm,
enabled: mapEnabled.value ? 1 : 0
})
message.success('地图配置已保存')
await load()
} finally {
savingMap.value = false
}
}
/** resetForm is a local helper used by this page script. */
const resetForm = () => Object.assign(form, {
sceneCode: 'USER_LOGIN_SMS_CODE',
sceneName: '手机号登录验证码',
platform: 'SMS',
msgType: 'VERIFICATION',
queueName: 'smsQueue',
sourceSystem: 'yuminail',
templateCode: 'SPUG0001',
channelId: undefined,
sendMethod: 'SPUG',
enabled: 1,
remark: ''
})
/** handleSceneChange is a local helper used by this page script. */
const handleSceneChange = (value: any) => {
const option = sceneOptions.find(item => item.value === String(value || ''))
if (option) form.sceneName = option.label
}
/** openCreate is a local helper used by this page script. */
const openCreate = () => { editingId.value = undefined; resetForm(); formOpen.value = true }
/** openEdit is a local helper used by this page script. */
const openEdit = (record: MessageHubPushConfigVO) => {
editingId.value = record.id
Object.assign(form, record)
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.sceneCode || !form.sceneName || !form.queueName || !form.sourceSystem || !form.templateCode) {
message.warning('请填写场景、队列、来源系统和模板编码')
return
}
saving.value = true
try {
if (editingId.value) {
await adminMessageHubPushConfigApi.updateConfig(editingId.value, form)
} else {
await adminMessageHubPushConfigApi.createConfig(form)
}
message.success('配置已保存')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** toggleStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const toggleStatus = async (record: MessageHubPushConfigVO, checked: boolean) => {
await adminMessageHubPushConfigApi.updateStatus(record.id, checked ? 1 : 0)
record.enabled = checked ? 1 : 0
}
/** openTest is a local helper used by this page script. */
const openTest = (record: MessageHubPushConfigVO) => {
testingId.value = record.id
testPhone.value = ''
testOpen.value = true
}
/** submitTest is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submitTest = async () => {
if (!/^1[3-9]\d{9}$/.test(testPhone.value)) {
message.warning('请输入正确的测试手机号')
return
}
testing.value = true
try {
await adminMessageHubPushConfigApi.testConfig(testingId.value, testPhone.value)
message.success('测试消息已投递到 MessageHub')
testOpen.value = false
} finally {
testing.value = false
}
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p, .muted { margin: 0; color: #7a6f68; }
</style>
@@ -43,6 +43,19 @@
{{ getStatusText(record.status) }}
</a-tag>
</template>
<template v-else-if="column.key === 'userTypeName'">
<a-tag :color="record.userType === 2 ? 'gold' : 'blue'">
{{ record.userTypeName || (record.userType === 2 ? '店长' : '美甲师') }}
</a-tag>
</template>
<template v-else-if="column.key === 'participateProduction'">
<a-tag :color="record.participateProduction === 1 ? 'green' : 'default'">
{{ record.participateProduction === 1 ? '参与制作' : '不参与' }}
</a-tag>
</template>
<template v-else-if="column.key === 'workTime'">
{{ formatWorkTime(record) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('nail_artist:view')" type="link" size="small" @click="showViewModal(record)">
@@ -154,6 +167,19 @@
<a-select-option :value="0">休息中</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="参与制作" name="participateProduction">
<a-switch
v-model:checked="formState.participateProduction"
:checked-value="1"
:un-checked-value="0"
:disabled="!isShopOwner"
/>
</a-form-item>
<a-form-item label="工作时间">
<a-input v-model:value="formState.workStartTime" type="time" placeholder="开始" />
<span class="time-separator">至</span>
<a-input v-model:value="formState.workEndTime" type="time" placeholder="结束" />
</a-form-item>
<a-form-item label="作品" name="portfolio">
<a-select
v-model:value="formState.portfolio"
@@ -207,6 +233,12 @@
<a-form-item label="状态">
<a-input v-model:value="viewFormState.statusText" :disabled="true" />
</a-form-item>
<a-form-item label="人员类型">
<a-input v-model:value="viewFormState.userTypeName" :disabled="true" />
</a-form-item>
<a-form-item label="工作时间">
<a-input v-model:value="viewFormState.workTime" :disabled="true" />
</a-form-item>
<a-form-item label="评分">
<a-input v-model:value="viewFormState.rating" :disabled="true" />
</a-form-item>
@@ -219,6 +251,10 @@
</template>
<script setup lang="ts">
/**
* NailArtistsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
@@ -236,6 +272,7 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
@@ -251,17 +288,26 @@ const getCurrentUserInfo = () => {
return null
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** tagLoading is a reactive state variable used by the template and event handlers. */
const tagLoading = ref(false)
/** productLoading is a reactive state variable used by the template and event handlers. */
const productLoading = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
const nailArtistList = ref<NailArtistInfoVO[]>([])
const tagList = ref<Tag[]>([])
const productList = ref<Product[]>([])
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false)
/** isShopOwner is a reactive state variable used by the template and event handlers. */
const isShopOwner = ref(false)
const formRef = ref<FormInstance>()
const currentNailArtist = ref<NailArtistInfoVO | null>(null)
@@ -275,6 +321,8 @@ const viewFormState = reactive({
experience: '',
skillsText: '',
statusText: '',
userTypeName: '',
workTime: '',
rating: '',
portfolioText: ''
})
@@ -295,20 +343,29 @@ const formState = reactive({
skills: [] as string[],
rating: 0,
status: 1,
participateProduction: 1,
workStartTime: '',
workEndTime: '',
portfolio: [] as string[],
nickname: ''
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-nail-artists', 'edit', currentNailArtist.value?.userId ?? formState.userId ?? 'unknown')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
identity: formState.identity,
experience: formState.experience,
skills: [...formState.skills],
status: formState.status,
participateProduction: formState.participateProduction,
workStartTime: formState.workStartTime,
workEndTime: formState.workEndTime,
portfolio: [...formState.portfolio]
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -322,18 +379,25 @@ const restoreDraft = () => {
status: typeof draft.payload.status === 'number'
? (draft.payload.status === 0 ? 0 : 1)
: formState.status,
participateProduction: typeof draft.payload.participateProduction === 'number'
? (draft.payload.participateProduction === 1 ? 1 : 0)
: formState.participateProduction,
workStartTime: draft.payload.workStartTime ?? formState.workStartTime,
workEndTime: draft.payload.workEndTime ?? formState.workEndTime,
portfolio: Array.isArray(draft.payload.portfolio) ? draft.payload.portfolio : formState.portfolio
})
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -353,6 +417,9 @@ const formRules = {
const columns = [
{ title: '美甲师姓名', dataIndex: 'nickname', key: 'nickname' },
{ title: '所属店铺', dataIndex: 'shopName', key: 'shopName' },
{ title: '人员类型', key: 'userTypeName', width: 110 },
{ title: '参与制作', key: 'participateProduction', width: 120 },
{ title: '工作时间', key: 'workTime', width: 150 },
{ title: '身份', dataIndex: 'identity', key: 'identity' },
{ title: '从业年限', dataIndex: 'experience', key: 'experience' },
{ title: '评分', dataIndex: 'rating', key: 'rating' },
@@ -360,14 +427,27 @@ const columns = [
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** getStatusText is a local helper used by this page script. */
const getStatusText = (status: number) => {
return status === 1 ? '营业中' : '休息中'
}
/** getStatusColor is a local helper used by this page script. */
const getStatusColor = (status: number) => {
return status === 1 ? 'green' : 'default'
}
/** formatWorkTime is a local helper used by this page script. */
const formatWorkTime = (record: Partial<NailArtistInfoVO>) => {
const start = record.workStartTime ? String(record.workStartTime).slice(0, 5) : ''
const end = record.workEndTime ? String(record.workEndTime).slice(0, 5) : ''
return start && end ? `${start} - ${end}` : '--'
}
/** normalizeTime is a local helper used by this page script. */
const normalizeTime = (value?: string) => value ? (String(value).length === 5 ? `${value}:00` : String(value)) : undefined
/** fetchTagList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTagList = async () => {
tagLoading.value = true
try {
@@ -380,6 +460,7 @@ const fetchTagList = async () => {
}
}
/** fetchProductList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchProductList = async () => {
productLoading.value = true
try {
@@ -399,6 +480,7 @@ const fetchProductList = async () => {
}
}
/** fetchNailArtistList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchNailArtistList = async () => {
loading.value = true
try {
@@ -421,17 +503,20 @@ const fetchNailArtistList = async () => {
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchNailArtistList())
}
/** 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
await runWithGlobalLoading(() => fetchNailArtistList())
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: Record<string, any>) => {
currentNailArtist.value = record as NailArtistInfoVO
const lockedFields = {
@@ -444,6 +529,9 @@ const showEditModal = (record: Record<string, any>) => {
experience: record.experience || 0,
skills: record.skills ? record.skills.split(',').filter(Boolean) : [],
status: record.status || 1,
participateProduction: record.participateProduction ?? (record.userType === 3 ? 1 : 0),
workStartTime: record.workStartTime || '',
workEndTime: record.workEndTime || '',
portfolio: record.portfolio ? record.portfolio.split(',').filter(Boolean) : [],
...lockedFields
})
@@ -452,6 +540,7 @@ const showEditModal = (record: Record<string, any>) => {
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: Record<string, any>) => {
const nailArtist = record as NailArtistInfoVO
// 构建技能标签文本
@@ -475,16 +564,20 @@ const showViewModal = (record: Record<string, any>) => {
experience: (nailArtist.experience || 0).toString(),
skillsText: skillsText,
statusText: getStatusText(nailArtist.status || 1),
userTypeName: nailArtist.userTypeName || (nailArtist.userType === 2 ? '店长' : '美甲师'),
workTime: formatWorkTime(nailArtist),
rating: (nailArtist.rating || 0).toString(),
portfolioText: portfolioText
})
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
@@ -505,6 +598,9 @@ const handleModalOk = async () => {
experience: formState.experience,
rating: formState.rating,
status: formState.status,
participateProduction: formState.participateProduction,
workStartTime: normalizeTime(formState.workStartTime),
workEndTime: normalizeTime(formState.workEndTime),
skills: formState.skills.join(','),
portfolio: formState.portfolio.join(',')
}
@@ -529,6 +625,7 @@ const handleModalOk = async () => {
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
currentNailArtist.value = null
@@ -185,6 +185,10 @@
</template>
<script setup lang="ts">
/**
* OrdersView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { orderApi } from '../../api/order'
@@ -198,18 +202,23 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { isMobile } = useAdminViewport()
const orders = ref<any[]>([])
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const currentOrder = ref<any | null>(null)
const currentUserType = ref<number | null>(null)
/** keyword is a reactive state variable used by the template and event handlers. */
const keyword = ref('')
const statusFilter = ref<'all' | string>('all')
const { hasPermission, loadUserPermissions } = usePermission()
/** detailVisible is a reactive state variable used by the template and event handlers. */
const detailVisible = computed({
get: () => !!currentOrder.value,
set: value => { if (!value) currentOrder.value = null }
})
/** canProcessOrders is a reactive state variable used by the template and event handlers. */
const canProcessOrders = computed(() => hasPermission('order:process'))
/** isArtist is a reactive state variable used by the template and event handlers. */
const isArtist = computed(() => currentUserType.value === 3)
const statusOptions = [
{ label: '全部状态', value: 'all' },
@@ -218,6 +227,7 @@ const statusOptions = [
{ label: '已取消', value: '3' }
]
/** filteredOrders is a reactive state variable used by the template and event handlers. */
const filteredOrders = computed(() => {
const keywordValue = keyword.value.trim().toLowerCase()
return orders.value.filter(order => {
@@ -259,6 +269,7 @@ const itemColumns = [
{ title: '总价', key: 'totalPrice', width: 100 }
]
/** statusColor is a local helper used by this page script. */
const statusColor = (status: number) => {
if (status === 1) return 'orange'
if (status === 2) return 'green'
@@ -266,6 +277,7 @@ const statusColor = (status: number) => {
return 'default'
}
/** resolveCurrentUserType is a local helper used by this page script. */
const resolveCurrentUserType = () => {
const cached = localStorage.getItem('adminUserInfo') || sessionStorage.getItem('adminUserInfo')
if (!cached) {
@@ -279,6 +291,7 @@ const resolveCurrentUserType = () => {
}
}
/** loadOrders is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadOrders = async () => {
loading.value = true
try {
@@ -290,6 +303,7 @@ const loadOrders = async () => {
}
}
/** process is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const process = async (orderId: IdType, status: number) => {
try {
await runWithGlobalLoading(async () => {
@@ -305,6 +319,7 @@ const process = async (orderId: IdType, status: number) => {
}
}
/** noop is a local helper used by this page script. */
const noop = () => {}
onMounted(async () => {
@@ -331,6 +331,10 @@
</template>
<script setup lang="ts">
/**
* PermissionsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
@@ -354,11 +358,16 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** activeTab is a reactive state variable used by the template and event handlers. */
const activeTab = ref('permissions')
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
const permissionList = ref<PermissionVO[]>([])
/** permissionModalVisible is a reactive state variable used by the template and event handlers. */
const permissionModalVisible = ref(false)
/** permissionModalLoading is a reactive state variable used by the template and event handlers. */
const permissionModalLoading = ref(false)
/** isEditPermission is a reactive state variable used by the template and event handlers. */
const isEditPermission = ref(false)
const permissionFormRef = ref<FormInstance>()
const currentPermission = ref<PermissionVO | null>(null)
@@ -380,8 +389,10 @@ const permissionFormState = reactive({
description: ''
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-permissions', isEditPermission.value ? 'edit' : 'create', currentPermission.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
permissionCode: permissionFormState.permissionCode,
permissionName: permissionFormState.permissionName,
@@ -389,6 +400,7 @@ const buildDraftPayload = () => ({
description: permissionFormState.description
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -400,12 +412,14 @@ const restoreDraft = () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -430,10 +444,13 @@ const permissionColumns = [
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** userLoading is a reactive state variable used by the template and event handlers. */
const userLoading = ref(false)
/** userSearchText is a reactive state variable used by the template and event handlers. */
const userSearchText = ref('')
const userList = ref<UserVO[]>([])
const selectedUser = ref<UserVO | null>(null)
/** assignLoading is a reactive state variable used by the template and event handlers. */
const assignLoading = ref(false)
const selectedPermissions = ref<IdType[]>([])
const assignablePermissionIds = ref<IdType[]>([])
@@ -442,11 +459,14 @@ const currentLoginUser = ref<UserVO | null>(null)
const mobilePermissionStep = ref<'users' | 'assign'>('users')
// 权限 ID 同样可能以字符串形式返回,所以这里统一转成字符串集合做包含判断。
/** assignablePermissionIdSet is a reactive state variable used by the template and event handlers. */
const assignablePermissionIdSet = computed(() => new Set(assignablePermissionIds.value.map(id => String(id))))
/** disabledPermissionCount is a reactive state variable used by the template and event handlers. */
const disabledPermissionCount = computed(() =>
permissionList.value.filter(permission => !assignablePermissionIdSet.value.has(String(permission.id))).length
)
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
permissionList.value.forEach(p => {
@@ -459,6 +479,7 @@ const groupedPermissions = computed(() => {
return groups
})
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number) => {
const map: Record<number, string> = {
0: '用户',
@@ -469,6 +490,7 @@ const getUserTypeText = (type: number) => {
return map[type] || '未知'
}
/** filteredUserList is a reactive state variable used by the template and event handlers. */
const filteredUserList = computed(() => {
if (!currentLoginUser.value) return []
@@ -488,6 +510,7 @@ const filteredUserList = computed(() => {
return []
})
/** isPermissionDisabled is a local helper used by this page script. */
const isPermissionDisabled = (permission: PermissionVO) => {
if (!selectedUser.value) {
return true
@@ -495,10 +518,12 @@ const isPermissionDisabled = (permission: PermissionVO) => {
return !assignablePermissionIdSet.value.has(String(permission.id))
}
/** resolveRequestErrorMessage is a local helper used by this page script. */
const resolveRequestErrorMessage = (error: any, fallback: string) => {
return error?.response?.data?.message || error?.message || fallback
}
/** fetchCurrentUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCurrentUser = async () => {
try {
// 尝试从API获取用户信息
@@ -524,6 +549,7 @@ const fetchCurrentUser = async () => {
}
}
/** fetchPermissionList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchPermissionList = async () => {
loading.value = true
try {
@@ -537,6 +563,7 @@ const fetchPermissionList = async () => {
}
}
/** fetchUserList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserList = async () => {
userLoading.value = true
try {
@@ -560,16 +587,19 @@ const fetchUserList = async () => {
}
}
/** handlePermissionTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePermissionTableChange = async (pag: any) => {
permissionPagination.current = pag.current
permissionPagination.pageSize = pag.pageSize
await runWithGlobalLoading(() => fetchPermissionList())
}
/** handleUserSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUserSearch = async () => {
await runWithGlobalLoading(() => fetchUserList())
}
/** selectUser is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const selectUser = async (user: UserVO) => {
selectedUser.value = user
assignLoading.value = true
@@ -582,6 +612,7 @@ const selectUser = async (user: UserVO) => {
])
assignablePermissionIds.value = allowedIds || []
const allowedIdSet = new Set(assignablePermissionIds.value.map(id => String(id)))
/** assignedIds is a local helper used by this page script. */
const assignedIds = (assignedPermissions || []).map((p: PermissionVO) => p.id)
selectedPermissions.value = assignedIds.filter(id => allowedIdSet.has(String(id)))
const trimmedCount = assignedIds.length - selectedPermissions.value.length
@@ -601,6 +632,7 @@ const selectUser = async (user: UserVO) => {
}
}
/** handleSaveUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSaveUserPermissions = async () => {
if (!selectedUser.value) return
const userId = selectedUser.value.id
@@ -616,6 +648,7 @@ const handleSaveUserPermissions = async () => {
}
}
/** showAddPermissionModal is a local helper used by this page script. */
const showAddPermissionModal = () => {
isEditPermission.value = false
currentPermission.value = null
@@ -629,6 +662,7 @@ const showAddPermissionModal = () => {
permissionModalVisible.value = true
}
/** showEditPermissionModal is a local helper used by this page script. */
const showEditPermissionModal = (record: Record<string, any>) => {
isEditPermission.value = true
currentPermission.value = record as PermissionVO
@@ -642,6 +676,7 @@ const showEditPermissionModal = (record: Record<string, any>) => {
permissionModalVisible.value = true
}
/** handlePermissionModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePermissionModalOk = async () => {
try {
await permissionFormRef.value?.validate()
@@ -667,11 +702,13 @@ const handlePermissionModalOk = async () => {
}
}
/** handlePermissionModalCancel is a local helper used by this page script. */
const handlePermissionModalCancel = () => {
permissionModalVisible.value = false
permissionFormRef.value?.resetFields()
}
/** handleDeletePermission is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDeletePermission = async (record: Record<string, any>) => {
try {
await runWithGlobalLoading(async () => {
@@ -300,7 +300,7 @@
:key="artist.id"
:value="artist.id.toString()"
>
{{ artist.nickname }}
{{ artist.nickname }}{{ artist.type === 2 ? '(店长 · 参与制作)' : '' }}
</a-select-option>
</a-select>
</a-form-item>
@@ -453,7 +453,7 @@
:key="artist?.id"
:value="artist?.id?.toString()"
>
{{ artist?.nickname || '' }}
{{ artist?.nickname || '' }}{{ artist?.type === 2 ? '(店长 · 参与制作)' : '' }}
</a-select-option>
</a-select>
</a-form-item>
@@ -485,6 +485,10 @@
</template>
<script setup lang="ts">
/**
* ProductsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, ref, reactive, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
@@ -506,33 +510,48 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
const productList = ref<Product[]>([])
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
const currentProduct = ref<Product | null>(null)
const shops = ref<Shop[]>([])
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
const tags = ref<any[]>([])
/** loadingTags is a reactive state variable used by the template and event handlers. */
const loadingTags = ref(false)
const artists = ref<any[]>([])
/** loadingArtists is a reactive state variable used by the template and event handlers. */
const loadingArtists = ref(false)
const coupons = ref<any[]>([])
/** loadingCoupons is a reactive state variable used by the template and event handlers. */
const loadingCoupons = ref(false)
/** previewVisible is a reactive state variable used by the template and event handlers. */
const previewVisible = ref(false)
/** previewImage is a reactive state variable used by the template and event handlers. */
const previewImage = ref('')
const imageFileList = ref<any[]>([])
const uploadedFileIds = ref<string[]>([])
const imageUrls = ref<Record<string, string[]>>({})
const viewImageUrls = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false)
const formRef = ref<any>(null)
const uploadTaskMap = new Map<string, ChunkUploadTask<any>>()
/** activeUploadCount is a reactive state variable used by the template and event handlers. */
const activeUploadCount = ref(0)
/** isUploadPending is a reactive state variable used by the template and event handlers. */
const isUploadPending = computed(() => activeUploadCount.value > 0)
const draftSavedAt = ref<number | null>(null)
const requestTokens = reactive({
@@ -543,13 +562,16 @@ const requestTokens = reactive({
products: 0
})
/** nextRequestToken is a local helper used by this page script. */
const nextRequestToken = (key: keyof typeof requestTokens) => {
requestTokens[key] += 1
return requestTokens[key]
}
/** isLatestRequestToken is a local helper used by this page script. */
const isLatestRequestToken = (key: keyof typeof requestTokens, token: number) => requestTokens[key] === token
/** formatDuration is a local helper used by this page script. */
const formatDuration = (value?: string | number | null) => {
if (value === undefined || value === null || value === '') {
return '--'
@@ -595,6 +617,7 @@ const formState = reactive({
availableCoupons: [] as string[]
})
/** validateInteractionCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validateInteractionCount = async (_rule: any, value: number | undefined) => {
if (value === undefined || value === null) {
return Promise.resolve()
@@ -629,12 +652,14 @@ const columns = [
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** getShopName is a local helper used by this page script. */
const getShopName = (shopId: IdType): string => {
const normalizedShopId = normalizeShopIdValue(shopId)
const shop = shops.value.find(s => normalizeShopIdValue(s.id) === normalizedShopId)
return shop ? shop.shopName : '未知店铺'
}
/** normalizeShopIdValue is a local helper used by this page script. */
const normalizeShopIdValue = (value: string | number | undefined | null) => {
if (value === undefined || value === null || value === '') {
return ''
@@ -642,6 +667,7 @@ const normalizeShopIdValue = (value: string | number | undefined | null) => {
return String(value)
}
/** normalizeInteractionCount is a local helper used by this page script. */
const normalizeInteractionCount = (value: unknown) => {
const numericValue = Number(value)
if (!Number.isFinite(numericValue) || numericValue < 0) {
@@ -650,6 +676,7 @@ const normalizeInteractionCount = (value: unknown) => {
return Math.floor(numericValue)
}
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
@@ -665,13 +692,16 @@ const getCurrentUserInfo = () => {
return null
}
/** canManageAvailableCoupons is a local helper used by this page script. */
const canManageAvailableCoupons = () => {
const userInfo = getCurrentUserInfo()
return Boolean(userInfo && (userInfo.type === 2 || userInfo.type === 4))
}
/** isCouponSelectionDisabled is a reactive state variable used by the template and event handlers. */
const isCouponSelectionDisabled = computed(() => !canManageAvailableCoupons())
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
const requestToken = nextRequestToken('shops')
loadingShops.value = true
@@ -712,6 +742,7 @@ const fetchShops = async () => {
}
}
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async (shopId?: IdType) => {
const requestToken = nextRequestToken('tags')
loadingTags.value = true
@@ -736,6 +767,7 @@ const fetchTags = async (shopId?: IdType) => {
}
}
/** fetchArtists is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchArtists = async (shopId?: IdType) => {
const requestToken = nextRequestToken('artists')
loadingArtists.value = true
@@ -755,6 +787,7 @@ const fetchArtists = async (shopId?: IdType) => {
}
}
/** syncAvailableCouponSelection is a local helper used by this page script. */
const syncAvailableCouponSelection = () => {
const availableCouponIdSet = new Set(
coupons.value
@@ -765,6 +798,7 @@ const syncAvailableCouponSelection = () => {
formState.availableCoupons = formState.availableCoupons.filter(couponId => availableCouponIdSet.has(String(couponId)))
}
/** fetchCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCoupons = async (shopId?: IdType) => {
if (!shopId) {
nextRequestToken('coupons')
@@ -793,6 +827,7 @@ const fetchCoupons = async (shopId?: IdType) => {
}
}
/** fetchProductList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchProductList = async () => {
const requestToken = nextRequestToken('products')
loading.value = true
@@ -829,6 +864,7 @@ const fetchProductList = async () => {
}
}
/** 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) {
@@ -870,6 +906,7 @@ const loadImageUrls = async (products: Product[], requestToken?: number) => {
return nextImageUrls
}
/** 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) {
@@ -878,17 +915,20 @@ const getProductImages = (product: Product | Record<string, any>): string[] => {
return [DEFAULT_PRODUCT_IMAGE]
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchProductList())
}
/** 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
await runWithGlobalLoading(() => fetchProductList())
}
/** showAddModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showAddModal = async () => {
isEdit.value = false
currentProduct.value = null
@@ -918,6 +958,7 @@ const showAddModal = async () => {
modalVisible.value = true
}
/** showEditModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showEditModal = async (record: Product | Record<string, any>) => {
isEdit.value = true
currentProduct.value = record as Product
@@ -976,6 +1017,7 @@ const showEditModal = async (record: Product | Record<string, any>) => {
modalVisible.value = true
}
/** showViewModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showViewModal = async (record: Product | Record<string, any>) => {
const recordShopId = 'shopId' in record ? record.shopId : (record as any).shopId
const recordTitle = 'title' in record ? record.title : (record as any).title
@@ -1044,17 +1086,21 @@ const showViewModal = async (record: Product | Record<string, any>) => {
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
viewImageUrls.value = []
}
/** cancelAllPendingUploads is a local helper used by this page script. */
const cancelAllPendingUploads = () => {
uploadTaskMap.forEach(task => task.cancel())
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-products', isEdit.value ? 'edit' : 'create', currentProduct.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
formState: {
shopId: formState.shopId,
@@ -1072,6 +1118,7 @@ const buildDraftPayload = () => ({
uploadedFileIds: [...uploadedFileIds.value]
})
/** 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()) {
@@ -1101,6 +1148,7 @@ const buildImageFileListByIds = async (ids: string[]) => {
return fileList
}
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const restoreDraft = async () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -1117,6 +1165,7 @@ const restoreDraft = async () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
if (isUploadPending.value) {
message.warning('图片上传完成后才能暂存')
@@ -1127,6 +1176,7 @@ const handleSaveDraft = () => {
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -1135,11 +1185,13 @@ const handleClearDraft = (showMessage = true) => {
}
}
/** syncUploadedFileIds is a local helper used by this page script. */
const syncUploadedFileIds = (fileIds: string[]) => {
uploadedFileIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
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
@@ -1147,6 +1199,7 @@ const getUploadResponse = (file: any) => {
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
@@ -1167,6 +1220,7 @@ const resolveUploadedFileId = (file: any) => {
return ''
}
/** getPreviewUrlFromFile is a local helper used by this page script. */
const getPreviewUrlFromFile = (file: any) => {
const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) {
@@ -1181,6 +1235,7 @@ const getPreviewUrlFromFile = (file: any) => {
return ''
}
/** beforeUpload is a local helper used by this page script. */
const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/')
if (!isImage) {
@@ -1190,6 +1245,7 @@ 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 { file, onSuccess, onError, onProgress } = options
let successMessage = '图片上传成功'
@@ -1247,6 +1303,7 @@ const handleUploadImage = async (options: any) => {
}
// 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) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
@@ -1274,6 +1331,7 @@ const handlePreview = async (file: any) => {
}
}
/** handleRemove is a local helper used by this page script. */
const handleRemove = (file: any) => {
const uploadTask = uploadTaskMap.get(String(file.uid))
if (uploadTask) {
@@ -1289,6 +1347,7 @@ const handleRemove = (file: any) => {
return true
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
if (isUploadPending.value) {
@@ -1341,12 +1400,14 @@ const handleModalOk = async () => {
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
cancelAllPendingUploads()
modalVisible.value = false
formRef.value?.resetFields()
}
/** handleDelete is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDelete = async (record: Product | Record<string, any>) => {
try {
await runWithGlobalLoading(async () => {
@@ -1363,6 +1424,7 @@ const handleDelete = async (record: Product | Record<string, any>) => {
}
}
/** handleSelectAllCoupons is a local helper used by this page script. */
const handleSelectAllCoupons = () => {
if (isCouponSelectionDisabled.value) {
return
@@ -1373,6 +1435,7 @@ const handleSelectAllCoupons = () => {
.map(id => String(id))
}
/** handleClearAvailableCoupons is a local helper used by this page script. */
const handleClearAvailableCoupons = () => {
formState.availableCoupons = []
}
@@ -75,6 +75,10 @@
</template>
<script setup lang="ts">
/**
* ProfileView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
@@ -91,15 +95,24 @@ import {
const router = useRouter()
const { userPermissions, loadUserPermissions, clearPermissions } = usePermission()
/** userInfo is a reactive state variable used by the template and event handlers. */
const userInfo = ref(loadCachedAdminUserInfo())
/** selectedShopId is a reactive state variable used by the template and event handlers. */
const selectedShopId = ref(userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined)
/** shopSwitchLoading is a reactive state variable used by the template and event handlers. */
const shopSwitchLoading = ref(false)
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
/** roleLabel is a reactive state variable used by the template and event handlers. */
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => getAdminShopOptions(userInfo.value))
/** shopSelectOptions is a reactive state variable used by the template and event handlers. */
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
/** permissionCount is a reactive state variable used by the template and event handlers. */
const permissionCount = computed(() => userPermissions.value.length)
/** shopScopeText is a reactive state variable used by the template and event handlers. */
const shopScopeText = computed(() => {
if (!shopOptions.value.length) {
return '游客模式'
@@ -107,6 +120,7 @@ const shopScopeText = computed(() => {
return shopOptions.value.map(item => item.name).join(' / ')
})
/** persistAdminSession is a local helper used by this page script. */
const persistAdminSession = (payload: any) => {
localStorage.setItem('adminAccessToken', payload.accessToken)
localStorage.setItem('adminRefreshToken', payload.refreshToken)
@@ -114,11 +128,13 @@ const persistAdminSession = (payload: any) => {
sessionStorage.setItem('adminAccessToken', payload.accessToken)
}
/** refreshLocalUserInfo is a local helper used by this page script. */
const refreshLocalUserInfo = () => {
userInfo.value = loadCachedAdminUserInfo()
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
}
/** handleShopChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleShopChange = async (shopId: unknown) => {
if (typeof shopId !== 'string' && typeof shopId !== 'number') {
return
@@ -145,6 +161,7 @@ const handleShopChange = async (shopId: unknown) => {
}
}
/** handleLogout is a local helper used by this page script. */
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
+180 -1
View File
@@ -89,6 +89,14 @@
@change="(checked: any) => handleStatusChange(record, checked === true)"
/>
</template>
<template v-else-if="column.key === 'authorization'">
<a-space direction="vertical" size="small">
<a-tag :color="record.authorizationExpired ? 'red' : 'green'">
{{ record.authorizationStatusText || (record.authorizationExpired ? '已到期' : '有效') }}
</a-tag>
<span>{{ formatAuthorizationExpireTime(record.authorizationExpireTime) }}</span>
</a-space>
</template>
<template v-else-if="column.key === 'shopName'">
<div style="max-width: 180px;">
<TableEllipsisText :text="record.shopName" />
@@ -200,11 +208,20 @@
<a-form-item label="店铺地址" name="address">
<a-input v-model:value="formState.address" placeholder="请输入店铺地址" />
</a-form-item>
<a-form-item label="地图位置">
<div class="map-picker-row">
<a-input v-model:value="formState.longitude" placeholder="经度" />
<a-input v-model:value="formState.latitude" placeholder="纬度" />
<a-button @click="openTencentLocationPicker">腾讯地图选点</a-button>
</div>
<div class="map-picker-tip">选点和展示使用腾讯地图;保存经纬度后,用户端可跳转腾讯地图或高德地图导航。</div>
</a-form-item>
<a-form-item label="营业时间" name="businessHours">
<div class="business-hours-picker">
<a-date-picker
v-model:value="businessStartTime"
picker="time"
popup-class-name="yumi-date-picker-panel yumi-time-panel"
value-format="HH:mm"
format="HH:mm"
placeholder="开始时间"
@@ -216,6 +233,7 @@
<a-date-picker
v-model:value="businessEndTime"
picker="time"
popup-class-name="yumi-date-picker-panel yumi-time-panel"
value-format="HH:mm"
format="HH:mm"
placeholder="结束时间"
@@ -225,6 +243,17 @@
/>
</div>
</a-form-item>
<a-form-item label="授权有效期" name="authorizationExpireTime">
<a-date-picker
v-model:value="formState.authorizationExpireTime"
show-time
value-format="YYYY-MM-DD HH:mm:ss"
format="YYYY-MM-DD HH:mm"
placeholder="为空表示长期有效"
:disabled="!isAdmin"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="Banner图片">
<div class="upload-tip">首页轮播图,建议尺寸 750x300 像素</div>
<a-upload
@@ -295,9 +324,18 @@
<a-form-item label="店铺地址">
<a-input v-model:value="viewFormState.address" :disabled="true" />
</a-form-item>
<a-form-item label="地图位置">
<a-input :value="formatLocation(viewFormState.longitude, viewFormState.latitude)" :disabled="true" />
</a-form-item>
<a-form-item label="营业时间">
<a-input v-model:value="viewFormState.businessHours" :disabled="true" />
</a-form-item>
<a-form-item label="授权状态">
<a-input :value="viewFormState.authorizationStatusText || '有效'" :disabled="true" />
</a-form-item>
<a-form-item label="授权有效期">
<a-input :value="formatAuthorizationExpireTime(viewFormState.authorizationExpireTime)" :disabled="true" />
</a-form-item>
<a-form-item label="Banner图片">
<div class="shop-images">
<a-image
@@ -345,6 +383,10 @@
</template>
<script setup lang="ts">
/**
* ShopsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
@@ -352,7 +394,7 @@ import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
import { DEFAULT_SHOP_IMAGE } from '@/constants'
import { adminShopApi, adminFileApi, type Shop } from '@/api/admin'
import { adminShopApi, adminFileApi, adminSystemParameterConfigApi, type Shop } from '@/api/admin'
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
@@ -365,21 +407,30 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
const shopList = ref<Shop[]>([])
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const currentShop = ref<Shop | null>(null)
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false)
// Banner图片相关
const bannerFileList = ref<any[]>([])
const uploadedBannerIds = ref<string[]>([])
/** bannerPreviewVisible is a reactive state variable used by the template and event handlers. */
const bannerPreviewVisible = ref(false)
/** bannerPreviewImage is a reactive state variable used by the template and event handlers. */
const bannerPreviewImage = ref('')
// 店铺图片相关
@@ -390,12 +441,18 @@ const shopImageUrls = ref<Record<string, string[]>>({})
const shopBannerUrls = ref<Record<string, string[]>>({})
const viewImageUrls = ref<string[]>([])
const viewBannerUrls = ref<string[]>([])
/** previewVisible is a reactive state variable used by the template and event handlers. */
const previewVisible = ref(false)
/** previewImage is a reactive state variable used by the template and event handlers. */
const previewImage = ref('')
/** businessStartTime is a reactive state variable used by the template and event handlers. */
const businessStartTime = ref('')
/** businessEndTime is a reactive state variable used by the template and event handlers. */
const businessEndTime = ref('')
const uploadTaskMap = new Map<string, ChunkUploadTask<any>>()
/** activeUploadCount is a reactive state variable used by the template and event handlers. */
const activeUploadCount = ref(0)
/** isUploadPending is a reactive state variable used by the template and event handlers. */
const isUploadPending = computed(() => activeUploadCount.value > 0)
const draftSavedAt = ref<number | null>(null)
@@ -404,8 +461,13 @@ const viewFormState = reactive({
shopName: '',
description: '',
address: '',
mapProvider: 'TENCENT',
longitude: '',
latitude: '',
businessHours: '',
status: 1,
authorizationExpireTime: '',
authorizationStatusText: '',
coverImageFileId: '',
imageFileIds: ''
})
@@ -423,8 +485,12 @@ const formState = reactive({
shopName: '',
description: '',
address: '',
mapProvider: 'TENCENT',
longitude: '',
latitude: '',
businessHours: '',
status: 1,
authorizationExpireTime: '',
coverImageFileId: '',
imageFileIds: ''
})
@@ -455,10 +521,12 @@ const columns = [
{ title: '店铺地址', dataIndex: 'address', key: 'address' },
{ title: '营业时间', dataIndex: 'businessHours', key: 'businessHours' },
{ title: '状态', key: 'status', width: 120 },
{ title: '授权', key: 'authorization', width: 180 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
@@ -474,6 +542,7 @@ const getCurrentUserInfo = () => {
return null
}
/** 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) {
// 加载店铺图片
@@ -538,6 +607,7 @@ const loadImageUrls = async (shops: Shop[]) => {
}
}
/** 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) {
@@ -546,6 +616,7 @@ const getShopImages = (shop: Shop | Record<string, any>): string[] => {
return []
}
/** 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) {
@@ -554,6 +625,52 @@ const getShopBannerImages = (shop: Shop | Record<string, any>): string[] => {
return []
}
/** formatAuthorizationExpireTime is a local helper used by this page script. */
const formatAuthorizationExpireTime = (value?: string) => {
if (!value) {
return '长期有效'
}
return value.replace('T', ' ').slice(0, 16)
}
const formatLocation = (longitude?: string | number, latitude?: string | number) => {
return longitude && latitude ? `${longitude}, ${latitude}` : '未设置地图坐标'
}
const openTencentLocationPicker = async () => {
const response = await adminSystemParameterConfigApi.getTencentMapKey()
const key = response?.key || ''
if (!key) {
message.warning('请先在参数管理中配置腾讯位置服务 Key')
return
}
const keyword = encodeURIComponent(formState.address || formState.shopName || '')
const url = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${key}&referer=yuminail&keyword=${keyword}`
const picker = window.open(url, 'yuminailTencentLocationPicker', 'width=900,height=680')
const handleMessage = (event: MessageEvent) => {
const data = event.data || {}
const location = data.loclatlng || data.latlng || data.location
if (!location) {
return
}
formState.latitude = String(location.lat || location.latitude || '')
formState.longitude = String(location.lng || location.longitude || '')
formState.mapProvider = 'TENCENT'
if (data.poiaddress || data.addr || data.address) {
formState.address = data.poiaddress || data.addr || data.address
}
if (data.poiname && !formState.shopName) {
formState.shopName = data.poiname
}
message.success('已选择腾讯地图位置')
window.removeEventListener('message', handleMessage)
picker?.close()
}
window.addEventListener('message', handleMessage)
}
/** fetchShopList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShopList = async () => {
loading.value = true
try {
@@ -582,17 +699,20 @@ const fetchShopList = async () => {
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchShopList())
}
/** 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
await runWithGlobalLoading(() => fetchShopList())
}
/** beforeUpload is a local helper used by this page script. */
const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/')
if (!isImage) {
@@ -606,6 +726,7 @@ const beforeUpload = (file: File) => {
}
// 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 { file, onSuccess, onError, onProgress } = options
const taskKey = `banner:${String(file.uid)}`
@@ -645,6 +766,7 @@ 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) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
@@ -671,6 +793,7 @@ const handleBannerPreview = async (file: any) => {
}
}
/** handleBannerRemove is a local helper used by this page script. */
const handleBannerRemove = (file: any) => {
const task = uploadTaskMap.get(`banner:${String(file.uid)}`)
if (task) {
@@ -686,6 +809,7 @@ 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 { file, onSuccess, onError, onProgress } = options
const taskKey = `image:${String(file.uid)}`
@@ -726,6 +850,7 @@ 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) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file)
@@ -752,6 +877,7 @@ const handlePreview = async (file: any) => {
}
}
/** handleRemove is a local helper used by this page script. */
const handleRemove = (file: any) => {
const task = uploadTaskMap.get(`image:${String(file.uid)}`)
if (task) {
@@ -766,12 +892,14 @@ const handleRemove = (file: any) => {
return true
}
/** syncBusinessHoursValue is a local helper used by this page script. */
const syncBusinessHoursValue = () => {
formState.businessHours = businessStartTime.value && businessEndTime.value
? `${businessStartTime.value}-${businessEndTime.value}`
: ''
}
/** setBusinessHoursValue is a local helper used by this page script. */
const setBusinessHoursValue = (value?: string) => {
const matched = (value || '').match(/(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/)
businessStartTime.value = matched?.[1] || ''
@@ -779,11 +907,13 @@ const setBusinessHoursValue = (value?: string) => {
syncBusinessHoursValue()
}
/** handleBusinessHoursChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBusinessHoursChange = async () => {
syncBusinessHoursValue()
await formRef.value?.validateFields?.(['businessHours']).catch(() => undefined)
}
/** showAddModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showAddModal = async () => {
isEdit.value = false
currentShop.value = null
@@ -791,8 +921,12 @@ const showAddModal = async () => {
shopName: '',
description: '',
address: '',
mapProvider: 'TENCENT',
longitude: '',
latitude: '',
businessHours: '',
status: 1,
authorizationExpireTime: '',
coverImageFileId: '',
imageFileIds: ''
})
@@ -805,6 +939,7 @@ const showAddModal = async () => {
modalVisible.value = true
}
/** showEditModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showEditModal = async (record: Shop | Record<string, any>) => {
isEdit.value = true
currentShop.value = record as Shop
@@ -812,8 +947,12 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
shopName: 'shopName' in record ? record.shopName : (record as any).shopName,
description: 'description' in record ? record.description : (record as any).description,
address: 'address' in record ? record.address : (record as any).address,
mapProvider: 'TENCENT',
longitude: 'longitude' in record ? record.longitude : (record as any).longitude,
latitude: 'latitude' in record ? record.latitude : (record as any).latitude,
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
authorizationExpireTime: 'authorizationExpireTime' in record ? record.authorizationExpireTime : (record as any).authorizationExpireTime,
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
})
@@ -845,13 +984,19 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
modalVisible.value = true
}
/** showViewModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showViewModal = async (record: Shop | Record<string, any>) => {
Object.assign(viewFormState, {
shopName: 'shopName' in record ? record.shopName : (record as any).shopName,
description: 'description' in record ? record.description : (record as any).description,
address: 'address' in record ? record.address : (record as any).address,
mapProvider: 'TENCENT',
longitude: 'longitude' in record ? record.longitude : (record as any).longitude,
latitude: 'latitude' in record ? record.latitude : (record as any).latitude,
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
authorizationExpireTime: 'authorizationExpireTime' in record ? record.authorizationExpireTime : (record as any).authorizationExpireTime,
authorizationStatusText: 'authorizationStatusText' in record ? record.authorizationStatusText : (record as any).authorizationStatusText,
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
})
@@ -907,25 +1052,33 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
viewImageUrls.value = []
viewBannerUrls.value = []
}
/** cancelAllPendingUploads is a local helper used by this page script. */
const cancelAllPendingUploads = () => {
uploadTaskMap.forEach(task => task.cancel())
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-shops', isEdit.value ? 'edit' : 'create', currentShop.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
formState: {
shopName: formState.shopName,
description: formState.description,
address: formState.address,
mapProvider: 'TENCENT',
longitude: formState.longitude,
latitude: formState.latitude,
businessHours: formState.businessHours,
status: formState.status,
authorizationExpireTime: formState.authorizationExpireTime,
coverImageFileId: formState.coverImageFileId,
imageFileIds: formState.imageFileIds
},
@@ -935,6 +1088,7 @@ const buildDraftPayload = () => ({
uploadedFileIds: [...uploadedFileIds.value]
})
/** 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()) {
@@ -964,6 +1118,7 @@ const buildShopUploadFileList = async (ids: string[], fileNamePrefix: string) =>
return fileList
}
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const restoreDraft = async () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -982,6 +1137,7 @@ const restoreDraft = async () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
if (isUploadPending.value) {
message.warning('图片上传完成后才能暂存')
@@ -992,6 +1148,7 @@ const handleSaveDraft = () => {
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -1000,16 +1157,19 @@ const handleClearDraft = (showMessage = true) => {
}
}
/** syncUploadedBannerIds is a local helper used by this page script. */
const syncUploadedBannerIds = (fileIds: string[]) => {
uploadedBannerIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.coverImageFileId = uploadedBannerIds.value.join(',')
}
/** syncUploadedFileIds is a local helper used by this page script. */
const syncUploadedFileIds = (fileIds: string[]) => {
uploadedFileIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
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
@@ -1017,6 +1177,7 @@ const getUploadResponse = (file: any) => {
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
@@ -1037,6 +1198,7 @@ const resolveUploadedFileId = (file: any) => {
return ''
}
/** getPreviewUrlFromFile is a local helper used by this page script. */
const getPreviewUrlFromFile = (file: any) => {
const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) {
@@ -1051,6 +1213,7 @@ const getPreviewUrlFromFile = (file: any) => {
return ''
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
if (isUploadPending.value) {
@@ -1081,6 +1244,7 @@ const handleModalOk = async () => {
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
cancelAllPendingUploads()
modalVisible.value = false
@@ -1092,6 +1256,7 @@ const handleModalCancel = () => {
syncUploadedFileIds([])
}
/** handleDelete is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDelete = async (record: Shop | Record<string, any>) => {
try {
await runWithGlobalLoading(async () => {
@@ -1105,6 +1270,7 @@ const handleDelete = async (record: Shop | Record<string, any>) => {
}
}
/** handleStatusChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleStatusChange = async (record: Shop | Record<string, any>, enabled: boolean) => {
try {
await runWithGlobalLoading(async () => {
@@ -1136,6 +1302,19 @@ onMounted(async () => {
gap: 4px;
}
.map-picker-row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
gap: 8px;
}
.map-picker-tip {
margin-top: 8px;
color: #8c8c8c;
font-size: 12px;
line-height: 1.6;
}
.shop-banner {
display: flex;
align-items: center;
@@ -0,0 +1,350 @@
<template>
<div class="system-messages admin-page">
<a-page-header title="消息发布" sub-title="发布站内消息,支持文本和单张图片" />
<a-card :bordered="false" class="admin-section-card">
<template #title>发布消息</template>
<a-form layout="vertical" :model="form">
<a-form-item label="标题" required>
<a-input v-model:value="form.title" :maxlength="100" placeholder="请输入消息标题" />
</a-form-item>
<a-form-item label="内容">
<a-textarea v-model:value="form.content" :rows="5" :maxlength="2000" placeholder="请输入消息内容,可配合图片展示" />
</a-form-item>
<a-form-item label="消息图片">
<div class="image-upload-row">
<a-upload
accept="image/*"
list-type="picture-card"
:show-upload-list="false"
:custom-request="handleImageUpload"
>
<div v-if="!imagePreviewUrl" class="upload-placeholder">
<span class="upload-plus">+</span>
<span>上传图片</span>
</div>
<img v-else class="message-image-preview" :src="imagePreviewUrl" alt="消息图片预览" />
</a-upload>
<div class="image-upload-copy">
<div>每条消息最多上传一张图片。</div>
<small>建议使用 JPG/PNG/WebP,图片会在弹窗和通知详情中展示。</small>
<a-button v-if="form.imageFileId" type="link" danger size="small" @click="removeImage">移除图片</a-button>
</div>
</div>
</a-form-item>
<a-row :gutter="16">
<a-col :xs="24" :md="10">
<a-form-item label="接收范围" required>
<a-select v-model:value="form.targetType" @change="handleTargetTypeChange">
<a-select-option v-for="item in targetTypes" :key="item.value" :value="item.value">
{{ item.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col v-if="needsShopSelection" :xs="24" :md="14">
<a-form-item label="接收店铺" required>
<a-select v-model:value="form.shopIds" mode="multiple" :options="shopOptions" placeholder="请选择店铺" />
</a-form-item>
</a-col>
<a-col v-if="form.targetType === 'SELECTED_USERS'" :xs="24" :md="14">
<a-form-item label="接收用户" required>
<a-select
v-model:value="form.userIds"
mode="multiple"
show-search
option-filter-prop="label"
:options="userOptions"
placeholder="请选择用户"
/>
</a-form-item>
</a-col>
</a-row>
<a-form-item>
<a-checkbox v-model:checked="popupEnabled">弹窗显示一次</a-checkbox>
</a-form-item>
<a-space>
<a-button type="primary" :loading="saving" @click="handlePublish">发布</a-button>
<a-button @click="resetForm">清空</a-button>
</a-space>
</a-form>
</a-card>
<a-card :bordered="false" class="admin-section-card">
<template #title>发布记录</template>
<a-table :columns="columns" :data-source="messages" :loading="loading" row-key="id" :pagination="{ pageSize: 8 }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'image'">
<a-image v-if="record.imageUrl" :src="record.imageUrl" :width="54" :height="54" class="table-image" />
<span v-else class="muted">无</span>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 1 ? 'green' : 'default'">{{ record.status === 1 ? '已发布' : '已撤回' }}</a-tag>
</template>
<template v-else-if="column.key === 'popupEnabled'">
<a-tag :color="record.popupEnabled === 1 ? 'blue' : 'default'">{{ record.popupEnabled === 1 ? '弹窗' : '不弹窗' }}</a-tag>
</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button type="link" size="small" @click="previewMessage(record as SystemMessageVO)">查看</a-button>
<a-popconfirm v-if="record.status === 1" title="确定撤回这条消息吗?" @confirm="handleRevoke(record.id)">
<a-button type="link" size="small" danger>撤回</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal v-model:open="previewVisible" title="消息详情" :footer="null" width="620px">
<h3>{{ currentMessage?.title }}</h3>
<p class="message-meta">{{ currentMessage?.publisherName }} · {{ currentMessage?.targetTypeName }} · {{ currentMessage?.publishTime }}</p>
<div v-if="currentMessage?.content" class="message-content">{{ currentMessage?.content }}</div>
<img v-if="currentMessage?.imageUrl" class="detail-image" :src="currentMessage.imageUrl" alt="消息图片" />
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* SystemMessagesView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminFileApi, adminSystemMessageApi, type SystemMessageVO, type SystemMessageCreateRequest } from '@/api/admin'
import type { IdType } from '@/utils/id'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** imageUploading is a reactive state variable used by the template and event handlers. */
const imageUploading = ref(false)
const messages = ref<SystemMessageVO[]>([])
/** targetOptions is a reactive state variable used by the template and event handlers. */
const targetOptions = ref({ shops: [] as any[], users: [] as any[] })
/** popupEnabled is a reactive state variable used by the template and event handlers. */
const popupEnabled = ref(true)
/** previewVisible is a reactive state variable used by the template and event handlers. */
const previewVisible = ref(false)
const currentMessage = ref<SystemMessageVO | null>(null)
/** imagePreviewUrl is a reactive state variable used by the template and event handlers. */
const imagePreviewUrl = ref('')
const form = reactive<SystemMessageCreateRequest>({
title: '',
content: '',
imageFileId: undefined,
targetType: 'CURRENT_SHOP_ALL',
shopIds: [],
userIds: [],
popupEnabled: 1
})
/** targetTypes is a reactive state variable used by the template and event handlers. */
const targetTypes = computed(() => {
const shopCount = targetOptions.value.shops.length
const hasPlatformScope = shopCount > 1
return [
...(hasPlatformScope ? [{ label: '全平台', value: 'PLATFORM_ALL' }] : []),
{ label: hasPlatformScope ? '指定店铺全员' : '本店全员', value: hasPlatformScope ? 'SELECTED_SHOPS' : 'CURRENT_SHOP_ALL' },
{ label: '指定用户', value: 'SELECTED_USERS' }
]
})
/** needsShopSelection is a reactive state variable used by the template and event handlers. */
const needsShopSelection = computed(() => form.targetType === 'SELECTED_SHOPS' || form.targetType === 'SHOP_ALL')
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() => targetOptions.value.shops.map(shop => ({ label: shop.shopName, value: shop.id })))
/** userOptions is a reactive state variable used by the template and event handlers. */
const userOptions = computed(() => targetOptions.value.users.map(user => ({
label: `${user.nickname || user.account} ${user.shopName ? `(${user.shopName})` : ''}`,
value: user.id
})))
const columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '图片', key: 'image', width: 84 },
{ title: '范围', dataIndex: 'targetTypeName', key: 'targetTypeName', width: 140 },
{ title: '发布人', dataIndex: 'publisherName', key: 'publisherName', width: 140 },
{ title: '弹窗', key: 'popupEnabled', width: 90 },
{ title: '状态', key: 'status', width: 90 },
{ title: '发布时间', dataIndex: 'publishTime', key: 'publishTime', width: 180 },
{ title: '操作', key: 'action', width: 120 }
]
/** loadData is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadData = async () => {
loading.value = true
try {
const [messageList, options] = await Promise.all([
adminSystemMessageApi.listMessages(),
adminSystemMessageApi.getTargetOptions()
])
messages.value = messageList || []
targetOptions.value = options || { shops: [], users: [] }
if (targetOptions.value.shops.length > 1 && form.targetType === 'CURRENT_SHOP_ALL') {
form.targetType = 'PLATFORM_ALL'
}
} catch (error: any) {
message.error(error?.message || '消息数据加载失败')
} finally {
loading.value = false
}
}
/** handleTargetTypeChange is a local helper used by this page script. */
const handleTargetTypeChange = () => {
form.shopIds = []
form.userIds = []
}
/** removeImage is a local helper used by this page script. */
const removeImage = () => {
form.imageFileId = undefined
imagePreviewUrl.value = ''
}
/** resetForm is a local helper used by this page script. */
const resetForm = () => {
form.title = ''
form.content = ''
form.imageFileId = undefined
form.targetType = targetOptions.value.shops.length > 1 ? 'PLATFORM_ALL' : 'CURRENT_SHOP_ALL'
form.shopIds = []
form.userIds = []
popupEnabled.value = true
imagePreviewUrl.value = ''
}
/** handleImageUpload is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleImageUpload = async (options: any) => {
const file = options.file as File
if (!file?.type?.startsWith('image/')) {
message.warning('请上传图片文件')
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
try {
const uploaded = await adminFileApi.uploadFile(file)
form.imageFileId = uploaded.id
imagePreviewUrl.value = await adminFileApi.getSignedUrl(uploaded.id)
options.onSuccess?.(uploaded)
} catch (error: any) {
message.error(error?.message || '图片上传失败')
options.onError?.(error)
} finally {
imageUploading.value = false
}
}
/** handlePublish is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePublish = async () => {
if (!form.title.trim()) return message.warning('请填写消息标题')
if (!form.content.trim() && !form.imageFileId) return message.warning('请填写消息内容或上传消息图片')
if (imageUploading.value) return message.warning('图片还在上传中,请稍后发布')
if (needsShopSelection.value && !form.shopIds?.length) return message.warning('请选择接收店铺')
if (form.targetType === 'SELECTED_USERS' && !form.userIds?.length) return message.warning('请选择接收用户')
saving.value = true
try {
await adminSystemMessageApi.createMessage({ ...form, popupEnabled: popupEnabled.value ? 1 : 0 })
message.success('消息已发布')
resetForm()
await loadData()
} catch (error: any) {
message.error(error?.message || '消息发布失败')
} finally {
saving.value = false
}
}
/** handleRevoke is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRevoke = async (id: IdType) => {
await adminSystemMessageApi.revokeMessage(id)
message.success('消息已撤回')
await loadData()
}
/** previewMessage is a local helper used by this page script. */
const previewMessage = (record: SystemMessageVO) => {
currentMessage.value = record
previewVisible.value = true
}
onMounted(loadData)
</script>
<style scoped>
.system-messages {
padding: 16px;
}
.admin-section-card {
margin-bottom: 16px;
}
.image-upload-row {
display: flex;
gap: 16px;
align-items: center;
}
.upload-placeholder {
display: grid;
gap: 4px;
color: #8a7b83;
text-align: center;
}
.upload-plus {
font-size: 24px;
line-height: 1;
}
.message-image-preview {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 6px;
}
.image-upload-copy {
color: #5f5660;
line-height: 1.7;
}
.image-upload-copy small,
.message-meta,
.muted {
color: #7f7781;
font-size: 13px;
}
.message-content {
white-space: pre-wrap;
line-height: 1.8;
}
.detail-image {
display: block;
width: 100%;
max-height: 420px;
margin-top: 14px;
object-fit: contain;
border-radius: 8px;
background: #f7f2f4;
}
.table-image {
overflow: hidden;
border-radius: 6px;
object-fit: cover;
}
</style>
@@ -234,6 +234,10 @@
</template>
<script setup lang="ts">
/**
* TagsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
@@ -252,6 +256,7 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
@@ -265,11 +270,17 @@ const getCurrentUserInfo = () => {
return null
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
const formRef = ref<FormInstance>()
const currentTag = ref<any>(null)
@@ -286,6 +297,7 @@ const viewFormState = reactive({
const tagList = ref<any[]>([])
const shops = ref<Shop[]>([])
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
const pagination = reactive({
@@ -305,8 +317,10 @@ const formState = reactive({
borderColor: '#E5E5E5'
})
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-tags', isEdit.value ? 'edit' : 'create', currentTag.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
tagName: formState.tagName,
shopId: formState.shopId,
@@ -315,6 +329,7 @@ const buildDraftPayload = () => ({
borderColor: formState.borderColor
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
@@ -326,12 +341,14 @@ const restoreDraft = () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
@@ -356,6 +373,7 @@ const columns = [
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async () => {
loading.value = true
try {
@@ -377,6 +395,7 @@ const fetchTags = async () => {
}
}
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
loadingShops.value = true
try {
@@ -389,6 +408,7 @@ const fetchShops = async () => {
}
}
/** normalizeShopIdValue is a local helper used by this page script. */
const normalizeShopIdValue = (value: string | number | undefined | null) => {
if (value === undefined || value === null || value === '') {
return ''
@@ -396,23 +416,27 @@ const normalizeShopIdValue = (value: string | number | undefined | null) => {
return String(value)
}
/** getShopName is a local helper used by this page script. */
const getShopName = (shopId: IdType | undefined) => {
const normalizedShopId = normalizeShopIdValue(shopId)
const shop = shops.value.find(s => normalizeShopIdValue(s.id) === normalizedShopId)
return shop ? shop.shopName : '未知店铺'
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchTags())
}
/** 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
await runWithGlobalLoading(() => fetchTags())
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentTag.value = null
@@ -429,6 +453,7 @@ const showAddModal = () => {
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentTag.value = record
@@ -443,6 +468,7 @@ const showEditModal = (record: any) => {
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
Object.assign(viewFormState, {
tagName: record.tagName,
@@ -454,10 +480,12 @@ const showViewModal = (record: any) => {
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
@@ -492,11 +520,13 @@ const handleModalOk = async () => {
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
}
/** handleDelete is a local helper used by this page script. */
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
@@ -445,6 +445,10 @@
</template>
<script setup lang="ts">
/**
* UsersView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
@@ -476,6 +480,7 @@ import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, hasAnyPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** currentUserInfo is a local helper used by this page script. */
const currentUserInfo = (() => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
@@ -486,17 +491,25 @@ const currentUserInfo = (() => {
}
})()
/** normalizeUserType is a local helper used by this page script. */
const normalizeUserType = (value: unknown) => {
const type = Number(value)
return Number.isFinite(type) ? type : -1
}
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** shopLoading is a reactive state variable used by the template and event handlers. */
const shopLoading = ref(false)
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
const formRef = ref<FormInstance>()
const userList = ref<UserVO[]>([])
@@ -505,8 +518,11 @@ const currentUser = ref<UserVO | null>(null)
const viewRecord = ref<UserVO | null>(null)
const draftSavedAt = ref<number | null>(null)
/** assetModalVisible is a reactive state variable used by the template and event handlers. */
const assetModalVisible = ref(false)
/** assetLoading is a reactive state variable used by the template and event handlers. */
const assetLoading = ref(false)
/** assetSaving is a reactive state variable used by the template and event handlers. */
const assetSaving = ref(false)
const assetTargetUser = ref<UserVO | null>(null)
const assetData = ref<UserAssetVO | null>(null)
@@ -514,10 +530,13 @@ const balanceHistory = ref<UserBalanceHistoryItem[]>([])
const balanceDraftSavedAt = ref<number | null>(null)
const vipDraftSavedAt = ref<number | null>(null)
/** canOpenAssetPanel is a reactive state variable used by the template and event handlers. */
const canOpenAssetPanel = computed(() =>
hasAnyPermission(['user:balance:view', 'user:balance:manage', 'user:vip:manage'])
)
/** currentUserType is a reactive state variable used by the template and event handlers. */
const currentUserType = computed(() => normalizeUserType(currentUserInfo?.type))
/** availableUserTypeOptions is a reactive state variable used by the template and event handlers. */
const availableUserTypeOptions = computed(() => {
if (currentUserType.value === 4) {
return [
@@ -540,12 +559,15 @@ const availableUserTypeOptions = computed(() => {
}
return []
})
/** canCreateUser is a reactive state variable used by the template and event handlers. */
const canCreateUser = computed(() =>
hasPermission('user:create') || currentUserType.value === 2 || currentUserType.value === 4
)
/** canDeleteUser is a reactive state variable used by the template and event handlers. */
const canDeleteUser = computed(() =>
currentUserType.value === 4 && hasPermission('user:delete')
)
/** canUnbindUser is a reactive state variable used by the template and event handlers. */
const canUnbindUser = computed(() =>
hasPermission('user:unbind')
)
@@ -569,6 +591,7 @@ const formState = reactive({
shopIds: [] as string[]
})
/** handleAccountInput is a local helper used by this page script. */
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
@@ -576,6 +599,7 @@ const handleAccountInput = () => {
}
}
/** handlePhoneInput is a local helper used by this page script. */
const handlePhoneInput = () => {
const normalized = formState.phone.replace(/\D/g, '').slice(0, 11)
if (normalized !== formState.phone) {
@@ -583,6 +607,7 @@ const handlePhoneInput = () => {
}
}
/** validatePhoneUniqueness is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validatePhoneUniqueness = async (value: string) => {
const normalized = value?.trim()
if (!normalized) {
@@ -620,9 +645,12 @@ const vipForm = reactive<AdminUserVipOverrideRequest>({
remark: ''
})
/** getBalanceDraftKey is a local helper used by this page script. */
const getBalanceDraftKey = () => buildDraftStorageKey('admin-user-assets', 'balance', assetTargetUser.value?.id ?? 'unknown')
/** getVipDraftKey is a local helper used by this page script. */
const getVipDraftKey = () => buildDraftStorageKey('admin-user-assets', 'vip', assetTargetUser.value?.id ?? 'unknown')
/** restoreBalanceDraft is a local helper used by this page script. */
const restoreBalanceDraft = () => {
const draft = loadDraftRecord<{
changeScene: string
@@ -640,6 +668,7 @@ const restoreBalanceDraft = () => {
message.success('已恢复余额变动暂存')
}
/** handleSaveBalanceDraft is a local helper used by this page script. */
const handleSaveBalanceDraft = () => {
const draft = saveDraftRecord(getBalanceDraftKey(), {
changeScene: balanceForm.changeScene,
@@ -652,6 +681,7 @@ const handleSaveBalanceDraft = () => {
message.success('余额变动已暂存到本地')
}
/** handleClearBalanceDraft is a local helper used by this page script. */
const handleClearBalanceDraft = (showMessage = true) => {
clearDraftRecord(getBalanceDraftKey())
balanceDraftSavedAt.value = null
@@ -660,6 +690,7 @@ const handleClearBalanceDraft = (showMessage = true) => {
}
}
/** restoreVipDraft is a local helper used by this page script. */
const restoreVipDraft = () => {
const draft = loadDraftRecord<{
vipLevel: string
@@ -674,6 +705,7 @@ const restoreVipDraft = () => {
message.success('已恢复 VIP 暂存')
}
/** handleSaveVipDraft is a local helper used by this page script. */
const handleSaveVipDraft = () => {
const draft = saveDraftRecord(getVipDraftKey(), {
vipLevel: vipForm.vipLevel,
@@ -683,6 +715,7 @@ const handleSaveVipDraft = () => {
message.success('VIP 设置已暂存到本地')
}
/** handleClearVipDraft is a local helper used by this page script. */
const handleClearVipDraft = (showMessage = true) => {
clearDraftRecord(getVipDraftKey())
vipDraftSavedAt.value = null
@@ -742,6 +775,7 @@ const historyColumns = [
{ title: '时间', key: 'changeTime', width: 180 }
]
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number) => {
const map: Record<number, string> = {
0: '用户',
@@ -752,6 +786,7 @@ const getUserTypeText = (type: number) => {
return map[type] || '未知'
}
/** getUserTypeColor is a local helper used by this page script. */
const getUserTypeColor = (type: number) => {
const map: Record<number, string> = {
0: 'default',
@@ -762,6 +797,7 @@ const getUserTypeColor = (type: number) => {
return map[type] || 'default'
}
/** canShowDelete is a local helper used by this page script. */
const canShowDelete = (record: Partial<UserVO> | Record<string, any>) => {
if (!canDeleteUser.value) {
return false
@@ -772,6 +808,7 @@ const canShowDelete = (record: Partial<UserVO> | Record<string, any>) => {
return String(record.id) !== String(currentUserInfo?.id ?? '')
}
/** canShowUnbind is a local helper used by this page script. */
const canShowUnbind = (record: Partial<UserVO> | Record<string, any>) => {
if (!canUnbindUser.value) {
return false
@@ -779,6 +816,7 @@ const canShowUnbind = (record: Partial<UserVO> | Record<string, any>) => {
return record.type !== 4
}
/** getUnbindConfirmText is a local helper used by this page script. */
const getUnbindConfirmText = (record: Partial<UserVO> | Record<string, any>) => {
if (currentUserType.value === 2 && record.type === 3) {
return '确定要解绑该美甲师与当前店铺的关系吗?解绑后该账号会同步降级为普通用户。'
@@ -786,6 +824,7 @@ const getUnbindConfirmText = (record: Partial<UserVO> | Record<string, any>) =>
return '确定要解绑该用户与当前店铺的关系吗?'
}
/** getSceneText is a local helper used by this page script. */
const getSceneText = (scene?: string) => {
const map: Record<string, string> = {
RECHARGE: '充值',
@@ -797,6 +836,7 @@ const getSceneText = (scene?: string) => {
return scene ? map[scene] || scene : '-'
}
/** formatMoney is a local helper used by this page script. */
const formatMoney = (value?: number | string | null) => {
if (value === undefined || value === null || value === '') {
return '0.00'
@@ -804,6 +844,7 @@ const formatMoney = (value?: number | string | null) => {
return Number(value).toFixed(2)
}
/** formatDate is a local helper used by this page script. */
const formatDate = (value?: string) => {
if (!value) {
return '-'
@@ -811,6 +852,7 @@ const formatDate = (value?: string) => {
return value.replace('T', ' ').slice(0, 19)
}
/** filterVisibleUsers is a local helper used by this page script. */
const filterVisibleUsers = (list: UserVO[]) => {
if (!currentUserInfo || currentUserType.value === 4) {
return list
@@ -824,6 +866,7 @@ const filterVisibleUsers = (list: UserVO[]) => {
return list
}
/** normalizeShopId is a local helper used by this page script. */
const normalizeShopId = (value: unknown) => {
if (value === undefined || value === null || value === '') {
return undefined
@@ -831,8 +874,10 @@ const normalizeShopId = (value: unknown) => {
return String(value)
}
/** getShopOptionValue is a local helper used by this page script. */
const getShopOptionValue = (shop: Shop) => normalizeShopId((shop as any).id) || ''
/** getShopNameById is a local helper used by this page script. */
const getShopNameById = (shopId?: string | number | null) => {
const targetShopId = normalizeShopId(shopId)
if (!targetShopId) {
@@ -842,6 +887,7 @@ const getShopNameById = (shopId?: string | number | null) => {
return matchedShop?.shopName || ''
}
/** getShopDisplay is a local helper used by this page script. */
const getShopDisplay = (user?: Partial<UserVO> | Record<string, any> | null) => {
if (!user) {
return ''
@@ -861,6 +907,7 @@ const getShopDisplay = (user?: Partial<UserVO> | Record<string, any> | null) =>
return getShopNameById(user.shopId) || ''
}
/** resolveEditableShopIds is a local helper used by this page script. */
const resolveEditableShopIds = (user?: UserVO | null) => {
const sourceIds = user?.shopIds?.length
? user.shopIds
@@ -879,6 +926,7 @@ const resolveEditableShopIds = (user?: UserVO | null) => {
: []
}
/** fetchShopList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShopList = async () => {
shopLoading.value = true
try {
@@ -894,6 +942,7 @@ const fetchShopList = async () => {
}
}
/** fetchUserList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserList = async () => {
loading.value = true
try {
@@ -919,6 +968,7 @@ const fetchUserList = async () => {
}
}
/** resetFormState is a local helper used by this page script. */
const resetFormState = () => {
Object.assign(formState, {
account: '',
@@ -932,8 +982,10 @@ const resetFormState = () => {
})
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-users', isEdit.value ? 'edit' : 'create', currentUser.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
account: formState.account,
nickname: formState.nickname,
@@ -943,6 +995,7 @@ const buildDraftPayload = () => ({
shopIds: [...formState.shopIds]
})
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey(), 'session')
if (!draft) {
@@ -955,12 +1008,14 @@ const restoreDraft = () => {
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload(), 'session')
draftSavedAt.value = draft.savedAt
message.success('已暂存到当前会话')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey(), 'session')
draftSavedAt.value = null
@@ -969,17 +1024,20 @@ const handleClearDraft = (showMessage = true) => {
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchUserList())
}
/** 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 || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
await runWithGlobalLoading(() => fetchUserList())
}
/** showAddModal is a local helper used by this page script. */
const showAddModal = () => {
isEdit.value = false
currentUser.value = null
@@ -988,6 +1046,7 @@ const showAddModal = () => {
modalVisible.value = true
}
/** showEditModal is a local helper used by this page script. */
const showEditModal = (record: any) => {
isEdit.value = true
currentUser.value = record
@@ -1003,11 +1062,13 @@ const showEditModal = (record: any) => {
modalVisible.value = true
}
/** showViewModal is a local helper used by this page script. */
const showViewModal = (record: any) => {
viewRecord.value = record
viewModalVisible.value = true
}
/** loadUserAssetData is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadUserAssetData = async (userId: IdType) => {
const [asset, history] = await Promise.all([
adminUserApi.getUserAsset(userId),
@@ -1018,6 +1079,7 @@ const loadUserAssetData = async (userId: IdType) => {
vipForm.vipLevel = asset.vipLevel || '普通'
}
/** resetAssetForms is a local helper used by this page script. */
const resetAssetForms = () => {
Object.assign(balanceForm, {
changeScene: 'RECHARGE',
@@ -1032,6 +1094,7 @@ const resetAssetForms = () => {
})
}
/** showAssetModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showAssetModal = async (record: any) => {
assetTargetUser.value = record
assetModalVisible.value = true
@@ -1052,6 +1115,7 @@ const showAssetModal = async (record: any) => {
}
}
/** handleAssetModalCancel is a local helper used by this page script. */
const handleAssetModalCancel = () => {
assetModalVisible.value = false
assetTargetUser.value = null
@@ -1060,6 +1124,7 @@ const handleAssetModalCancel = () => {
resetAssetForms()
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
await formRef.value?.validate()
@@ -1101,12 +1166,14 @@ const handleModalOk = async () => {
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
resetFormState()
}
/** handleStatusChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleStatusChange = async (record: any, checked: boolean) => {
try {
await runWithGlobalLoading(async () => {
@@ -1125,6 +1192,7 @@ const handleStatusChange = async (record: any, checked: boolean) => {
}
}
/** handleResetPassword is a local helper used by this page script. */
const handleResetPassword = (record: any) => {
Modal.confirm({
title: '确认重置密码',
@@ -1143,6 +1211,7 @@ const handleResetPassword = (record: any) => {
})
}
/** handleDelete is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDelete = async (record: any) => {
try {
if (record.type === 4) {
@@ -1167,6 +1236,7 @@ const handleDelete = async (record: any) => {
}
}
/** handleUnbind is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUnbind = async (record: any) => {
try {
if (record.type === 4) {
@@ -1195,6 +1265,7 @@ const handleUnbind = async (record: any) => {
}
}
/** refreshAssetPanel is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const refreshAssetPanel = async () => {
if (!assetTargetUser.value) {
return
@@ -1212,6 +1283,7 @@ const refreshAssetPanel = async () => {
}
}
/** handleBalanceChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBalanceChange = async () => {
if (!assetTargetUser.value) {
return
@@ -1258,6 +1330,7 @@ const handleBalanceChange = async () => {
}
}
/** handleVipOverride is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleVipOverride = async () => {
if (!assetTargetUser.value) {
return
@@ -1283,6 +1356,7 @@ const handleVipOverride = async () => {
}
}
/** handleVipRecalculate is a local helper used by this page script. */
const handleVipRecalculate = () => {
if (!assetTargetUser.value) {
return
@@ -0,0 +1,149 @@
<template>
<div class="admin-page">
<div class="page-head">
<div>
<h2>VIP 充值配置</h2>
<p>这里只配置展示档位,不会创建支付订单或修改余额。</p>
</div>
<a-button type="primary" @click="openCreate">新增档位</a-button>
</div>
<a-table :columns="columns" :data-source="plans" :loading="loading" row-key="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'amount'">
充 {{ money(record.rechargeAmount) }} 送 {{ money(record.giftAmount) }}
</template>
<template v-else-if="column.key === 'status'">
<a-switch :checked="record.status === 1" @change="checked => toggleStatus(record as VipRechargePlanVO, Boolean(checked))" />
</template>
<template v-else-if="column.key === 'action'">
<a-button size="small" @click="openEdit(record as VipRechargePlanVO)">编辑</a-button>
</template>
</template>
</a-table>
<a-modal v-model:open="formOpen" :title="editingId ? '编辑档位' : '新增档位'" @ok="submit" :confirm-loading="saving">
<a-form layout="vertical">
<a-form-item label="所属店铺">
<a-select v-model:value="form.shopId" :options="shopOptions" allow-clear placeholder="店长默认当前店铺" />
</a-form-item>
<a-form-item label="标题">
<a-input v-model:value="form.title" />
</a-form-item>
<a-form-item label="充值金额">
<a-input-number v-model:value="form.rechargeAmount" :min="0" :precision="2" style="width: 100%" />
</a-form-item>
<a-form-item label="赠送金额">
<a-input-number v-model:value="form.giftAmount" :min="0" :precision="2" style="width: 100%" />
</a-form-item>
<a-form-item label="对应 VIP 等级">
<a-input v-model:value="form.vipLevel" placeholder="如 青铜VIP / 白银VIP / 黄金VIP" />
</a-form-item>
<a-form-item label="展示说明">
<a-textarea v-model:value="form.description" :rows="3" />
</a-form-item>
<a-form-item label="排序">
<a-input-number v-model:value="form.sortOrder" style="width: 100%" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* VipRechargePlansView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminShopApi, adminVipRechargePlanApi, type Shop, type VipRechargePlanVO } from '@/api/admin'
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** saving is a reactive state variable used by the template and event handlers. */
const saving = ref(false)
/** formOpen is a reactive state variable used by the template and event handlers. */
const formOpen = ref(false)
const editingId = ref<any>()
const plans = ref<VipRechargePlanVO[]>([])
const shops = ref<Shop[]>([])
const form = reactive<any>({ shopId: undefined, title: '', rechargeAmount: 0, giftAmount: 0, vipLevel: '', description: '', sortOrder: 0, status: 1 })
const columns = [
{ title: '标题', dataIndex: 'title', key: 'title' },
{ title: '店铺', dataIndex: 'shopName', key: 'shopName' },
{ title: '金额', key: 'amount' },
{ title: 'VIP 等级', dataIndex: 'vipLevel', key: 'vipLevel' },
{ title: '说明', dataIndex: 'description', key: 'description' },
{ title: '启用', key: 'status', width: 100 },
{ title: '操作', key: 'action', width: 100 }
]
const shopOptions = ref<Array<{ label: string; value: any }>>([])
/** money is a local helper used by this page script. */
const money = (value: number | string) => Number(value || 0).toFixed(2)
/** load is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const load = async () => {
loading.value = true
try {
const [planList, shopList] = await Promise.all([
adminVipRechargePlanApi.listPlans(),
adminShopApi.listAllShops().catch(() => [])
])
plans.value = planList || []
shops.value = shopList || []
shopOptions.value = shops.value.map(item => ({ label: item.shopName, value: item.id }))
} finally {
loading.value = false
}
}
/** resetForm is a local helper used by this page script. */
const resetForm = () => Object.assign(form, { shopId: undefined, title: '', rechargeAmount: 0, giftAmount: 0, vipLevel: '', description: '', sortOrder: 0, status: 1 })
/** openCreate is a local helper used by this page script. */
const openCreate = () => { editingId.value = undefined; resetForm(); formOpen.value = true }
/** openEdit is a local helper used by this page script. */
const openEdit = (record: VipRechargePlanVO) => {
editingId.value = record.id
Object.assign(form, record)
formOpen.value = true
}
/** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const submit = async () => {
if (!form.title || !form.vipLevel || Number(form.rechargeAmount) <= 0) {
message.warning('请填写标题、充值金额和 VIP 等级')
return
}
saving.value = true
try {
if (editingId.value) {
await adminVipRechargePlanApi.updatePlan(editingId.value, form)
} else {
await adminVipRechargePlanApi.createPlan(form)
}
message.success('档位已保存')
formOpen.value = false
await load()
} finally {
saving.value = false
}
}
/** toggleStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const toggleStatus = async (record: VipRechargePlanVO, checked: boolean) => {
await adminVipRechargePlanApi.updateStatus(record.id, checked ? 1 : 0)
record.status = checked ? 1 : 0
}
onMounted(load)
</script>
<style scoped>
.admin-page { display: grid; gap: 18px; }
.page-head { display: flex; justify-content: space-between; gap: 16px; align-items: center; }
.page-head h2 { margin: 0 0 4px; }
.page-head p { margin: 0; color: #7a6f68; }
</style>