统一甲屿云命名体系
This commit is contained in:
@@ -0,0 +1,462 @@
|
||||
<template>
|
||||
<el-config-provider>
|
||||
<ConfigProvider :locale="antdLocale" :theme="antdTheme">
|
||||
<div
|
||||
class="app-container"
|
||||
:class="{
|
||||
'app-container--phone-shell': !isAdminShell,
|
||||
'app-container--admin': isAdminShell
|
||||
}"
|
||||
>
|
||||
<div v-if="isAdminShell" class="admin-shell">
|
||||
<div class="page-content no-nav-padding">
|
||||
<router-view v-slot="{ Component }">
|
||||
<component :is="Component" :key="route.path" />
|
||||
</router-view>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="jayu-cloud-phone-frame" :class="{ 'jayu-cloud-phone-frame--hidden-nav': isHiddenNav }">
|
||||
<BottomNav v-if="!isHiddenNav" />
|
||||
<div class="page-content" :class="{ 'no-nav-padding': isHiddenNav }">
|
||||
<router-view v-slot="{ Component }">
|
||||
<component :is="Component" :key="route.path" />
|
||||
</router-view>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ConfigProvider>
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 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, onUnmounted, provide, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ConfigProvider, Modal } from 'ant-design-vue'
|
||||
import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes'
|
||||
import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context'
|
||||
import { CheckOutlined } from '@ant-design/icons-vue'
|
||||
import BottomNav from './components/BottomNav.vue'
|
||||
import SystemMessageCard from './components/SystemMessageCard.vue'
|
||||
import { cartApi } from './api/cart'
|
||||
/**
|
||||
* Purpose: SystemMessageVO supports App.vue by holding or executing the system message vo page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { userApi, type SystemMessageVO } from './api/user'
|
||||
import antdLocale from './config/antdv-locale'
|
||||
import { useGlobalConfirmEnter } from './composables/useConfirmEnter'
|
||||
import { useShopTheme } from './composables/useShopTheme'
|
||||
import { buildSystemMessageActionPath } from './utils/system-message-action'
|
||||
|
||||
/**
|
||||
* Purpose: route supports App.vue by holding or executing the route page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const route = useRoute()
|
||||
/**
|
||||
* Purpose: router supports App.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
const { currentTheme, refreshShopTheme, setupShopThemeSync } = useShopTheme()
|
||||
useGlobalConfirmEnter()
|
||||
/**
|
||||
* Purpose: ButtonPropsWithClass supports App.vue by holding or executing the button props with class page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
type ButtonPropsWithClass = ButtonProps & { class?: string }
|
||||
const popupMessageOkButtonProps: ButtonPropsWithClass = { class: 'popup-message-ok-button' }
|
||||
/** routerReady is a reactive state variable used by the template and event handlers. */
|
||||
const routerReady = ref(false)
|
||||
let stopThemeSync: (() => void) | undefined
|
||||
const adminThemeRefreshOptions = { mode: 'admin' as const }
|
||||
const customerThemeRefreshOptions = { mode: 'customer' as const }
|
||||
|
||||
const isAdminShell = computed(() => route.path.startsWith('/admin') || route.matched.some(r => r.meta.isAdmin))
|
||||
const bottomNavRouteNames = new Set(['home', 'products', 'cart', 'profile'])
|
||||
|
||||
/** isHiddenNav is a reactive state variable used by the template and event handlers. */
|
||||
const isHiddenNav = computed(() => {
|
||||
if (!routerReady.value) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (isAdminShell.value) {
|
||||
return true
|
||||
}
|
||||
|
||||
return !bottomNavRouteNames.has(String(route.name || ''))
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: antdTheme supports App.vue by holding or executing the antd theme page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const antdTheme = computed<ThemeConfig>(() => ({
|
||||
token: {
|
||||
colorPrimary: currentTheme.value.primaryColor,
|
||||
colorLink: currentTheme.value.primaryColor,
|
||||
borderRadius: 8
|
||||
},
|
||||
components: {
|
||||
Button: {
|
||||
colorPrimary: currentTheme.value.primaryColor,
|
||||
colorPrimaryHover: currentTheme.value.accentColor,
|
||||
colorPrimaryActive: currentTheme.value.accentColor
|
||||
},
|
||||
Radio: {
|
||||
colorPrimary: currentTheme.value.primaryColor
|
||||
},
|
||||
Input: {
|
||||
activeBorderColor: currentTheme.value.primaryColor,
|
||||
hoverBorderColor: currentTheme.value.primaryColor
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
// 全局购物车数量状态
|
||||
/** 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 {
|
||||
// 检查用户是否已登录
|
||||
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
|
||||
if (!token) {
|
||||
cartCount.value = 0
|
||||
return
|
||||
}
|
||||
|
||||
const response = await cartApi.getCartList() as any
|
||||
const data = response || []
|
||||
const cartList = Array.isArray(data) ? data : []
|
||||
const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0)
|
||||
cartCount.value = totalQuantity
|
||||
} catch (error) {
|
||||
cartCount.value = 0
|
||||
}
|
||||
}
|
||||
|
||||
// 提供更新购物车数量的方法
|
||||
/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const updateCartCount = async () => {
|
||||
await loadCartCount()
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveSystemMessageActionPath supports App.vue by holding or executing the resolve system message action path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const resolveSystemMessageActionPath = (item: SystemMessageVO) => {
|
||||
return buildSystemMessageActionPath(item)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: openSystemMessageAction supports App.vue by holding or executing the open system message action page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const openSystemMessageAction = async (item: SystemMessageVO) => {
|
||||
const actionPath = resolveSystemMessageActionPath(item)
|
||||
if (!actionPath) {
|
||||
return
|
||||
}
|
||||
await router.push(actionPath)
|
||||
}
|
||||
|
||||
/** 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()
|
||||
}
|
||||
const metaText = `${item.publisherName || '系统消息'} · ${item.publishTime || item.createTime || '刚刚'}`
|
||||
Modal.info({
|
||||
icon: null,
|
||||
centered: true,
|
||||
width: 560,
|
||||
class: 'jayu-cloud-system-message-dialog',
|
||||
wrapClassName: 'jayu-cloud-system-message-wrap',
|
||||
content: h(SystemMessageCard, {
|
||||
title: item.title || '系统消息',
|
||||
content: item.content || '',
|
||||
imageUrl: item.imageUrl || '',
|
||||
meta: metaText,
|
||||
surface: 'modal'
|
||||
}),
|
||||
okText: h('span', { class: 'popup-message-ok-text' }, [
|
||||
h(CheckOutlined),
|
||||
h('span', '我知道了')
|
||||
]),
|
||||
okButtonProps: popupMessageOkButtonProps,
|
||||
async onOk() {
|
||||
await markShownAndResolve()
|
||||
await openSystemMessageAction(item)
|
||||
},
|
||||
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)
|
||||
|
||||
// 监听路由变化,更新购物车数量
|
||||
watch(() => route.path, async () => {
|
||||
// 检查当前是否是后台页面,如果是则不加载购物车数据
|
||||
const isAdminPage = route.matched.some(r => r.meta.isAdmin)
|
||||
await refreshShopTheme(isAdminPage ? adminThemeRefreshOptions : customerThemeRefreshOptions)
|
||||
if (!isAdminPage) {
|
||||
await loadCartCount()
|
||||
await checkPopupMessages()
|
||||
}
|
||||
})
|
||||
|
||||
// 页面加载时获取购物车数量
|
||||
loadCartCount()
|
||||
|
||||
onMounted(async () => {
|
||||
stopThemeSync = setupShopThemeSync()
|
||||
await router.isReady()
|
||||
routerReady.value = true
|
||||
await refreshShopTheme(route.matched.some(r => r.meta.isAdmin) ? adminThemeRefreshOptions : customerThemeRefreshOptions)
|
||||
await checkPopupMessages()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopThemeSync?.()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style>
|
||||
#app {
|
||||
font-family: Avenir, Helvetica, Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.app-container {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.page-content {
|
||||
flex: 1;
|
||||
padding-bottom: 60px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* 当导航栏隐藏时,移除底部 padding */
|
||||
.page-content.no-nav-padding {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-panel-container {
|
||||
overflow: hidden;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 18px 44px rgba(34, 40, 49, 0.18);
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-panel {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-header {
|
||||
padding: 8px 12px;
|
||||
border-bottom-color: var(--theme-border);
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-header button {
|
||||
min-width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-header-view {
|
||||
line-height: 34px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-content th {
|
||||
height: 34px;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-cell {
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.jayu-cloud-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;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-cell:hover .ant-picker-cell-inner {
|
||||
background: var(--theme-primary-soft);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-cell-selected .ant-picker-cell-inner,
|
||||
.jayu-cloud-date-picker-panel .ant-picker-cell-range-start .ant-picker-cell-inner,
|
||||
.jayu-cloud-date-picker-panel .ant-picker-cell-range-end .ant-picker-cell-inner {
|
||||
background: var(--theme-primary);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-picker-panel .ant-picker-footer {
|
||||
border-top-color: var(--theme-border);
|
||||
}
|
||||
|
||||
.jayu-cloud-date-time-panel .ant-picker-time-panel,
|
||||
.jayu-cloud-time-panel .ant-picker-time-panel {
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-time-panel .ant-picker-time-panel-column,
|
||||
.jayu-cloud-time-panel .ant-picker-time-panel-column {
|
||||
width: 76px;
|
||||
padding: 8px 6px;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-time-panel .ant-picker-time-panel-cell-inner,
|
||||
.jayu-cloud-time-panel .ant-picker-time-panel-cell-inner {
|
||||
height: 34px !important;
|
||||
line-height: 34px !important;
|
||||
border-radius: 8px !important;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.jayu-cloud-date-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner,
|
||||
.jayu-cloud-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner {
|
||||
background: var(--theme-primary-soft);
|
||||
color: var(--theme-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.ant-picker {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.ant-picker-focused,
|
||||
.ant-picker:hover {
|
||||
border-color: var(--theme-primary);
|
||||
box-shadow: var(--theme-focus-shadow);
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-wrap .ant-modal {
|
||||
max-width: calc(100vw - 32px);
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .ant-modal-content {
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
border-radius: 8px;
|
||||
background: var(--theme-card-bg);
|
||||
box-shadow: 0 24px 70px rgba(38, 31, 36, 0.32);
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .ant-modal-confirm-body-wrapper {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .ant-modal-confirm-body {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .ant-modal-confirm-content {
|
||||
max-width: none;
|
||||
margin: 0 !important;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .ant-modal-confirm-btns {
|
||||
display: flex;
|
||||
justify-content: stretch;
|
||||
margin: 0;
|
||||
padding: 0 30px 30px;
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .popup-message-ok-button {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
color: #ffffff;
|
||||
font-weight: 700;
|
||||
background: var(--theme-gradient);
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .popup-message-ok-button:hover,
|
||||
.jayu-cloud-system-message-dialog .popup-message-ok-button:focus {
|
||||
color: #ffffff;
|
||||
background: linear-gradient(135deg, var(--theme-accent) 0%, var(--theme-secondary) 100%);
|
||||
}
|
||||
|
||||
.popup-message-ok-text {
|
||||
display: inline-flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.jayu-cloud-system-message-dialog .ant-modal-content {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.jayu-cloud-system-message-dialog .popup-message-ok-button {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Purpose: WEB_API_AUTH_FREE_PATHS supports auth-free-paths.ts by holding or executing the web api auth free paths page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const WEB_API_AUTH_FREE_PATHS = [
|
||||
'/user/login',
|
||||
'/user/register',
|
||||
'/user/check/',
|
||||
'/user/refresh-token',
|
||||
'/user/send-verification-code',
|
||||
'/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/',
|
||||
'/nail-artist/',
|
||||
'/shop/get/',
|
||||
'/shop/trust-profile/',
|
||||
'/shop/list',
|
||||
'/shop/list/public',
|
||||
'/shop/list/simple',
|
||||
'/tag/list/all',
|
||||
'/tag/list/filter-options',
|
||||
'/file/get-signed-url/',
|
||||
'/admin/auth/login',
|
||||
'/admin/auth/login-shops/',
|
||||
'/admin/auth/refresh'
|
||||
] as const
|
||||
|
||||
/**
|
||||
* Purpose: ADMIN_API_AUTH_FREE_PATHS supports auth-free-paths.ts by holding or executing the admin api auth free paths page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ADMIN_API_AUTH_FREE_PATHS = [
|
||||
'/auth/login',
|
||||
'/auth/login-shops/',
|
||||
'/auth/refresh'
|
||||
] as const
|
||||
|
||||
/**
|
||||
* Purpose: normalizePathname supports auth-free-paths.ts by holding or executing the normalize pathname page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const normalizePathname = (url?: string) => {
|
||||
const raw = String(url || '')
|
||||
const withoutHash = raw.split('#')[0] || ''
|
||||
const withoutQuery = withoutHash.split('?')[0] || ''
|
||||
try {
|
||||
return new URL(withoutQuery, 'http://jayucloud.local').pathname
|
||||
} catch {
|
||||
return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: matchesAuthFreePath supports auth-free-paths.ts by holding or executing the matches auth free path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const matchesAuthFreePath = (url: string | undefined, path: string) => {
|
||||
const pathname = normalizePathname(url)
|
||||
if (path.endsWith('/')) {
|
||||
return pathname === path.slice(0, -1) || pathname.startsWith(path)
|
||||
}
|
||||
return pathname === path
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isApiAuthFreePath supports auth-free-paths.ts by holding or executing the is api auth free path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isApiAuthFreePath = (url?: string) => {
|
||||
return WEB_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isAdminApiAuthFreePath supports auth-free-paths.ts by holding or executing the is admin api auth free path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isAdminApiAuthFreePath = (url?: string) => {
|
||||
return ADMIN_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: SendVerificationCodeRequest supports auth.ts by holding or executing the send verification code request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface SendVerificationCodeRequest {
|
||||
phone: string
|
||||
sceneCode?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: LoginRequest supports auth.ts by holding or executing the login request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface LoginRequest {
|
||||
account: string
|
||||
password: string
|
||||
rememberMe?: boolean
|
||||
shopId?: string | number
|
||||
agreementAccepted?: boolean
|
||||
agreementVersions?: Record<string, string>
|
||||
clientType?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: PhoneLoginRequest supports auth.ts by holding or executing the phone login request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface PhoneLoginRequest {
|
||||
phone: string
|
||||
verificationCode: string
|
||||
shopId?: string | number
|
||||
agreementAccepted?: boolean
|
||||
agreementVersions?: Record<string, string>
|
||||
clientType?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: RegisterRequest supports auth.ts by holding or executing the register request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface RegisterRequest {
|
||||
account: string
|
||||
password: string
|
||||
nickname: string
|
||||
shopId?: string | number
|
||||
inviteCode?: string
|
||||
phone?: string
|
||||
verificationCode?: string
|
||||
agreementAccepted?: boolean
|
||||
agreementVersions?: Record<string, string>
|
||||
clientType?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: LegalAgreement supports auth.ts by holding or executing the legal agreement page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface LegalAgreement {
|
||||
id: IdType
|
||||
agreementType: 'USER_TERMS' | 'PRIVACY_POLICY'
|
||||
agreementTypeName: string
|
||||
title: string
|
||||
version: string
|
||||
content: string
|
||||
status: number
|
||||
statusText?: string
|
||||
effectiveTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: LoginResponse supports auth.ts by holding or executing the login response page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface LoginResponse {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
userInfo: UserInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UserInfo supports auth.ts by holding or executing the user info page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UserInfo {
|
||||
id: IdType
|
||||
account: string
|
||||
nickname: string
|
||||
avatar?: string
|
||||
signature?: string
|
||||
type?: number
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
shopAuthorizationExpireTime?: string
|
||||
shopAuthorizationExpired?: boolean
|
||||
shopIds?: IdType[]
|
||||
shopNames?: string[]
|
||||
createTime: string
|
||||
updateTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: RefreshTokenRequest supports auth.ts by holding or executing the refresh token request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface RefreshTokenRequest {
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: RefreshTokenResponse supports auth.ts by holding or executing the refresh token response page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface RefreshTokenResponse {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ResetPasswordRequest supports auth.ts by holding or executing the reset password request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ResetPasswordRequest {
|
||||
phone: string
|
||||
verificationCode: string
|
||||
newPassword: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: SwitchShopRequest supports auth.ts by holding or executing the switch shop request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface 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)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: legalAgreementApi supports auth.ts by holding or executing the legal agreement api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const 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')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
interface CartItem {
|
||||
productId: IdType
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 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 { AxiosProgressEvent } from 'axios'
|
||||
import type { ChunkUploadInitRequest, ChunkUploadSessionVO } from '@/api/file'
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
/**
|
||||
* Purpose: CommentVO supports comment.ts by holding or executing the comment vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CommentVO {
|
||||
id: IdType
|
||||
userId: IdType
|
||||
userNickname?: string
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
commentContent: string
|
||||
parentCommentId?: IdType
|
||||
parentCommentContent?: string
|
||||
likeCount?: number
|
||||
ratingScore?: number
|
||||
imageFileIds?: IdType[]
|
||||
imageUrls?: string[]
|
||||
createTime?: string
|
||||
updateTime?: string
|
||||
replies?: CommentVO[]
|
||||
}
|
||||
|
||||
export interface CommentCreateRequest {
|
||||
productId: IdType
|
||||
shopId?: IdType | null
|
||||
parentCommentId?: IdType | null
|
||||
commentContent: string
|
||||
ratingScore?: number
|
||||
imageFileIds?: IdType[]
|
||||
}
|
||||
|
||||
export interface CommentImageFileVO {
|
||||
id: IdType
|
||||
fileName?: string
|
||||
fileUrl?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: CommentCreateRequest) => {
|
||||
return api.post<IdType>('/comment/create', data) as unknown as Promise<IdType>
|
||||
},
|
||||
uploadImage: (file: File) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
return api.post<CommentImageFileVO>('/comment/upload-image', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
}) as unknown as Promise<CommentImageFileVO>
|
||||
},
|
||||
initImageChunkUpload: (data: ChunkUploadInitRequest) => {
|
||||
return api.post<ChunkUploadSessionVO>('/comment/upload-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
|
||||
},
|
||||
uploadImageChunk: (
|
||||
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
|
||||
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
|
||||
) => {
|
||||
const formData = new FormData()
|
||||
formData.append('uploadId', data.uploadId)
|
||||
formData.append('chunkIndex', String(data.chunkIndex))
|
||||
formData.append('totalChunks', String(data.totalChunks))
|
||||
formData.append('chunk', data.chunk)
|
||||
return api.post<boolean>('/comment/upload-image/chunk', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
signal: config?.signal,
|
||||
onUploadProgress: config?.onUploadProgress
|
||||
})
|
||||
},
|
||||
completeImageChunkUpload: (uploadId: string) => {
|
||||
return api.post<CommentImageFileVO>('/comment/upload-image/complete', { uploadId }) as unknown as Promise<CommentImageFileVO>
|
||||
},
|
||||
cancelImageChunkUpload: (uploadId: string) => {
|
||||
return api.delete<boolean>(`/comment/upload-image/${uploadId}`)
|
||||
},
|
||||
/**
|
||||
* `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
|
||||
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
|
||||
* @param id: IdType caller-supplied value for `id: IdType`
|
||||
*/
|
||||
delete: (id: IdType) => {
|
||||
return api.delete<boolean>(`/comment/delete/${id}`) as unknown as Promise<boolean>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface Coupon {
|
||||
id: IdType
|
||||
couponCode: string
|
||||
couponName: string
|
||||
couponType: number
|
||||
couponTypeName: string
|
||||
discountValue?: number
|
||||
minAmount?: number
|
||||
reduceAmount?: number
|
||||
totalCount: number
|
||||
usedCount: number
|
||||
remainingCount: number
|
||||
startTime: string
|
||||
endTime: string
|
||||
status: number
|
||||
statusName: string
|
||||
shopId?: IdType
|
||||
couponScene?: string
|
||||
requiredVipLevel?: string
|
||||
autoMatch?: number
|
||||
availableTags: Tag[]
|
||||
unavailableTags: Tag[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: Tag supports coupon.ts by holding or executing the tag page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface Tag {
|
||||
id: IdType
|
||||
tagName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UserCoupon {
|
||||
id: IdType
|
||||
couponId: IdType
|
||||
couponName: string
|
||||
couponType: number
|
||||
couponTypeName: string
|
||||
discountValue: string
|
||||
minAmount: string
|
||||
reduceAmount: string
|
||||
startTime: string
|
||||
endTime: string
|
||||
status: number
|
||||
statusName: string
|
||||
obtainTime: string
|
||||
useTime: string
|
||||
sourceType?: string
|
||||
requiredVipLevel?: string
|
||||
autoMatched?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CreateCouponRequest {
|
||||
couponCode: string
|
||||
couponName: string
|
||||
couponType: number
|
||||
discountValue?: number
|
||||
minAmount?: number
|
||||
reduceAmount?: number
|
||||
totalCount: number
|
||||
startTime: string
|
||||
endTime: string
|
||||
couponScene?: string
|
||||
requiredVipLevel?: string
|
||||
autoMatch?: number
|
||||
availableTagIds: IdType[]
|
||||
unavailableTagIds: IdType[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CouponListResponse {
|
||||
list: Coupon[]
|
||||
total: number
|
||||
page: number
|
||||
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',
|
||||
method: 'post',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
// 更新优惠券
|
||||
/**
|
||||
* `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}`,
|
||||
method: 'put',
|
||||
data
|
||||
})
|
||||
},
|
||||
|
||||
// 删除优惠券
|
||||
/**
|
||||
* `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}`,
|
||||
method: 'delete'
|
||||
})
|
||||
},
|
||||
|
||||
// 获取优惠券详情
|
||||
/**
|
||||
* `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}`,
|
||||
method: 'get'
|
||||
})
|
||||
},
|
||||
|
||||
// 获取优惠券列表
|
||||
/**
|
||||
* `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',
|
||||
method: 'get',
|
||||
params
|
||||
})
|
||||
},
|
||||
|
||||
// 为用户分配优惠券
|
||||
/**
|
||||
* `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',
|
||||
method: 'post',
|
||||
params: { userId, couponId }
|
||||
})
|
||||
},
|
||||
|
||||
// 获取用户优惠券列表
|
||||
listUserCoupons: async (status?: number): Promise<UserCoupon[]> => {
|
||||
return await request({
|
||||
url: '/coupon/user/list',
|
||||
method: 'get',
|
||||
params: { status }
|
||||
}) as UserCoupon[]
|
||||
},
|
||||
|
||||
// 使用优惠券
|
||||
/**
|
||||
* `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',
|
||||
method: 'post',
|
||||
params: { userCouponId }
|
||||
})
|
||||
},
|
||||
|
||||
// 获取作品可用的优惠券
|
||||
getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise<UserCoupon[]> => {
|
||||
return await request({
|
||||
url: '/coupon/available',
|
||||
method: 'get',
|
||||
params: { productTags, productPrice, shopId }
|
||||
}) as UserCoupon[]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AxiosError } from 'axios'
|
||||
import {
|
||||
getApiResponseMessage,
|
||||
isPermissionErrorMessage,
|
||||
isSystemFailureResponse,
|
||||
isTokenExpiredMessage,
|
||||
normalizeApiErrorMessage,
|
||||
shouldShowDedupedError,
|
||||
updateSystemFailureWindow
|
||||
} from './error'
|
||||
|
||||
describe('api error helpers', () => {
|
||||
it('extracts messages and classifies error types', () => {
|
||||
const error = { message: 'fallback', response: { data: { message: '服务异常' } } } as AxiosError
|
||||
expect(getApiResponseMessage(error, '请求失败')).toBe('服务异常')
|
||||
expect(isPermissionErrorMessage('权限不足')).toBe(true)
|
||||
expect(isPermissionErrorMessage('permission denied')).toBe(true)
|
||||
expect(isTokenExpiredMessage('登录已过期,请重新登录')).toBe(true)
|
||||
})
|
||||
|
||||
it('dedupes prompts by message and time', () => {
|
||||
expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'a', 40, 50)).toBe(false)
|
||||
expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'b', 100, 50)).toBe(true)
|
||||
})
|
||||
|
||||
it('normalizes garbled booking unavailable messages', () => {
|
||||
expect(normalizeApiErrorMessage('涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试')
|
||||
expect(normalizeApiErrorMessage('创建订单失败:涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试')
|
||||
})
|
||||
|
||||
it('classifies system failure responses', () => {
|
||||
expect(isSystemFailureResponse({ response: { status: 500 } } as AxiosError)).toBe(true)
|
||||
expect(isSystemFailureResponse({ response: { status: 503 } } as AxiosError)).toBe(true)
|
||||
expect(isSystemFailureResponse({ response: { status: 400 } } as AxiosError)).toBe(false)
|
||||
expect(isSystemFailureResponse({ response: undefined } as AxiosError)).toBe(true)
|
||||
})
|
||||
|
||||
it('tracks failure windows with pruning and threshold', () => {
|
||||
expect(updateSystemFailureWindow([1_000, 12_000], 40_000, 30_000, 3)).toEqual({
|
||||
failureTimes: [12_000, 40_000],
|
||||
triggered: false
|
||||
})
|
||||
expect(updateSystemFailureWindow([1_000, 12_000, 20_000], 30_000, 30_000, 3)).toEqual({
|
||||
failureTimes: [1_000, 12_000, 20_000, 30_000],
|
||||
triggered: true
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { AxiosError } from 'axios'
|
||||
|
||||
export interface ApiResponseBody {
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ErrorPromptState {
|
||||
lastErrorTime: number
|
||||
lastErrorMessage: string
|
||||
}
|
||||
|
||||
export interface SystemFailureWindowState {
|
||||
failureTimes: number[]
|
||||
triggered: boolean
|
||||
}
|
||||
|
||||
const BOOKING_UNAVAILABLE_MESSAGE = '不可预约,请调整美甲师或预约时间后重试'
|
||||
const GARbled_BOOKING_UNAVAILABLE_MESSAGES = [
|
||||
'涓嶅彲棰勭害'
|
||||
]
|
||||
|
||||
export const normalizeApiErrorMessage = (messageText: string): string => {
|
||||
const trimmedMessage = String(messageText || '').trim()
|
||||
if (!trimmedMessage) return trimmedMessage
|
||||
if (GARbled_BOOKING_UNAVAILABLE_MESSAGES.some(message => trimmedMessage.includes(message))) {
|
||||
return BOOKING_UNAVAILABLE_MESSAGE
|
||||
}
|
||||
return trimmedMessage
|
||||
}
|
||||
|
||||
export const getApiResponseMessage = (error: AxiosError, fallbackMessage: string): string => {
|
||||
const responseData = error.response?.data as ApiResponseBody | undefined
|
||||
return normalizeApiErrorMessage(responseData?.message || error.message || fallbackMessage)
|
||||
}
|
||||
|
||||
export const isPermissionErrorMessage = (messageText: string): boolean =>
|
||||
messageText.includes('权限') || messageText.includes('permission')
|
||||
|
||||
export const isTokenExpiredMessage = (messageText: string): boolean => (
|
||||
messageText.includes('Token')
|
||||
|| messageText.includes('token')
|
||||
|| messageText.includes('登录态')
|
||||
|| messageText.includes('登录已过期')
|
||||
|| messageText.includes('未登录')
|
||||
|| messageText.includes('认证')
|
||||
|| messageText.includes('重新登录')
|
||||
)
|
||||
|
||||
export const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null): boolean =>
|
||||
Boolean(requestToken && isTokenExpiredMessage(getApiResponseMessage(error, '请求失败')))
|
||||
|
||||
export const isSystemFailureResponse = (error: AxiosError): boolean => {
|
||||
const status = error.response?.status
|
||||
if (typeof status === 'number') {
|
||||
return status >= 500
|
||||
}
|
||||
|
||||
return !error.response
|
||||
}
|
||||
|
||||
export const shouldShowDedupedError = (
|
||||
state: ErrorPromptState,
|
||||
messageText: string,
|
||||
now: number,
|
||||
debounceTime: number
|
||||
): boolean => now - state.lastErrorTime > debounceTime || messageText !== state.lastErrorMessage
|
||||
|
||||
export const updateErrorPromptState = (
|
||||
messageText: string,
|
||||
now: number
|
||||
): ErrorPromptState => ({
|
||||
lastErrorTime: now,
|
||||
lastErrorMessage: messageText
|
||||
})
|
||||
|
||||
export const updateSystemFailureWindow = (
|
||||
failureTimes: number[],
|
||||
now: number,
|
||||
windowMs: number,
|
||||
threshold: number
|
||||
): SystemFailureWindowState => {
|
||||
const nextFailureTimes = failureTimes
|
||||
.filter(failureTime => now - failureTime <= windowMs)
|
||||
.concat(now)
|
||||
|
||||
return {
|
||||
failureTimes: nextFailureTimes,
|
||||
triggered: nextFailureTimes.length >= threshold
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: ChunkUploadInitRequest supports file.ts by holding or executing the chunk upload init request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ChunkUploadInitRequest {
|
||||
fileName: string
|
||||
fileSize: number
|
||||
contentType: string
|
||||
fileFingerprint: string
|
||||
scene: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ChunkUploadSessionVO supports file.ts by holding or executing the chunk upload session vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ChunkUploadSessionVO {
|
||||
uploadId: string
|
||||
chunkSize: number
|
||||
totalChunks: number
|
||||
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)
|
||||
return api.post<string>('/user/upload-avatar', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
})
|
||||
},
|
||||
uploadProfileImage: (file: File) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
return api.post<string>('/user/upload-profile-image', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
}) as unknown as Promise<string>
|
||||
},
|
||||
/**
|
||||
* `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>
|
||||
},
|
||||
uploadAvatarChunk: (
|
||||
/**
|
||||
* Purpose: data supports file.ts by holding or executing the data page or API role.
|
||||
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
|
||||
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
|
||||
) => {
|
||||
const formData = new FormData()
|
||||
formData.append('uploadId', data.uploadId)
|
||||
formData.append('chunkIndex', String(data.chunkIndex))
|
||||
formData.append('totalChunks', String(data.totalChunks))
|
||||
formData.append('chunk', data.chunk)
|
||||
return api.post<boolean>('/user/upload-avatar/chunk', formData, {
|
||||
/**
|
||||
* Purpose: headers supports file.ts by holding or executing the headers page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
/**
|
||||
* Purpose: signal supports file.ts by holding or executing the signal page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
signal: config?.signal,
|
||||
/**
|
||||
* Purpose: onUploadProgress supports file.ts by holding or executing the on upload progress page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
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}`)
|
||||
},
|
||||
initProfileImageChunkUpload: (data: ChunkUploadInitRequest) => {
|
||||
return api.post<ChunkUploadSessionVO>('/user/upload-profile-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
|
||||
},
|
||||
uploadProfileImageChunk: (
|
||||
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
|
||||
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
|
||||
) => {
|
||||
const formData = new FormData()
|
||||
formData.append('uploadId', data.uploadId)
|
||||
formData.append('chunkIndex', String(data.chunkIndex))
|
||||
formData.append('totalChunks', String(data.totalChunks))
|
||||
formData.append('chunk', data.chunk)
|
||||
return api.post<boolean>('/user/upload-profile-image/chunk', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
signal: config?.signal,
|
||||
onUploadProgress: config?.onUploadProgress
|
||||
})
|
||||
},
|
||||
completeProfileImageChunkUpload: (uploadId: string) => {
|
||||
return api.post<string>('/user/upload-profile-image/complete', { uploadId }) as unknown as Promise<string>
|
||||
},
|
||||
cancelProfileImageChunkUpload: (uploadId: string) => {
|
||||
return api.delete<boolean>(`/user/upload-profile-image/${uploadId}`)
|
||||
},
|
||||
|
||||
/**
|
||||
* `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
|
||||
* 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}`, {
|
||||
/**
|
||||
* Purpose: params supports file.ts by holding or executing the params page or API role.
|
||||
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
params: { expiryTimeInMinutes }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* 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'
|
||||
import { wishlistApi } from './wishlist'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import { API_BASE_URL } from '../config/api'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
||||
import { attachRequestSignature } from '@/utils/request-signature'
|
||||
import { isApiAuthFreePath } from './auth-free-paths'
|
||||
import {
|
||||
getApiResponseMessage,
|
||||
isPermissionErrorMessage,
|
||||
isSystemFailureResponse,
|
||||
isTokenExpiredResponse,
|
||||
normalizeApiErrorMessage,
|
||||
shouldShowDedupedError,
|
||||
updateSystemFailureWindow,
|
||||
updateErrorPromptState,
|
||||
type ErrorPromptState
|
||||
} from './error'
|
||||
|
||||
// 防重复提示标志
|
||||
let lastErrorTime = 0
|
||||
/**
|
||||
* Purpose: lastErrorMessage supports index.ts by holding or executing the last error message page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let lastErrorMessage = ''
|
||||
/**
|
||||
* Purpose: ERROR_DEBOUNCE_TIME supports index.ts by holding or executing the error debounce time page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误
|
||||
const SYSTEM_FAILURE_WINDOW_MS = 30 * 1000
|
||||
const SYSTEM_FAILURE_THRESHOLD = 3
|
||||
const SYSTEM_FAILURE_MODAL_COOLDOWN_MS = 60 * 1000
|
||||
const SYSTEM_FAILURE_MODAL_TITLE = '系统暂不可用'
|
||||
const SYSTEM_FAILURE_MODAL_CONTENT = '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。'
|
||||
const SYSTEM_FAILURE_MODAL_OK_TEXT = '我知道了'
|
||||
let systemFailureTimes: number[] = []
|
||||
let systemFailureModalVisible = false
|
||||
let lastSystemFailureModalTime: number | null = null
|
||||
|
||||
/**
|
||||
* Purpose: api supports index.ts by holding or executing the api page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: 60000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: isRefreshing supports index.ts by holding or executing the is refreshing page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let isRefreshing = false
|
||||
let failedQueue: Array<{
|
||||
resolve: (value?: any) => void
|
||||
reject: (reason?: any) => void
|
||||
}> = []
|
||||
|
||||
/**
|
||||
* Purpose: getStoredAccessToken supports index.ts by holding or executing the get stored access token page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getStoredAccessToken = (isAdmin = false) => {
|
||||
return isAdmin
|
||||
? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken'))
|
||||
: (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getStoredRefreshToken = (isAdmin = false) => {
|
||||
return isAdmin
|
||||
? (localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken'))
|
||||
: (localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getRequestToken supports index.ts by holding or executing the get request token page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getRequestToken = (request: any) => {
|
||||
if (request?._authToken) {
|
||||
return request._authToken as string
|
||||
}
|
||||
|
||||
const authHeader = request?.headers?.Authorization || request?.headers?.authorization
|
||||
if (typeof authHeader !== 'string') {
|
||||
return null
|
||||
}
|
||||
|
||||
return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isCurrentStoredToken supports index.ts by holding or executing the is current stored token page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isCurrentStoredToken = (token: string | null, isAdmin = false) => {
|
||||
return Boolean(token && token === getStoredAccessToken(isAdmin))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: processQueue supports index.ts by holding or executing the process queue page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const processQueue = (error: unknown, token: string | null = null) => {
|
||||
failedQueue.forEach(prom => {
|
||||
if (error) {
|
||||
prom.reject(error)
|
||||
} else {
|
||||
prom.resolve(token)
|
||||
}
|
||||
})
|
||||
failedQueue = []
|
||||
}
|
||||
|
||||
// 防抖处理错误提示
|
||||
const showError = (msg: string) => {
|
||||
const now = Date.now()
|
||||
const state: ErrorPromptState = { lastErrorTime, lastErrorMessage }
|
||||
if (!shouldShowDedupedError(state, msg, now, ERROR_DEBOUNCE_TIME)) {
|
||||
return
|
||||
}
|
||||
|
||||
const nextState = updateErrorPromptState(msg, now)
|
||||
lastErrorTime = nextState.lastErrorTime
|
||||
lastErrorMessage = nextState.lastErrorMessage
|
||||
message.error(msg)
|
||||
}
|
||||
|
||||
const resetSystemFailureWindow = () => {
|
||||
systemFailureTimes = []
|
||||
}
|
||||
|
||||
const showSystemFailureModal = (now: number) => {
|
||||
if (
|
||||
systemFailureModalVisible
|
||||
|| (
|
||||
lastSystemFailureModalTime !== null
|
||||
&& now - lastSystemFailureModalTime < SYSTEM_FAILURE_MODAL_COOLDOWN_MS
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
systemFailureModalVisible = true
|
||||
lastSystemFailureModalTime = now
|
||||
Modal.error({
|
||||
title: SYSTEM_FAILURE_MODAL_TITLE,
|
||||
content: SYSTEM_FAILURE_MODAL_CONTENT,
|
||||
okText: SYSTEM_FAILURE_MODAL_OK_TEXT,
|
||||
onOk: () => {
|
||||
systemFailureModalVisible = false
|
||||
},
|
||||
afterClose: () => {
|
||||
systemFailureModalVisible = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const recordSystemFailure = (error: AxiosError): boolean => {
|
||||
if (!isSystemFailureResponse(error)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const nextState = updateSystemFailureWindow(
|
||||
systemFailureTimes,
|
||||
now,
|
||||
SYSTEM_FAILURE_WINDOW_MS,
|
||||
SYSTEM_FAILURE_THRESHOLD
|
||||
)
|
||||
systemFailureTimes = nextState.failureTimes
|
||||
if (nextState.triggered) {
|
||||
showSystemFailureModal(now)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isAuthFreePath supports index.ts by holding or executing the is auth free path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isAuthFreePath = (url?: string) => {
|
||||
return isApiAuthFreePath(url)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: handleTokenExpired supports index.ts by holding or executing the handle token expired page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) => {
|
||||
if (!isCurrentStoredToken(failedToken, isAdmin)) {
|
||||
return
|
||||
}
|
||||
|
||||
// 清理token和用户信息
|
||||
if (isAdmin) {
|
||||
// 清理后台管理的token
|
||||
clearAdminSessionStorage()
|
||||
} else {
|
||||
// 清理前台的token
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
localStorage.removeItem('userInfo')
|
||||
sessionStorage.removeItem('accessToken')
|
||||
sessionStorage.removeItem('refreshToken')
|
||||
}
|
||||
|
||||
// 显示错误提示
|
||||
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
|
||||
showError('登录已过期,请重新登录')
|
||||
}
|
||||
|
||||
// 执行跳转,确保无论如何都会跳转
|
||||
setTimeout(() => {
|
||||
if (isAdmin) {
|
||||
window.location.href = '/admin/login'
|
||||
} else {
|
||||
window.location.href = '/'
|
||||
}
|
||||
}, 500) // 延迟执行,确保错误提示先显示
|
||||
}
|
||||
|
||||
api.interceptors.request.use(
|
||||
async config => {
|
||||
const isAdminRequest = config.url?.includes('/admin/') || config.url?.includes('/order/admin/')
|
||||
let token = isAdminRequest
|
||||
? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken'))
|
||||
: (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken'))
|
||||
|
||||
// 检查是否是后台管理的API请求
|
||||
if (!token && (config.url?.includes('/admin/') || config.url?.includes('/order/admin/'))) {
|
||||
token = localStorage.getItem('adminAccessToken')
|
||||
if (!token) {
|
||||
token = sessionStorage.getItem('adminAccessToken')
|
||||
}
|
||||
}
|
||||
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
;(config as any)._authToken = token || null
|
||||
return attachRequestSignature(config, token, {
|
||||
authFree: isAuthFreePath(config.url)
|
||||
})
|
||||
},
|
||||
error => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
api.interceptors.response.use(
|
||||
response => {
|
||||
resetSystemFailureWindow()
|
||||
const res = response.data
|
||||
if (res.code !== 200) {
|
||||
const errorMsg = normalizeApiErrorMessage(res.message || '请求失败')
|
||||
if (!isPermissionErrorMessage(errorMsg)) {
|
||||
showError(errorMsg)
|
||||
}
|
||||
return Promise.reject(new Error(errorMsg))
|
||||
}
|
||||
return res.data as any
|
||||
},
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as any
|
||||
|
||||
const isWhitelistedPath = (url: string) => {
|
||||
return isApiAuthFreePath(url)
|
||||
}
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
// 检查是否是后台管理的API请求
|
||||
const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/')
|
||||
const requestToken = getRequestToken(originalRequest)
|
||||
const isRealTokenExpired = isTokenExpiredResponse(error, requestToken)
|
||||
|
||||
if (!isRealTokenExpired) {
|
||||
showError(getApiResponseMessage(error, '请求失败'))
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (!isCurrentStoredToken(requestToken, isAdminRequest)) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
|
||||
if (isRefreshing) {
|
||||
return new Promise((resolve, reject) => {
|
||||
failedQueue.push({ resolve, reject })
|
||||
}).then(token => {
|
||||
if (token) {
|
||||
originalRequest.headers.Authorization = `Bearer ${token}`
|
||||
originalRequest._authToken = token
|
||||
}
|
||||
return api(originalRequest)
|
||||
}).catch(err => {
|
||||
return Promise.reject(err)
|
||||
})
|
||||
}
|
||||
|
||||
originalRequest._retry = true
|
||||
isRefreshing = true
|
||||
|
||||
try {
|
||||
let refreshToken
|
||||
if (isAdminRequest) {
|
||||
refreshToken = getStoredRefreshToken(true)
|
||||
} else {
|
||||
refreshToken = getStoredRefreshToken(false)
|
||||
}
|
||||
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available')
|
||||
}
|
||||
|
||||
// 这里需要根据是否是后台请求调用不同的refreshToken API
|
||||
// 暂时使用同一个API,实际项目中可能需要分开
|
||||
const response = isAdminRequest
|
||||
? await adminAuthApi.refreshToken(refreshToken)
|
||||
: await authApi.refreshToken({ refreshToken })
|
||||
const newToken = (response as any).accessToken
|
||||
const newRefreshToken = (response as any).refreshToken
|
||||
|
||||
if (isAdminRequest) {
|
||||
localStorage.setItem('adminAccessToken', newToken)
|
||||
localStorage.setItem('adminRefreshToken', newRefreshToken)
|
||||
sessionStorage.setItem('adminAccessToken', newToken)
|
||||
} else {
|
||||
localStorage.setItem('accessToken', newToken)
|
||||
localStorage.setItem('refreshToken', newRefreshToken)
|
||||
sessionStorage.setItem('accessToken', newToken)
|
||||
sessionStorage.setItem('refreshToken', newRefreshToken)
|
||||
}
|
||||
|
||||
processQueue(null, newToken)
|
||||
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
originalRequest._authToken = newToken
|
||||
return api(originalRequest)
|
||||
} catch (refreshError) {
|
||||
processQueue(refreshError, null)
|
||||
handleTokenExpired(isAdminRequest, requestToken)
|
||||
return Promise.reject(refreshError)
|
||||
} finally {
|
||||
isRefreshing = false
|
||||
}
|
||||
} else {
|
||||
handleTokenExpired(isAdminRequest, requestToken)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
} else if (error.response?.status !== 403) { // 403权限不足不提示
|
||||
const errorMsg = getApiResponseMessage(error, '请求失败')
|
||||
if (!recordSystemFailure(error)) {
|
||||
showError(errorMsg)
|
||||
}
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export { wishlistApi }
|
||||
|
||||
export default api
|
||||
@@ -0,0 +1,92 @@
|
||||
import api from './index'
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
export interface NailArtistAvailabilityVO {
|
||||
startTime: string
|
||||
endTime: string
|
||||
dateText: string
|
||||
timeText: string
|
||||
available: boolean
|
||||
}
|
||||
|
||||
export interface NailArtistWorkVO {
|
||||
id: IdType
|
||||
title?: string
|
||||
description?: string
|
||||
price?: number | string
|
||||
coverImageUrl?: string
|
||||
imageUrls?: string[]
|
||||
tags?: string[]
|
||||
likeCount?: number
|
||||
collectCount?: number
|
||||
}
|
||||
|
||||
export interface NailArtistReviewVO {
|
||||
id: IdType
|
||||
artistId: IdType
|
||||
customerId?: IdType
|
||||
customerName?: string
|
||||
customerAvatar?: string
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
rating?: number | string
|
||||
content?: string
|
||||
imageFileIds?: IdType[]
|
||||
imageUrls?: string[]
|
||||
submittedAt?: string
|
||||
}
|
||||
|
||||
export interface NailArtistListItemVO {
|
||||
id?: IdType
|
||||
userId?: IdType
|
||||
identity?: string
|
||||
experience?: number
|
||||
skills?: string
|
||||
rating?: number | string
|
||||
status?: number
|
||||
participateProduction?: number
|
||||
workStartTime?: string
|
||||
workEndTime?: string
|
||||
userType?: number
|
||||
userTypeName?: string
|
||||
portfolio?: string
|
||||
nickname?: string
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
signature?: string
|
||||
}
|
||||
|
||||
export interface NailArtistProfileVO {
|
||||
artistId: IdType
|
||||
artistName?: string
|
||||
avatar?: string
|
||||
identity?: string
|
||||
signature?: string
|
||||
experience?: number
|
||||
status?: number
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
rating?: number | string
|
||||
serviceCount?: number | string
|
||||
workStartTime?: string
|
||||
workEndTime?: string
|
||||
styleTags?: string[]
|
||||
works?: NailArtistWorkVO[]
|
||||
reviews?: NailArtistReviewVO[]
|
||||
availability?: NailArtistAvailabilityVO[]
|
||||
}
|
||||
|
||||
export const nailArtistApi = {
|
||||
getPublicProfile: async (artistId: IdType): Promise<NailArtistProfileVO> => {
|
||||
return await api.get<NailArtistProfileVO>(`/nail-artist/profile/${artistId}`) as unknown as NailArtistProfileVO
|
||||
},
|
||||
getAvailability: async (artistId: IdType): Promise<NailArtistAvailabilityVO[]> => {
|
||||
return await api.get<NailArtistAvailabilityVO[]>(`/nail-artist/${artistId}/availability`) as unknown as NailArtistAvailabilityVO[]
|
||||
},
|
||||
listReviews: async (artistId: IdType): Promise<NailArtistReviewVO[]> => {
|
||||
return await api.get<NailArtistReviewVO[]>(`/nail-artist/${artistId}/reviews`) as unknown as NailArtistReviewVO[]
|
||||
},
|
||||
listByShopId: async (shopId: IdType): Promise<NailArtistListItemVO[]> => {
|
||||
return await api.get<NailArtistListItemVO[]>(`/nail-artist/list/shop/${shopId}`) as unknown as NailArtistListItemVO[]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: OrderItem supports order.ts by holding or executing the order item page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderItem {
|
||||
productId: IdType
|
||||
quantity: number
|
||||
artistId?: IdType
|
||||
appointmentTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CreateOrderRequest supports order.ts by holding or executing the create order request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CreateOrderRequest {
|
||||
couponId?: IdType
|
||||
couponSourceType?: string
|
||||
remark?: string
|
||||
clientRequestId?: string
|
||||
items: OrderItem[]
|
||||
}
|
||||
|
||||
export type CheckoutPreviewRequest = CreateOrderRequest
|
||||
|
||||
export interface CheckoutCouponPreview {
|
||||
id: IdType
|
||||
couponId?: IdType
|
||||
userCouponId?: IdType
|
||||
sourceType?: string
|
||||
couponName: string
|
||||
couponType: number
|
||||
couponTypeName?: string
|
||||
discountValue?: number
|
||||
minAmount?: number
|
||||
reduceAmount?: number
|
||||
discountAmount?: number
|
||||
available?: boolean
|
||||
best?: boolean
|
||||
vipAuto?: boolean
|
||||
displayText?: string
|
||||
savingText?: string
|
||||
unavailableReason?: string
|
||||
startTime?: string
|
||||
endTime?: string
|
||||
}
|
||||
|
||||
export interface CheckoutIssue {
|
||||
code: string
|
||||
message: string
|
||||
itemId?: IdType
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
}
|
||||
|
||||
export interface CheckoutPreview {
|
||||
subtotalAmount: number
|
||||
savedAmount: number
|
||||
payableAmount: number
|
||||
bestCoupon?: CheckoutCouponPreview
|
||||
availableCoupons: CheckoutCouponPreview[]
|
||||
unavailableCoupons: CheckoutCouponPreview[]
|
||||
bookingAvailable?: boolean
|
||||
bookingIssues?: CheckoutIssue[]
|
||||
vipTip?: string
|
||||
summaryText?: string
|
||||
}
|
||||
|
||||
export interface PaymentOrderVO {
|
||||
id: IdType
|
||||
payNo?: string
|
||||
orderId: IdType
|
||||
orderNo?: string
|
||||
userId?: IdType
|
||||
shopId?: IdType
|
||||
channel?: string
|
||||
status?: string
|
||||
payAmount?: number
|
||||
paidAmount?: number
|
||||
payTime?: string
|
||||
expireTime?: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export interface OrderQuoteItem {
|
||||
orderItemId: IdType
|
||||
quotedPrice?: number
|
||||
}
|
||||
|
||||
export interface OrderQuoteSubmitRequest {
|
||||
remark?: string
|
||||
items: OrderQuoteItem[]
|
||||
}
|
||||
|
||||
export interface OrderQuoteReplyRequest {
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export interface OrderQuoteMessage {
|
||||
id: IdType
|
||||
orderId: IdType
|
||||
actorId?: IdType
|
||||
actorType?: string
|
||||
actorTypeText?: string
|
||||
action?: string
|
||||
actionText?: string
|
||||
remark?: string
|
||||
items?: any[]
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
export interface AfterSaleApplyRequest {
|
||||
orderId: IdType
|
||||
orderItemId?: IdType
|
||||
type: string
|
||||
reason: string
|
||||
refundAmount?: number
|
||||
}
|
||||
|
||||
export interface AfterSaleVO {
|
||||
id: IdType
|
||||
afterSaleNo?: string
|
||||
orderId: IdType
|
||||
orderItemId?: IdType
|
||||
userId?: IdType
|
||||
shopId?: IdType
|
||||
type?: string
|
||||
reason?: string
|
||||
refundAmount?: number
|
||||
status?: string
|
||||
auditReason?: string
|
||||
auditTime?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
export interface PageResult<T> {
|
||||
list: T[]
|
||||
total: number
|
||||
page: number
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface GrowthSummaryVO {
|
||||
userId?: IdType
|
||||
growthValue?: number
|
||||
levelName?: string
|
||||
appointmentCount?: number
|
||||
reviewCount?: number
|
||||
}
|
||||
|
||||
export const paymentApi = {
|
||||
prepareOrderPayment: async (orderId: IdType): Promise<PaymentOrderVO> => {
|
||||
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO
|
||||
},
|
||||
mockSuccess: async (orderId: IdType): Promise<PaymentOrderVO> => {
|
||||
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO
|
||||
}
|
||||
}
|
||||
|
||||
export const afterSaleApi = {
|
||||
apply: async (data: AfterSaleApplyRequest): Promise<AfterSaleVO> => {
|
||||
return await api.post<AfterSaleVO>('/after-sale/apply', data) as unknown as AfterSaleVO
|
||||
},
|
||||
listMy: async (params: { page: number; size: number }): Promise<PageResult<AfterSaleVO>> => {
|
||||
return await api.get<PageResult<AfterSaleVO>>('/after-sale/my', { params }) as unknown as PageResult<AfterSaleVO>
|
||||
}
|
||||
}
|
||||
|
||||
export const growthApi = {
|
||||
getSummary: async (): Promise<GrowthSummaryVO> => {
|
||||
return await api.get<GrowthSummaryVO>('/growth/summary') as unknown as GrowthSummaryVO
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ArtistCalendarAppointment supports order.ts by holding or executing the artist calendar appointment page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: OrderArtistReviewVO supports order.ts by holding or executing the order artist review vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderArtistReviewVO {
|
||||
id: IdType
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
artistId?: IdType
|
||||
artistName?: string
|
||||
artistAvatar?: string
|
||||
userId?: IdType
|
||||
rating?: number
|
||||
content?: string
|
||||
imageFileIds?: IdType[]
|
||||
status?: number
|
||||
statusText?: string
|
||||
submitTime?: string
|
||||
reviewTime?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: OrderArtistReviewSubmitRequest supports order.ts by holding or executing the order artist review submit request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderArtistReviewSubmitRequest {
|
||||
rating: number
|
||||
content?: string
|
||||
imageFileIds: IdType[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: OrderArtistChangeOptionsVO supports order.ts by holding or executing the order artist change options vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderArtistChangeOptionsVO {
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
currentArtistId?: IdType
|
||||
currentArtistName?: string
|
||||
artists: Array<{
|
||||
artistId: IdType
|
||||
artistName: string
|
||||
artistAvatar?: string
|
||||
userType?: number
|
||||
participateProduction?: boolean
|
||||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: OrderArtistChangeRequestVO supports order.ts by holding or executing the order artist change request vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderArtistChangeRequestVO {
|
||||
id: IdType
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
shopId?: IdType
|
||||
userId?: IdType
|
||||
customerId?: IdType
|
||||
originalArtistId?: IdType
|
||||
originalArtistName?: string
|
||||
requestedArtistId?: IdType
|
||||
requestedArtistName?: string
|
||||
fromArtistId?: IdType
|
||||
fromArtistName?: string
|
||||
toArtistId?: IdType
|
||||
toArtistName?: string
|
||||
requesterId?: IdType
|
||||
requesterName?: string
|
||||
status?: string
|
||||
statusText?: string
|
||||
reason?: string
|
||||
rejectReason?: string
|
||||
appointmentTime?: string
|
||||
timeAffected?: boolean
|
||||
timeImpactText?: string
|
||||
originalPrice?: number | string
|
||||
newPrice?: number | string
|
||||
priceAffected?: boolean
|
||||
priceImpactText?: string
|
||||
reviewerId?: IdType
|
||||
messageId?: IdType
|
||||
reviewTime?: string
|
||||
approvedTime?: string
|
||||
rejectedTime?: string
|
||||
expireTime?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: OrderArtistChangeRequestSubmitRequest supports order.ts by holding or executing the order artist change request submit request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderArtistChangeRequestSubmitRequest {
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
requestedArtistId: IdType
|
||||
reason: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: OrderArtistChangeRejectRequest supports order.ts by holding or executing the order artist change reject request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface OrderArtistChangeRejectRequest {
|
||||
rejectReason?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
},
|
||||
|
||||
createInquiryAppointment: (data: CreateOrderRequest) => {
|
||||
return api.post('/order/create', data)
|
||||
},
|
||||
|
||||
checkoutPreview: async (data: CheckoutPreviewRequest): Promise<CheckoutPreview> => {
|
||||
return await api.post<CheckoutPreview>('/order/checkout-preview', data) as unknown as CheckoutPreview
|
||||
},
|
||||
|
||||
replyQuote: async (orderId: IdType, data?: OrderQuoteReplyRequest): Promise<any> => {
|
||||
return await api.post(`/order/${orderId}/quote/reply`, data || {}) as unknown as any
|
||||
},
|
||||
|
||||
confirmUserQuote: async (orderId: IdType): Promise<any> => {
|
||||
return await api.put(`/order/${orderId}/quote/confirm`) as unknown as any
|
||||
},
|
||||
|
||||
submitShopQuote: async (orderId: IdType, data: OrderQuoteSubmitRequest): Promise<any> => {
|
||||
return await api.post(`/order/${orderId}/quote/shop`, data) as unknown as any
|
||||
},
|
||||
|
||||
confirmShopQuote: async (orderId: IdType): Promise<any> => {
|
||||
return await api.put(`/order/${orderId}/quote/shop/confirm`) as unknown as any
|
||||
},
|
||||
|
||||
// 获取订单列表
|
||||
getOrderList: async (): Promise<any[]> => {
|
||||
return await api.get<any[]>('/order/list') as unknown as any[]
|
||||
},
|
||||
|
||||
getMyPendingReviews: async (): Promise<OrderArtistReviewVO[]> => {
|
||||
return await api.get<OrderArtistReviewVO[]>('/order/review/my-pending') as unknown as OrderArtistReviewVO[]
|
||||
},
|
||||
|
||||
getOrderReviews: async (orderId: IdType): Promise<OrderArtistReviewVO[]> => {
|
||||
return await api.get<OrderArtistReviewVO[]>(`/order/${orderId}/reviews`) as unknown as OrderArtistReviewVO[]
|
||||
},
|
||||
|
||||
submitArtistReview: async (reviewId: IdType, data: OrderArtistReviewSubmitRequest): Promise<OrderArtistReviewVO> => {
|
||||
return await api.post<OrderArtistReviewVO>(`/order/review/${reviewId}/submit`, data) as unknown as OrderArtistReviewVO
|
||||
},
|
||||
|
||||
getArtistChangeOptions: async (orderId: IdType, orderItemId: IdType): Promise<OrderArtistChangeOptionsVO> => {
|
||||
return await api.get<OrderArtistChangeOptionsVO>(`/order/${orderId}/artist-change/options`, {
|
||||
params: { orderItemId }
|
||||
}) as unknown as OrderArtistChangeOptionsVO
|
||||
},
|
||||
|
||||
requestArtistChange: async (data: OrderArtistChangeRequestSubmitRequest): Promise<OrderArtistChangeRequestVO> => {
|
||||
return await api.post<OrderArtistChangeRequestVO>('/order/artist-change/request', data) as unknown as OrderArtistChangeRequestVO
|
||||
},
|
||||
|
||||
getMyPendingArtistChangeRequests: async (): Promise<OrderArtistChangeRequestVO[]> => {
|
||||
return await api.get<OrderArtistChangeRequestVO[]>('/order/artist-change/my-pending') as unknown as OrderArtistChangeRequestVO[]
|
||||
},
|
||||
|
||||
getOrderArtistChangeRequests: async (orderId: IdType): Promise<OrderArtistChangeRequestVO[]> => {
|
||||
return await api.get<OrderArtistChangeRequestVO[]>(`/order/${orderId}/artist-change/requests`) as unknown as OrderArtistChangeRequestVO[]
|
||||
},
|
||||
|
||||
approveArtistChange: async (requestId: IdType): Promise<OrderArtistChangeRequestVO> => {
|
||||
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/approve`) as unknown as OrderArtistChangeRequestVO
|
||||
},
|
||||
|
||||
rejectArtistChange: async (requestId: IdType, data?: OrderArtistChangeRejectRequest): Promise<OrderArtistChangeRequestVO> => {
|
||||
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/reject`, data || {}) as unknown as OrderArtistChangeRequestVO
|
||||
},
|
||||
|
||||
// 获取订单详情
|
||||
/**
|
||||
* `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 }
|
||||
})
|
||||
},
|
||||
|
||||
// 美甲师查看自己的订单
|
||||
/**
|
||||
* `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[]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: PermissionVO supports permission.ts by holding or executing the permission vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface PermissionVO {
|
||||
id: IdType
|
||||
permissionCode: string
|
||||
permissionName: string
|
||||
permissionGroup: string
|
||||
description: string
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CreatePermissionRequest supports permission.ts by holding or executing the create permission request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CreatePermissionRequest {
|
||||
permissionCode: string
|
||||
permissionName: string
|
||||
permissionGroup: string
|
||||
description: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdatePermissionRequest supports permission.ts by holding or executing the update permission request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdatePermissionRequest {
|
||||
permissionCode?: string
|
||||
permissionName?: string
|
||||
permissionGroup?: string
|
||||
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}`)
|
||||
}
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: ProductVO supports product.ts by holding or executing the product vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ProductVO {
|
||||
id: IdType
|
||||
shopId: IdType | null
|
||||
shopName?: string
|
||||
name: string
|
||||
title?: string
|
||||
description: string
|
||||
targetAudience?: string
|
||||
precautions?: string
|
||||
image: string
|
||||
imageFileIds?: string
|
||||
imageUrls?: string[]
|
||||
price: number
|
||||
estimatedTime: number
|
||||
approximateDuration?: string
|
||||
serviceDurationMinutes?: number
|
||||
bookableArtists?: string
|
||||
availableBookableArtistCount?: number
|
||||
bookableArtistRestricted?: boolean
|
||||
availableCoupons?: string
|
||||
category: string
|
||||
tags?: string
|
||||
tagList?: string[]
|
||||
tagInfos?: TagInfo[]
|
||||
status: number
|
||||
likeCount?: number
|
||||
collectCount?: number
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: TagInfo supports product.ts by holding or executing the tag info page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface TagInfo {
|
||||
id: IdType
|
||||
tagName: string
|
||||
textColor?: string
|
||||
bgColor?: string
|
||||
borderColor?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ListProductsParams supports product.ts by holding or executing the list products params page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ListProductsParams {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
tag?: string
|
||||
tagIds?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CreateProductRequest supports product.ts by holding or executing the create product request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CreateProductRequest {
|
||||
name: string
|
||||
description: string
|
||||
image: string
|
||||
price: number
|
||||
estimatedTime: number
|
||||
category: string
|
||||
status: number
|
||||
shopId: IdType | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdateProductRequest supports product.ts by holding or executing the update product request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdateProductRequest {
|
||||
name?: string
|
||||
description?: string
|
||||
image?: string
|
||||
price?: number
|
||||
estimatedTime?: number
|
||||
category?: string
|
||||
status?: number
|
||||
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[]
|
||||
},
|
||||
|
||||
getProductById: async (id: IdType): Promise<ProductVO> => {
|
||||
return await api.get<ProductVO>(`/product/get/${id}`) as unknown as ProductVO
|
||||
},
|
||||
|
||||
getProductsByTag: async (tag: string): Promise<ProductVO[]> => {
|
||||
return await api.get<ProductVO[]>(`/product/list/tag/${tag}`) as unknown as ProductVO[]
|
||||
},
|
||||
|
||||
likeProduct: async (productId: IdType): Promise<boolean> => {
|
||||
return await api.post<boolean>(`/product-like/like/${productId}`) as unknown as boolean
|
||||
},
|
||||
|
||||
unlikeProduct: async (productId: IdType): Promise<boolean> => {
|
||||
return await api.post<boolean>(`/product-like/unlike/${productId}`) as unknown as boolean
|
||||
},
|
||||
|
||||
searchProducts: async (keyword: string): Promise<ProductVO[]> => {
|
||||
return await api.get<ProductVO[]>('/product/list/search', {
|
||||
params: {
|
||||
keyword: keyword
|
||||
}
|
||||
}) as unknown as ProductVO[]
|
||||
},
|
||||
|
||||
getProductPage: async (params: ListProductsParams): Promise<{ list: ProductVO[]; total: number; page: number; size: number }> => {
|
||||
return await api.get('/product/list/page', { params }) as unknown as { list: ProductVO[]; total: number; page: number; size: number }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 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}`)
|
||||
},
|
||||
|
||||
/**
|
||||
* 取消点赞作品
|
||||
* @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}`)
|
||||
},
|
||||
|
||||
/**
|
||||
* 检查用户是否已点赞作品
|
||||
* @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}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: ShopVO supports shop.ts by holding or executing the shop vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ShopVO {
|
||||
id: IdType
|
||||
shopName: string
|
||||
description: string
|
||||
address: string
|
||||
mapProvider?: string
|
||||
longitude?: number | string
|
||||
latitude?: number | string
|
||||
navigationUrls?: Record<string, string>
|
||||
businessHours: string
|
||||
status?: number
|
||||
authorizationStartDate?: string
|
||||
authorizationDays?: number
|
||||
authorizationExpireTime?: string
|
||||
authorizationExpired?: boolean
|
||||
authorizationStatusText?: string
|
||||
coverImageFileId?: string
|
||||
coverImageUrls?: string[]
|
||||
imageFileIds: string
|
||||
imageUrls?: string[]
|
||||
themePrimaryColor?: string
|
||||
themeSecondaryColor?: string
|
||||
themeAccentColor?: string
|
||||
themePageBgColor?: string
|
||||
themeCardBgColor?: string
|
||||
themeBackgroundImageFileId?: string
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ShopSimpleVO supports shop.ts by holding or executing the shop simple vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ShopSimpleVO {
|
||||
id: string | number
|
||||
shopName?: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page.
|
||||
* Usage: fetch it with getTrustProfile and render ratings, recent reviews, environment images, and booking hints.
|
||||
*/
|
||||
export interface ShopTrustProfileVO {
|
||||
shopId: IdType
|
||||
shopName?: string
|
||||
businessHoursText?: string
|
||||
businessStatusText?: string
|
||||
locationAvailable?: boolean
|
||||
distanceCapabilityText?: string
|
||||
navigationAvailable?: boolean
|
||||
stats?: {
|
||||
averageRating?: number
|
||||
reviewCount?: number
|
||||
productCount?: number
|
||||
artistCount?: number
|
||||
recentReviewCount?: number
|
||||
}
|
||||
environmentImages?: string[]
|
||||
featuredProducts?: Array<{
|
||||
id: IdType
|
||||
title?: string
|
||||
imageUrl?: string
|
||||
imageFileIds?: string
|
||||
price?: number
|
||||
likeCount?: number
|
||||
collectCount?: number
|
||||
availableBookableArtistCount?: number
|
||||
bookingHint?: string
|
||||
}>
|
||||
recentReviews?: Array<{
|
||||
id: IdType
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
ratingScore?: number
|
||||
content?: string
|
||||
imageUrls?: string[]
|
||||
submittedAt?: string
|
||||
}>
|
||||
availabilitySummary?: {
|
||||
available?: boolean
|
||||
summaryText?: string
|
||||
nextSlots?: string[]
|
||||
}
|
||||
contactSummary?: {
|
||||
actionText?: string
|
||||
phoneExposed?: boolean
|
||||
phone?: string
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ListShopsParams supports shop.ts by holding or executing the list shops params page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ListShopsParams {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CreateShopRequest supports shop.ts by holding or executing the create shop request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CreateShopRequest {
|
||||
name: string
|
||||
description: string
|
||||
image: string
|
||||
phone: string
|
||||
address: string
|
||||
businessHours: string
|
||||
status: number
|
||||
authorizationStartDate?: string
|
||||
authorizationDays?: number
|
||||
authorizationExpireTime?: string
|
||||
themePrimaryColor?: string
|
||||
themeSecondaryColor?: string
|
||||
themeAccentColor?: string
|
||||
themePageBgColor?: string
|
||||
themeCardBgColor?: string
|
||||
themeBackgroundImageFileId?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdateShopRequest supports shop.ts by holding or executing the update shop request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdateShopRequest {
|
||||
name?: string
|
||||
description?: string
|
||||
image?: string
|
||||
phone?: string
|
||||
address?: string
|
||||
businessHours?: string
|
||||
status?: number
|
||||
authorizationStartDate?: string
|
||||
authorizationDays?: number
|
||||
authorizationExpireTime?: string
|
||||
themePrimaryColor?: string
|
||||
themeSecondaryColor?: string
|
||||
themeAccentColor?: string
|
||||
themePageBgColor?: string
|
||||
themeCardBgColor?: string
|
||||
themeBackgroundImageFileId?: 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[]
|
||||
},
|
||||
|
||||
getPublicShops: async (): Promise<ShopVO[]> => {
|
||||
return await api.get<ShopVO[]>('/shop/list/public') as unknown as ShopVO[]
|
||||
},
|
||||
|
||||
getShopsSimple: async (): Promise<ShopSimpleVO[]> => {
|
||||
return await api.get<ShopSimpleVO[]>('/shop/list/simple') as unknown as ShopSimpleVO[]
|
||||
},
|
||||
|
||||
getShopById: async (id: IdType): Promise<ShopVO> => {
|
||||
return await api.get<ShopVO>(`/shop/get/${id}`) as unknown as ShopVO
|
||||
},
|
||||
|
||||
getTrustProfile: async (id: IdType): Promise<ShopTrustProfileVO> => {
|
||||
return await api.get<ShopTrustProfileVO>(`/shop/trust-profile/${id}`) as unknown as ShopTrustProfileVO
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: TagVO supports tag.ts by holding or executing the tag vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface TagVO {
|
||||
id: IdType
|
||||
tagName: string
|
||||
textColor: string
|
||||
bgColor: string
|
||||
borderColor: string
|
||||
sceneGroup?: string
|
||||
displayName?: string
|
||||
sortOrder?: number
|
||||
frontVisible?: number
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: TagFilterGroupVO groups public tags for scene filters.
|
||||
* Usage: render each group as one filter row and pass selected tag ids to product list APIs.
|
||||
*/
|
||||
export interface TagFilterGroupVO {
|
||||
groupName: string
|
||||
tags: TagVO[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: TagDTO supports tag.ts by holding or executing the tag dto page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface TagDTO {
|
||||
tagName: string
|
||||
textColor: string
|
||||
bgColor: string
|
||||
borderColor: string
|
||||
sceneGroup?: string
|
||||
displayName?: string
|
||||
sortOrder?: number
|
||||
frontVisible?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 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')
|
||||
},
|
||||
|
||||
/**
|
||||
* `getFilterOptions` API call. Use this method to load customer-facing scene filters.
|
||||
* Call guide: optionally pass shopId, await the grouped tags, then query products with tagIds.
|
||||
*/
|
||||
getFilterOptions: (shopId?: IdType | null) => {
|
||||
return api.get<TagFilterGroupVO[]>('/tag/list/filter-options', {
|
||||
params: shopId ? { shopId } : undefined
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* `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}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: UserVO supports user.ts by holding or executing the user vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UserVO extends UserInfo {
|
||||
id: IdType
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
shopIds?: IdType[]
|
||||
shopNames?: string[]
|
||||
nickname: string
|
||||
account: string
|
||||
avatar: string
|
||||
signature?: string
|
||||
level?: string
|
||||
type: number
|
||||
vipId?: IdType
|
||||
createTime: string
|
||||
updateTime: string
|
||||
status: number
|
||||
phone?: string
|
||||
contactPhone?: string
|
||||
birthday?: string
|
||||
wechatId?: string
|
||||
wechatQrCode?: string
|
||||
email?: string
|
||||
maskedPhone?: string
|
||||
maskedEmail?: string
|
||||
shopRoleId?: IdType
|
||||
shopRoleName?: string
|
||||
parentUserId?: IdType
|
||||
parentUserName?: string
|
||||
parentUserTypeName?: string
|
||||
relationSourceType?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdateUserInfoRequest supports user.ts by holding or executing the update user info request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdateUserInfoRequest {
|
||||
nickname?: string
|
||||
avatar?: string
|
||||
signature?: string
|
||||
contactPhone?: string
|
||||
birthday?: string
|
||||
wechatId?: string
|
||||
wechatQrCode?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ListUsersParams supports user.ts by holding or executing the list users params page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ListUsersParams {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
shopId?: IdType
|
||||
status?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CreateUserRequest supports user.ts by holding or executing the create user request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface CreateUserRequest {
|
||||
account: string
|
||||
nickname: string
|
||||
phone: string
|
||||
contactPhone?: string
|
||||
birthday?: string
|
||||
wechatId?: string
|
||||
wechatQrCode?: string
|
||||
password: string
|
||||
type: number
|
||||
shopId?: IdType
|
||||
shopIds?: IdType[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdateUserRequest supports user.ts by holding or executing the update user request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdateUserRequest {
|
||||
account?: string
|
||||
nickname?: string
|
||||
phone?: string
|
||||
contactPhone?: string
|
||||
birthday?: string
|
||||
wechatId?: string
|
||||
wechatQrCode?: string
|
||||
type?: number
|
||||
shopId?: IdType
|
||||
shopIds?: IdType[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdatePasswordRequest supports user.ts by holding or executing the update password request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdatePasswordRequest {
|
||||
password: string
|
||||
verificationCode: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: BindPhoneRequest supports user.ts by holding or executing the bind phone request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface BindPhoneRequest {
|
||||
phone: string
|
||||
verificationCode: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: AvailabilityCheckResponse supports user.ts by holding or executing the availability check response page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface AvailabilityCheckResponse {
|
||||
available: boolean
|
||||
message: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: LoginAccountCheckResponse supports user.ts by holding or executing the login account check response page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface LoginAccountCheckResponse {
|
||||
exists: boolean
|
||||
nickname?: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: LoginShopSelectionResponse supports user.ts by holding or executing the login shop selection response page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface LoginShopSelectionResponse {
|
||||
allowShoplessLogin: boolean
|
||||
message: string
|
||||
shops: Array<{
|
||||
id: IdType
|
||||
shopName: string
|
||||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UserRelationVO supports user.ts by holding or executing the user relation vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UserRelationVO {
|
||||
userId: IdType
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
parentUserId?: IdType
|
||||
parentUserName?: string
|
||||
parentRoleType?: number
|
||||
parentRoleTypeName?: string
|
||||
sourceType?: string
|
||||
sourceTypeName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: NailArtistInfoVO supports user.ts by holding or executing the nail artist info vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface NailArtistInfoVO {
|
||||
userId?: IdType
|
||||
userType?: number
|
||||
participateProduction?: number | boolean
|
||||
status?: number
|
||||
}
|
||||
|
||||
// 用户端常用接口约定:
|
||||
// - 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UpdatePhoneRequest supports user.ts by holding or executing the update phone request page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface UpdatePhoneRequest {
|
||||
oldPhone: string
|
||||
newPhone: string
|
||||
verificationCode: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: UserAssetVO supports user.ts by holding or executing the user asset vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: BalanceHistoryItem supports user.ts by holding or executing the balance history item page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: SystemMessageVO supports user.ts by holding or executing the system message vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface SystemMessageVO {
|
||||
id: IdType
|
||||
title: string
|
||||
content: string
|
||||
imageFileId?: IdType
|
||||
imageUrl?: string
|
||||
publisherName?: string
|
||||
targetType?: string
|
||||
targetTypeName?: string
|
||||
businessType?: string
|
||||
businessId?: IdType
|
||||
actionPath?: string
|
||||
popupEnabled?: number
|
||||
popupShown?: number
|
||||
readStatus?: number
|
||||
publishTime?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: AnnouncementVO supports user.ts by holding or executing the announcement vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface AnnouncementVO {
|
||||
id: IdType
|
||||
title: string
|
||||
content: string
|
||||
publisherName?: string
|
||||
targetType?: string
|
||||
status?: number
|
||||
sortOrder?: number
|
||||
publishTime?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: VipRechargePlanVO supports user.ts by holding or executing the vip recharge plan vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface VipRechargePlanVO {
|
||||
id: IdType
|
||||
shopId: IdType
|
||||
shopName?: string
|
||||
title: string
|
||||
rechargeAmount: number
|
||||
giftAmount: number
|
||||
vipLevel: string
|
||||
description?: string
|
||||
sortOrder?: number
|
||||
status: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ContactInfoVO supports user.ts by holding or executing the contact info vo page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ContactInfoVO {
|
||||
contactUserId?: IdType
|
||||
contactName?: string
|
||||
roleLabel?: string
|
||||
phone?: string
|
||||
phoneAvailable?: boolean
|
||||
wechatId?: string
|
||||
wechatAvailable?: boolean
|
||||
wechatQrCode?: string
|
||||
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)
|
||||
},
|
||||
getUserByAccount: async (account: string): Promise<UserVO> => {
|
||||
return await api.get<UserVO>(`/user/get/account/${account}`) as unknown as UserVO
|
||||
},
|
||||
checkAccountAvailability: async (account: string): Promise<AvailabilityCheckResponse> => {
|
||||
return await api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse
|
||||
},
|
||||
checkLoginAccountAvailability: async (account: string): Promise<LoginAccountCheckResponse> => {
|
||||
return await api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse
|
||||
},
|
||||
getLoginShopsByAccount: async (account: string): Promise<LoginShopSelectionResponse> => {
|
||||
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse
|
||||
},
|
||||
getLoginShopsByPhone: async (phone: string): Promise<LoginShopSelectionResponse> => {
|
||||
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/phone/${encodeURIComponent(phone)}`) as unknown as LoginShopSelectionResponse
|
||||
},
|
||||
checkPhoneAvailability: async (phone: string): Promise<AvailabilityCheckResponse> => {
|
||||
return await api.get<AvailabilityCheckResponse>(`/user/check/phone/${encodeURIComponent(phone)}`) as unknown as AvailabilityCheckResponse
|
||||
},
|
||||
listUsersByType: async (type: number): Promise<UserVO[]> => {
|
||||
return await api.get<UserVO[]>(`/user/list/type/${type}`) as unknown as UserVO[]
|
||||
},
|
||||
/**
|
||||
* `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
|
||||
},
|
||||
getNailArtistInfo: async (userId: IdType): Promise<NailArtistInfoVO | null> => {
|
||||
return await api.get<NailArtistInfoVO | null>(`/nail-artist/get/${userId}`) as unknown as NailArtistInfoVO | null
|
||||
},
|
||||
// 注册页输入邀请码时先解析,给用户展示“将归属到谁/哪个店铺”。
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
/**
|
||||
* Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface WishlistItem {
|
||||
id: IdType
|
||||
userId: IdType
|
||||
productId: IdType
|
||||
groupId?: IdType | null
|
||||
groupName?: string | null
|
||||
note?: string | null
|
||||
sortOrder?: number | null
|
||||
product: {
|
||||
id: IdType
|
||||
shopId: IdType | null
|
||||
shopName?: string
|
||||
title: string
|
||||
description: string
|
||||
imageFileIds?: string
|
||||
imageUrls?: string[]
|
||||
price: number
|
||||
tags?: string
|
||||
tagList?: string[]
|
||||
tagInfos?: any[]
|
||||
likeCount?: number
|
||||
collectCount?: number
|
||||
approximateDuration?: string
|
||||
bookableArtists?: string
|
||||
availableCoupons?: string
|
||||
createTime: string
|
||||
updateTime: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface WishlistGroup {
|
||||
id: IdType
|
||||
name: string
|
||||
sortOrder: number
|
||||
itemCount: number
|
||||
items?: WishlistItem[]
|
||||
}
|
||||
|
||||
export interface WishlistInspiration {
|
||||
total: number
|
||||
groups: WishlistGroup[]
|
||||
}
|
||||
|
||||
export interface WishlistGroupPayload {
|
||||
name: string
|
||||
sortOrder?: number
|
||||
}
|
||||
|
||||
export interface WishlistAddWithGroupPayload {
|
||||
productId: IdType
|
||||
groupId?: IdType | null
|
||||
note?: string
|
||||
sortOrder?: number
|
||||
}
|
||||
|
||||
export interface WishlistMovePayload {
|
||||
wishlistId?: IdType
|
||||
productId?: IdType
|
||||
groupId?: IdType | null
|
||||
note?: string
|
||||
sortOrder?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
},
|
||||
|
||||
removeFromWishlist: async (productId: IdType): Promise<boolean> => {
|
||||
return await api.post<boolean>('/wishlist/remove', { productId }) as unknown as boolean
|
||||
},
|
||||
|
||||
checkWishlist: async (productId: IdType): Promise<boolean> => {
|
||||
return await api.get<boolean>(`/wishlist/check?productId=${productId}`) as unknown as boolean
|
||||
},
|
||||
|
||||
getWishlist: async (): Promise<WishlistItem[]> => {
|
||||
return await api.get<WishlistItem[]>('/wishlist/list') as unknown as WishlistItem[]
|
||||
},
|
||||
|
||||
getGroups: async (): Promise<WishlistGroup[]> => {
|
||||
return await api.get<WishlistGroup[]>('/wishlist/groups') as unknown as WishlistGroup[]
|
||||
},
|
||||
|
||||
createGroup: async (payload: WishlistGroupPayload): Promise<IdType> => {
|
||||
return await api.post<IdType>('/wishlist/groups', payload) as unknown as IdType
|
||||
},
|
||||
|
||||
updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise<boolean> => {
|
||||
return await api.put<boolean>(`/wishlist/groups/${id}`, payload) as unknown as boolean
|
||||
},
|
||||
|
||||
deleteGroup: async (id: IdType): Promise<boolean> => {
|
||||
return await api.delete<boolean>(`/wishlist/groups/${id}`) as unknown as boolean
|
||||
},
|
||||
|
||||
addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise<boolean> => {
|
||||
return await api.post<boolean>('/wishlist/add-with-group', payload) as unknown as boolean
|
||||
},
|
||||
|
||||
moveWishlist: async (payload: WishlistMovePayload): Promise<boolean> => {
|
||||
return await api.post<boolean>('/wishlist/move', payload) as unknown as boolean
|
||||
},
|
||||
|
||||
getInspiration: async (): Promise<WishlistInspiration> => {
|
||||
return await api.get<WishlistInspiration>('/wishlist/inspiration') as unknown as WishlistInspiration
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 496 B |
+90
@@ -0,0 +1,90 @@
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// @ts-nocheck
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// Generated by unplugin-auto-import
|
||||
// biome-ignore lint: disable
|
||||
export {}
|
||||
declare global {
|
||||
const EffectScope: typeof import('vue').EffectScope
|
||||
const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate
|
||||
const computed: typeof import('vue').computed
|
||||
const createApp: typeof import('vue').createApp
|
||||
const createPinia: typeof import('pinia').createPinia
|
||||
const customRef: typeof import('vue').customRef
|
||||
const defineAsyncComponent: typeof import('vue').defineAsyncComponent
|
||||
const defineComponent: typeof import('vue').defineComponent
|
||||
const defineStore: typeof import('pinia').defineStore
|
||||
const effectScope: typeof import('vue').effectScope
|
||||
const getActivePinia: typeof import('pinia').getActivePinia
|
||||
const getCurrentInstance: typeof import('vue').getCurrentInstance
|
||||
const getCurrentScope: typeof import('vue').getCurrentScope
|
||||
const getCurrentWatcher: typeof import('vue').getCurrentWatcher
|
||||
const h: typeof import('vue').h
|
||||
const inject: typeof import('vue').inject
|
||||
const isProxy: typeof import('vue').isProxy
|
||||
const isReactive: typeof import('vue').isReactive
|
||||
const isReadonly: typeof import('vue').isReadonly
|
||||
const isRef: typeof import('vue').isRef
|
||||
const isShallow: typeof import('vue').isShallow
|
||||
const mapActions: typeof import('pinia').mapActions
|
||||
const mapGetters: typeof import('pinia').mapGetters
|
||||
const mapState: typeof import('pinia').mapState
|
||||
const mapStores: typeof import('pinia').mapStores
|
||||
const mapWritableState: typeof import('pinia').mapWritableState
|
||||
const markRaw: typeof import('vue').markRaw
|
||||
const nextTick: typeof import('vue').nextTick
|
||||
const onActivated: typeof import('vue').onActivated
|
||||
const onBeforeMount: typeof import('vue').onBeforeMount
|
||||
const onBeforeRouteLeave: typeof import('vue-router').onBeforeRouteLeave
|
||||
const onBeforeRouteUpdate: typeof import('vue-router').onBeforeRouteUpdate
|
||||
const onBeforeUnmount: typeof import('vue').onBeforeUnmount
|
||||
const onBeforeUpdate: typeof import('vue').onBeforeUpdate
|
||||
const onDeactivated: typeof import('vue').onDeactivated
|
||||
const onErrorCaptured: typeof import('vue').onErrorCaptured
|
||||
const onMounted: typeof import('vue').onMounted
|
||||
const onRenderTracked: typeof import('vue').onRenderTracked
|
||||
const onRenderTriggered: typeof import('vue').onRenderTriggered
|
||||
const onScopeDispose: typeof import('vue').onScopeDispose
|
||||
const onServerPrefetch: typeof import('vue').onServerPrefetch
|
||||
const onUnmounted: typeof import('vue').onUnmounted
|
||||
const onUpdated: typeof import('vue').onUpdated
|
||||
const onWatcherCleanup: typeof import('vue').onWatcherCleanup
|
||||
const provide: typeof import('vue').provide
|
||||
const reactive: typeof import('vue').reactive
|
||||
const readonly: typeof import('vue').readonly
|
||||
const ref: typeof import('vue').ref
|
||||
const resolveComponent: typeof import('vue').resolveComponent
|
||||
const setActivePinia: typeof import('pinia').setActivePinia
|
||||
const setMapStoreSuffix: typeof import('pinia').setMapStoreSuffix
|
||||
const shallowReactive: typeof import('vue').shallowReactive
|
||||
const shallowReadonly: typeof import('vue').shallowReadonly
|
||||
const shallowRef: typeof import('vue').shallowRef
|
||||
const storeToRefs: typeof import('pinia').storeToRefs
|
||||
const toRaw: typeof import('vue').toRaw
|
||||
const toRef: typeof import('vue').toRef
|
||||
const toRefs: typeof import('vue').toRefs
|
||||
const toValue: typeof import('vue').toValue
|
||||
const triggerRef: typeof import('vue').triggerRef
|
||||
const unref: typeof import('vue').unref
|
||||
const useAttrs: typeof import('vue').useAttrs
|
||||
const useCssModule: typeof import('vue').useCssModule
|
||||
const useCssVars: typeof import('vue').useCssVars
|
||||
const useId: typeof import('vue').useId
|
||||
const useLink: typeof import('vue-router').useLink
|
||||
const useModel: typeof import('vue').useModel
|
||||
const useRoute: typeof import('vue-router').useRoute
|
||||
const useRouter: typeof import('vue-router').useRouter
|
||||
const useSlots: typeof import('vue').useSlots
|
||||
const useTemplateRef: typeof import('vue').useTemplateRef
|
||||
const watch: typeof import('vue').watch
|
||||
const watchEffect: typeof import('vue').watchEffect
|
||||
const watchPostEffect: typeof import('vue').watchPostEffect
|
||||
const watchSyncEffect: typeof import('vue').watchSyncEffect
|
||||
}
|
||||
// for type re-export
|
||||
declare global {
|
||||
// @ts-ignore
|
||||
export type { Component, Slot, Slots, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, ShallowRef, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
|
||||
import('vue')
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
/* eslint-disable */
|
||||
// @ts-nocheck
|
||||
// biome-ignore lint: disable
|
||||
// oxlint-disable
|
||||
// ------
|
||||
// Generated by unplugin-vue-components
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
|
||||
export {}
|
||||
|
||||
/* prettier-ignore */
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
AAlert: typeof import('ant-design-vue/es')['Alert']
|
||||
AAvatar: typeof import('ant-design-vue/es')['Avatar']
|
||||
ABadge: typeof import('ant-design-vue/es')['Badge']
|
||||
AButton: typeof import('ant-design-vue/es')['Button']
|
||||
ACard: typeof import('ant-design-vue/es')['Card']
|
||||
ACarousel: typeof import('ant-design-vue/es')['Carousel']
|
||||
ACheckbox: typeof import('ant-design-vue/es')['Checkbox']
|
||||
ACheckboxGroup: typeof import('ant-design-vue/es')['CheckboxGroup']
|
||||
ACol: typeof import('ant-design-vue/es')['Col']
|
||||
ACollapse: typeof import('ant-design-vue/es')['Collapse']
|
||||
ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
|
||||
ADatePicker: typeof import('ant-design-vue/es')['DatePicker']
|
||||
ADescriptions: typeof import('ant-design-vue/es')['Descriptions']
|
||||
ADescriptionsItem: typeof import('ant-design-vue/es')['DescriptionsItem']
|
||||
ADivider: typeof import('ant-design-vue/es')['Divider']
|
||||
AdminFilterPanel: typeof import('./components/admin/AdminFilterPanel.vue')['default']
|
||||
AdminMobileCardList: typeof import('./components/admin/AdminMobileCardList.vue')['default']
|
||||
AdminMobileFab: typeof import('./components/admin/AdminMobileFab.vue')['default']
|
||||
AdminResponsiveModal: typeof import('./components/admin/AdminResponsiveModal.vue')['default']
|
||||
ADrawer: typeof import('ant-design-vue/es')['Drawer']
|
||||
ADropdown: typeof import('ant-design-vue/es')['Dropdown']
|
||||
AEmpty: typeof import('ant-design-vue/es')['Empty']
|
||||
AForm: typeof import('ant-design-vue/es')['Form']
|
||||
AFormItem: typeof import('ant-design-vue/es')['FormItem']
|
||||
AImage: typeof import('ant-design-vue/es')['Image']
|
||||
AInput: typeof import('ant-design-vue/es')['Input']
|
||||
AInputNumber: typeof import('ant-design-vue/es')['InputNumber']
|
||||
AInputPassword: typeof import('ant-design-vue/es')['InputPassword']
|
||||
AInputSearch: typeof import('ant-design-vue/es')['InputSearch']
|
||||
ALayout: typeof import('ant-design-vue/es')['Layout']
|
||||
ALayoutContent: typeof import('ant-design-vue/es')['LayoutContent']
|
||||
ALayoutHeader: typeof import('ant-design-vue/es')['LayoutHeader']
|
||||
ALayoutSider: typeof import('ant-design-vue/es')['LayoutSider']
|
||||
AList: typeof import('ant-design-vue/es')['List']
|
||||
AListItem: typeof import('ant-design-vue/es')['ListItem']
|
||||
AListItemMeta: typeof import('ant-design-vue/es')['ListItemMeta']
|
||||
AMenu: typeof import('ant-design-vue/es')['Menu']
|
||||
AMenuDivider: typeof import('ant-design-vue/es')['MenuDivider']
|
||||
AMenuItem: typeof import('ant-design-vue/es')['MenuItem']
|
||||
AModal: typeof import('ant-design-vue/es')['Modal']
|
||||
APageHeader: typeof import('ant-design-vue/es')['PageHeader']
|
||||
APopconfirm: typeof import('ant-design-vue/es')['Popconfirm']
|
||||
AProgress: typeof import('ant-design-vue/es')['Progress']
|
||||
ARadio: typeof import('ant-design-vue/es')['Radio']
|
||||
ARadioButton: typeof import('ant-design-vue/es')['RadioButton']
|
||||
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
|
||||
ARangePicker: typeof import('ant-design-vue/es')['RangePicker']
|
||||
AResult: typeof import('ant-design-vue/es')['Result']
|
||||
ARow: typeof import('ant-design-vue/es')['Row']
|
||||
ASegmented: typeof import('ant-design-vue/es')['Segmented']
|
||||
ASelect: typeof import('ant-design-vue/es')['Select']
|
||||
ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
|
||||
ASkeleton: typeof import('ant-design-vue/es')['Skeleton']
|
||||
ASpace: typeof import('ant-design-vue/es')['Space']
|
||||
ASpin: typeof import('ant-design-vue/es')['Spin']
|
||||
AStatistic: typeof import('ant-design-vue/es')['Statistic']
|
||||
ASwitch: typeof import('ant-design-vue/es')['Switch']
|
||||
ATable: typeof import('ant-design-vue/es')['Table']
|
||||
ATabPane: typeof import('ant-design-vue/es')['TabPane']
|
||||
ATabs: typeof import('ant-design-vue/es')['Tabs']
|
||||
ATag: typeof import('ant-design-vue/es')['Tag']
|
||||
ATextarea: typeof import('ant-design-vue/es')['Textarea']
|
||||
ATimeline: typeof import('ant-design-vue/es')['Timeline']
|
||||
ATimelineItem: typeof import('ant-design-vue/es')['TimelineItem']
|
||||
ATooltip: typeof import('ant-design-vue/es')['Tooltip']
|
||||
ATypographyText: typeof import('ant-design-vue/es')['TypographyText']
|
||||
AUpload: typeof import('ant-design-vue/es')['Upload']
|
||||
BottomNav: typeof import('./components/BottomNav.vue')['default']
|
||||
DraftActions: typeof import('./components/DraftActions.vue')['default']
|
||||
ElButton: typeof import('element-plus/es')['ElButton']
|
||||
ElColorPicker: typeof import('element-plus/es')['ElColorPicker']
|
||||
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
|
||||
ElIcon: typeof import('element-plus/es')['ElIcon']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
SystemMessageCard: typeof import('./components/SystemMessageCard.vue')['default']
|
||||
TableEllipsisText: typeof import('./components/TableEllipsisText.vue')['default']
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
<template>
|
||||
<a-layout class="bottom-nav">
|
||||
<a-layout-content class="nav-content">
|
||||
<button class="nav-item" :class="{ active: currentRoute === 'home' }" type="button" @click="handleNavClick('home')">
|
||||
<a-badge :count="0" :offset="[0, 0]">
|
||||
<div class="nav-icon">
|
||||
<HomeOutlined :style="{ fontSize: '25px' }" />
|
||||
</div>
|
||||
</a-badge>
|
||||
<span class="nav-label">首页</span>
|
||||
</button>
|
||||
|
||||
<button class="nav-item" :class="{ active: currentRoute === 'products' }" type="button" @click="handleNavClick('products')">
|
||||
<a-badge :count="0" :offset="[0, 0]">
|
||||
<div class="nav-icon">
|
||||
<ShoppingOutlined :style="{ fontSize: '25px' }" />
|
||||
</div>
|
||||
</a-badge>
|
||||
<span class="nav-label">作品集</span>
|
||||
</button>
|
||||
|
||||
<button class="nav-item" :class="{ active: currentRoute === 'cart' }" type="button" @click="handleNavClick('cart')">
|
||||
<a-badge :count="cartCount" :offset="[0, 0]">
|
||||
<div class="nav-icon">
|
||||
<ShoppingCartOutlined :style="{ fontSize: '25px' }" />
|
||||
</div>
|
||||
</a-badge>
|
||||
<span class="nav-label">购物车</span>
|
||||
</button>
|
||||
|
||||
<button class="nav-item" :class="{ active: currentRoute === 'profile' }" type="button" @click="handleNavClick('profile')">
|
||||
<a-badge :dot="hasNotification" :offset="[0, 0]">
|
||||
<div class="nav-icon">
|
||||
<UserOutlined :style="{ fontSize: '25px' }" />
|
||||
</div>
|
||||
</a-badge>
|
||||
<span class="nav-label">我的</span>
|
||||
</button>
|
||||
</a-layout-content>
|
||||
</a-layout>
|
||||
</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'
|
||||
|
||||
/**
|
||||
* Purpose: router supports BottomNav.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
/**
|
||||
* Purpose: route supports BottomNav.vue by holding or executing the route page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const route = useRoute()
|
||||
|
||||
// 注入全局购物车数量状态
|
||||
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 会调用它
|
||||
}
|
||||
|
||||
// 页面加载时获取购物车数量
|
||||
onMounted(() => {
|
||||
// 检查当前是否是后台页面,如果是则不加载购物车数据
|
||||
const isAdminPage = window.location.pathname.startsWith('/admin')
|
||||
if (!isAdminPage) {
|
||||
// 调用全局更新方法
|
||||
updateCartCount()
|
||||
}
|
||||
})
|
||||
|
||||
// 提供一个方法让其他组件调用更新购物车数量
|
||||
defineExpose({
|
||||
loadCartCount
|
||||
})
|
||||
|
||||
// 根据当前路由判断激活的导航项
|
||||
/** 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
|
||||
if (path === '/') return 'home'
|
||||
if (path === '/products') return 'products'
|
||||
if (path === '/product') return 'products'
|
||||
if (path === '/cart') return 'cart'
|
||||
if (path === '/profile') return 'profile'
|
||||
if (path === '/wishlist') return 'profile'
|
||||
return 'home'
|
||||
})
|
||||
|
||||
// 处理导航点击事件
|
||||
/** handleNavClick is a local helper used by this page script. */
|
||||
const handleNavClick = (tab: string) => {
|
||||
if (tab === 'home') {
|
||||
router.push('/home')
|
||||
} else if (tab === 'products') {
|
||||
router.push('/products')
|
||||
} else if (tab === 'cart') {
|
||||
router.push('/cart')
|
||||
} else if (tab === 'profile') {
|
||||
router.push('/profile')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.bottom-nav {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: 100%;
|
||||
height: 64px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 96%, transparent);
|
||||
border-top: 1px solid var(--theme-border);
|
||||
box-shadow: 0 -14px 34px color-mix(in srgb, var(--theme-neutral) 10%, transparent);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
backdrop-filter: blur(18px);
|
||||
backface-visibility: hidden;
|
||||
will-change: transform;
|
||||
transform: translateZ(0);
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.nav-content {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
margin: 0 auto;
|
||||
padding: 0 12px calc(env(safe-area-inset-bottom, 0px) / 2);
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 3px;
|
||||
min-width: 58px;
|
||||
min-height: 54px;
|
||||
padding: 6px 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.nav-item:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.nav-item.active {
|
||||
color: var(--theme-primary-action);
|
||||
}
|
||||
|
||||
.nav-item.active .nav-icon {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 34px;
|
||||
margin-bottom: 0;
|
||||
border-radius: 18px 18px 16px 16px;
|
||||
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
color: var(--text-secondary);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.nav-item.active .nav-icon {
|
||||
color: var(--theme-primary-action);
|
||||
background: color-mix(in srgb, var(--theme-primary) 34%, var(--theme-card-bg));
|
||||
}
|
||||
|
||||
.nav-label {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
color: var(--text-secondary);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-item.active .nav-label {
|
||||
color: var(--theme-primary-action);
|
||||
}
|
||||
|
||||
.nav-item :deep(.ant-badge-count) {
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
line-height: 16px;
|
||||
background: var(--theme-primary-action);
|
||||
box-shadow: 0 0 0 1px var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.nav-item :deep(.ant-badge-dot) {
|
||||
background: var(--theme-secondary);
|
||||
box-shadow: 0 0 0 1px var(--theme-card-bg);
|
||||
}
|
||||
|
||||
@media (max-width: 359px) {
|
||||
.bottom-nav {
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
.nav-content {
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
min-width: 0;
|
||||
padding: 8px 4px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.nav-icon :deep(.anticon) {
|
||||
font-size: 22px !important;
|
||||
}
|
||||
|
||||
.nav-label {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.nav-content {
|
||||
max-width: var(--frontend-page-max-width);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
@media (min-width: 768px) {
|
||||
.jayu-cloud-phone-frame > .bottom-nav {
|
||||
right: auto;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
width: var(--frontend-page-max-width);
|
||||
max-width: calc(100vw - 48px);
|
||||
border-bottom-right-radius: 32px;
|
||||
border-bottom-left-radius: 32px;
|
||||
transform: translateX(-50%) translateZ(0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,71 @@
|
||||
<template>
|
||||
<div class="draft-actions">
|
||||
<a-space wrap>
|
||||
<a-button size="small" @click="$emit('save')" :disabled="disabled">
|
||||
暂存
|
||||
</a-button>
|
||||
<a-button v-if="showClear" size="small" type="link" @click="$emit('clear')" :disabled="disabled">
|
||||
清除暂存
|
||||
</a-button>
|
||||
<span v-if="savedAt" class="draft-saved-at">
|
||||
上次暂存:{{ formattedSavedAt }}
|
||||
</span>
|
||||
<span v-else class="draft-saved-at">
|
||||
暂存仅保存在当前浏览器中
|
||||
</span>
|
||||
</a-space>
|
||||
</div>
|
||||
</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'
|
||||
|
||||
/**
|
||||
* Purpose: props supports DraftActions.vue by holding or executing the props page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const props = withDefaults(defineProps<{
|
||||
savedAt?: number | null
|
||||
disabled?: boolean
|
||||
showClear?: boolean
|
||||
}>(), {
|
||||
savedAt: null,
|
||||
disabled: false,
|
||||
showClear: true
|
||||
})
|
||||
|
||||
defineEmits<{
|
||||
(event: 'save'): void
|
||||
(event: 'clear'): void
|
||||
}>()
|
||||
|
||||
/** formattedSavedAt is a reactive state variable used by the template and event handlers. */
|
||||
const formattedSavedAt = computed(() => {
|
||||
if (!props.savedAt) {
|
||||
return ''
|
||||
}
|
||||
const date = new Date(props.savedAt)
|
||||
const year = date.getFullYear()
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const day = `${date.getDate()}`.padStart(2, '0')
|
||||
const hour = `${date.getHours()}`.padStart(2, '0')
|
||||
const minute = `${date.getMinutes()}`.padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hour}:${minute}`
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.draft-actions {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.draft-saved-at {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 24px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,280 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { BellOutlined, ClockCircleOutlined } from '@ant-design/icons-vue'
|
||||
import { renderRichContent } from '@/utils/rich-content'
|
||||
|
||||
/**
|
||||
* Purpose: props supports SystemMessageCard.vue by holding or executing the props page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const props = withDefaults(defineProps<{
|
||||
title?: string
|
||||
content?: string
|
||||
imageUrl?: string
|
||||
imageAlt?: string
|
||||
meta?: string
|
||||
badge?: string
|
||||
auxiliaryBadge?: string
|
||||
surface?: 'modal' | 'preview'
|
||||
footerAlign?: 'between' | 'end'
|
||||
}>(), {
|
||||
title: '系统消息',
|
||||
content: '',
|
||||
imageUrl: '',
|
||||
imageAlt: '消息图片',
|
||||
meta: '',
|
||||
badge: '',
|
||||
auxiliaryBadge: '',
|
||||
surface: 'preview',
|
||||
footerAlign: 'between'
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: hasImage supports SystemMessageCard.vue by holding or executing the has image page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const hasImage = computed(() => Boolean(props.imageUrl))
|
||||
/**
|
||||
* Purpose: displayTitle supports SystemMessageCard.vue by holding or executing the display title page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const displayTitle = computed(() => props.title?.trim() || '系统消息')
|
||||
/**
|
||||
* Purpose: displayContent supports SystemMessageCard.vue by holding or executing the display content page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const displayContent = computed(() => props.content?.trim() || (hasImage.value ? '' : '你收到了一条新的系统消息。'))
|
||||
const displayContentHtml = computed(() => renderRichContent(displayContent.value))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article
|
||||
class="system-message-card"
|
||||
:class="[
|
||||
`system-message-card--${surface}`,
|
||||
`system-message-card--footer-${footerAlign}`,
|
||||
{ 'system-message-card--with-image': hasImage }
|
||||
]"
|
||||
>
|
||||
<div v-if="hasImage" class="system-message-card__media">
|
||||
<img :src="imageUrl" :alt="imageAlt" />
|
||||
</div>
|
||||
|
||||
<div v-else class="system-message-card__icon">
|
||||
<BellOutlined />
|
||||
</div>
|
||||
|
||||
<section class="system-message-card__main">
|
||||
<div v-if="badge || auxiliaryBadge" class="system-message-card__badges">
|
||||
<span v-if="auxiliaryBadge" class="system-message-card__badge system-message-card__badge--soft">{{ auxiliaryBadge }}</span>
|
||||
<span v-if="badge" class="system-message-card__badge">{{ badge }}</span>
|
||||
</div>
|
||||
|
||||
<h2 class="system-message-card__title">{{ displayTitle }}</h2>
|
||||
|
||||
<div v-if="meta" class="system-message-card__meta">
|
||||
<ClockCircleOutlined />
|
||||
<span>{{ meta }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="displayContentHtml" class="system-message-card__content" v-html="displayContentHtml"></div>
|
||||
</section>
|
||||
|
||||
<footer v-if="$slots.footer" class="system-message-card__footer">
|
||||
<slot name="footer" />
|
||||
</footer>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.system-message-card {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--theme-border);
|
||||
border-radius: 8px;
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.system-message-card--preview {
|
||||
box-shadow: 0 20px 54px rgba(77, 50, 62, 0.16);
|
||||
}
|
||||
|
||||
.system-message-card--modal {
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.system-message-card__media {
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
padding: 12px 12px 0;
|
||||
background: var(--theme-gradient-soft);
|
||||
}
|
||||
|
||||
.system-message-card__media img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.system-message-card__icon {
|
||||
display: grid;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin: 28px auto 0;
|
||||
place-items: center;
|
||||
border-radius: 8px;
|
||||
color: #ffffff;
|
||||
font-size: 20px;
|
||||
background: var(--theme-gradient);
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
.system-message-card__main {
|
||||
padding: 20px 30px 28px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.system-message-card--with-image .system-message-card__main {
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
.system-message-card__badges {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.system-message-card__badge {
|
||||
display: inline-flex;
|
||||
min-height: 24px;
|
||||
align-items: center;
|
||||
padding: 0 10px;
|
||||
border-radius: 8px;
|
||||
color: #ffffff;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
background: var(--theme-gradient);
|
||||
}
|
||||
|
||||
.system-message-card__badge--soft {
|
||||
color: var(--theme-primary);
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.system-message-card__title {
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
font-size: 19px;
|
||||
font-weight: 800;
|
||||
line-height: 1.35;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.system-message-card__meta {
|
||||
display: inline-flex;
|
||||
max-width: 100%;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 10px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.system-message-card__content {
|
||||
margin: 20px 0 0;
|
||||
color: var(--text-primary);
|
||||
font-size: 15px;
|
||||
line-height: 1.75;
|
||||
text-align: left;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(*) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(p),
|
||||
.system-message-card__content :deep(ul),
|
||||
.system-message-card__content :deep(ol),
|
||||
.system-message-card__content :deep(blockquote),
|
||||
.system-message-card__content :deep(pre),
|
||||
.system-message-card__content :deep(table) {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(p:last-child),
|
||||
.system-message-card__content :deep(ul:last-child),
|
||||
.system-message-card__content :deep(ol:last-child),
|
||||
.system-message-card__content :deep(blockquote:last-child),
|
||||
.system-message-card__content :deep(pre:last-child),
|
||||
.system-message-card__content :deep(table:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(ul),
|
||||
.system-message-card__content :deep(ol) {
|
||||
padding-left: 1.25em;
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(a) {
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(img) {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.system-message-card__content :deep(pre) {
|
||||
overflow-x: auto;
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.system-message-card__footer {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 18px 30px;
|
||||
border-top: 1px solid var(--theme-border);
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.system-message-card--footer-end .system-message-card__footer {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.system-message-card {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.system-message-card__main,
|
||||
.system-message-card__footer {
|
||||
padding-left: 22px;
|
||||
padding-right: 22px;
|
||||
}
|
||||
|
||||
.system-message-card__title {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.system-message-card__footer {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,76 @@
|
||||
<template>
|
||||
<span v-if="!displayText" class="empty-text">{{ emptyText }}</span>
|
||||
<a-tooltip v-else :title="displayText" placement="topLeft">
|
||||
<div class="ellipsis-text" :class="lineClass">
|
||||
{{ displayText }}
|
||||
</div>
|
||||
</a-tooltip>
|
||||
</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'
|
||||
|
||||
/**
|
||||
* Purpose: props supports TableEllipsisText.vue by holding or executing the props page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const props = withDefaults(defineProps<{
|
||||
text?: string | number | null
|
||||
lines?: 1 | 2 | 3
|
||||
emptyText?: string
|
||||
}>(), {
|
||||
lines: 1,
|
||||
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 ''
|
||||
}
|
||||
const value = String(props.text).trim()
|
||||
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}` : ''
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.ellipsis-text {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
line-height: 1.5;
|
||||
vertical-align: bottom;
|
||||
}
|
||||
|
||||
.lines-2,
|
||||
.lines-3 {
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
white-space: normal;
|
||||
word-break: normal;
|
||||
overflow-wrap: normal;
|
||||
}
|
||||
|
||||
.lines-2 {
|
||||
-webkit-line-clamp: 2;
|
||||
}
|
||||
|
||||
.lines-3 {
|
||||
-webkit-line-clamp: 3;
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,120 @@
|
||||
<script setup lang="ts">
|
||||
import { shallowRef } from 'vue'
|
||||
import { DownOutlined, FilterOutlined } from '@ant-design/icons-vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
activeCount?: number
|
||||
label?: string
|
||||
}>(), {
|
||||
activeCount: 0,
|
||||
label: '筛选'
|
||||
})
|
||||
|
||||
const filtersOpen = shallowRef(false)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="admin-filter-panel">
|
||||
<div class="mobile-filter-toggle">
|
||||
<button
|
||||
class="mobile-filter-toggle__button"
|
||||
type="button"
|
||||
:aria-expanded="filtersOpen"
|
||||
@click="filtersOpen = !filtersOpen"
|
||||
>
|
||||
<FilterOutlined />
|
||||
<span>{{ props.activeCount ? `${props.label} ${props.activeCount}` : props.label }}</span>
|
||||
<DownOutlined class="mobile-filter-toggle__chevron" :class="{ 'is-open': filtersOpen }" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="admin-filter-bar admin-filter-bar--mobile"
|
||||
:class="{ 'admin-filter-bar--collapsed': !filtersOpen }"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.admin-filter-panel {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.admin-filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mobile-filter-toggle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.admin-filter-panel {
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.mobile-filter-toggle {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.mobile-filter-toggle__button {
|
||||
width: 100%;
|
||||
min-height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--admin-mobile-border);
|
||||
border-radius: 12px;
|
||||
background: var(--theme-card-bg);
|
||||
color: var(--admin-mobile-ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.mobile-filter-toggle__chevron {
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.mobile-filter-toggle__chevron.is-open {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.admin-filter-bar--mobile {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
max-height: 560px;
|
||||
overflow: hidden;
|
||||
opacity: 1;
|
||||
transition: max-height 0.22s ease, opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.admin-filter-bar--mobile.admin-filter-bar--collapsed {
|
||||
max-height: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.admin-filter-bar--mobile :deep(.ant-input),
|
||||
.admin-filter-bar--mobile :deep(.ant-input-affix-wrapper),
|
||||
.admin-filter-bar--mobile :deep(.ant-input-number),
|
||||
.admin-filter-bar--mobile :deep(.ant-picker),
|
||||
.admin-filter-bar--mobile :deep(.ant-select),
|
||||
.admin-filter-bar--mobile :deep(.ant-btn) {
|
||||
width: 100% !important;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-filter-bar--mobile :deep(.ant-picker) {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,38 @@
|
||||
<template>
|
||||
<div class="admin-mobile-card-list">
|
||||
<template v-if="items.length">
|
||||
<slot
|
||||
v-for="(item, index) in items"
|
||||
:key="resolveItemKey(item, index)"
|
||||
name="item"
|
||||
:item="item"
|
||||
:index="index"
|
||||
/>
|
||||
</template>
|
||||
<a-empty v-else :description="emptyDescription" />
|
||||
</div>
|
||||
</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
|
||||
itemKey?: string
|
||||
}>(), {
|
||||
items: () => [],
|
||||
emptyDescription: '暂无数据',
|
||||
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]
|
||||
}
|
||||
return index
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,32 @@
|
||||
<template>
|
||||
<button
|
||||
v-if="visible"
|
||||
class="admin-mobile-fab"
|
||||
type="button"
|
||||
:aria-label="label"
|
||||
:title="label"
|
||||
@click="$emit('click')"
|
||||
>
|
||||
<PlusOutlined />
|
||||
</button>
|
||||
</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<{
|
||||
visible?: boolean
|
||||
label?: string
|
||||
}>(), {
|
||||
visible: false,
|
||||
label: '新增'
|
||||
})
|
||||
|
||||
defineEmits<{
|
||||
(event: 'click'): void
|
||||
}>()
|
||||
</script>
|
||||
@@ -0,0 +1,130 @@
|
||||
<template>
|
||||
<a-modal
|
||||
v-bind="$attrs"
|
||||
:open="open"
|
||||
:title="title"
|
||||
:width="mergedWidth"
|
||||
:mask-closable="false"
|
||||
:centered="!isMobile"
|
||||
:wrap-class-name="mergedWrapClassName"
|
||||
:style="mergedStyle"
|
||||
:body-style="mergedBodyStyle"
|
||||
@update:open="handleOpenChange"
|
||||
@cancel="handleCancel"
|
||||
@ok="handleOk"
|
||||
>
|
||||
<slot />
|
||||
<template v-if="$slots.footer" #footer>
|
||||
<slot name="footer" />
|
||||
</template>
|
||||
</a-modal>
|
||||
</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, useAttrs } from 'vue'
|
||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||
import { CONFIRM_ENTER_DISABLED_CLASS } from '@/composables/useConfirmEnter'
|
||||
|
||||
/**
|
||||
* Purpose: modalInstanceSeed supports AdminResponsiveModal.vue by holding or executing the modal instance seed page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let modalInstanceSeed = 0
|
||||
|
||||
/**
|
||||
* Purpose: props supports AdminResponsiveModal.vue by holding or executing the props page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const props = withDefaults(defineProps<{
|
||||
open: boolean
|
||||
title?: string
|
||||
desktopWidth?: string | number
|
||||
mobileBodyPadding?: string
|
||||
confirmOnEnter?: boolean
|
||||
}>(), {
|
||||
title: '',
|
||||
desktopWidth: 720,
|
||||
mobileBodyPadding: '16px 16px 104px',
|
||||
confirmOnEnter: true
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: emit supports AdminResponsiveModal.vue by holding or executing the emit page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:open', value: boolean): void
|
||||
(event: 'cancel', value?: unknown): void
|
||||
(event: 'ok', value?: unknown): void
|
||||
}>()
|
||||
|
||||
const { isMobile } = useAdminViewport()
|
||||
/**
|
||||
* Purpose: attrs supports AdminResponsiveModal.vue by holding or executing the attrs page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const attrs = useAttrs()
|
||||
/**
|
||||
* Purpose: modalInstanceClass supports AdminResponsiveModal.vue by holding or executing the modal instance class page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const modalInstanceClass = `admin-responsive-modal-${modalInstanceSeed++}`
|
||||
|
||||
/** mergedWidth is a reactive state variable used by the template and event handlers. */
|
||||
const mergedWidth = computed(() => (isMobile.value ? '100dvw' : props.desktopWidth))
|
||||
/** mergedStyle is a reactive state variable used by the template and event handlers. */
|
||||
const mergedStyle = computed(() => (
|
||||
isMobile.value
|
||||
? {
|
||||
top: '0px',
|
||||
maxWidth: '100dvw',
|
||||
paddingBottom: '0px'
|
||||
}
|
||||
: undefined
|
||||
))
|
||||
/**
|
||||
* Purpose: mergedWrapClassName supports AdminResponsiveModal.vue by holding or executing the merged wrap class name page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const mergedWrapClassName = computed(() => (
|
||||
[
|
||||
attrs.wrapClassName || attrs['wrap-class-name'],
|
||||
isMobile.value ? 'admin-mobile-modal' : '',
|
||||
props.confirmOnEnter ? '' : CONFIRM_ENTER_DISABLED_CLASS,
|
||||
modalInstanceClass
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
))
|
||||
/** mergedBodyStyle is a reactive state variable used by the template and event handlers. */
|
||||
const mergedBodyStyle = computed(() => (
|
||||
isMobile.value
|
||||
? ({
|
||||
maxHeight: 'calc(100vh - 124px)',
|
||||
overflowY: 'auto',
|
||||
padding: props.mobileBodyPadding
|
||||
} as CSSProperties)
|
||||
: 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)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,80 @@
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
|
||||
/**
|
||||
* Purpose: ADMIN_MOBILE_BREAKPOINT supports useAdminViewport.ts by holding or executing the admin mobile breakpoint page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ADMIN_MOBILE_BREAKPOINT = 960
|
||||
|
||||
/**
|
||||
* Purpose: viewportWidth supports useAdminViewport.ts by holding or executing the viewport width page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const viewportWidth = ref(
|
||||
typeof window !== 'undefined' ? window.innerWidth : ADMIN_MOBILE_BREAKPOINT + 1
|
||||
)
|
||||
|
||||
/**
|
||||
* Purpose: listenerCount supports useAdminViewport.ts by holding or executing the listener count page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let listenerCount = 0
|
||||
|
||||
/**
|
||||
* Purpose: updateViewportWidth supports useAdminViewport.ts by holding or executing the update viewport width page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const updateViewportWidth = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
viewportWidth.value = window.innerWidth
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: bindViewportListener supports useAdminViewport.ts by holding or executing the bind viewport listener page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const bindViewportListener = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
if (listenerCount === 0) {
|
||||
window.addEventListener('resize', updateViewportWidth, { passive: true })
|
||||
}
|
||||
listenerCount += 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: unbindViewportListener supports useAdminViewport.ts by holding or executing the unbind viewport listener page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const unbindViewportListener = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
listenerCount = Math.max(0, listenerCount - 1)
|
||||
if (listenerCount === 0) {
|
||||
window.removeEventListener('resize', updateViewportWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: useAdminViewport supports useAdminViewport.ts by holding or executing the use admin viewport page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const useAdminViewport = () => {
|
||||
onMounted(() => {
|
||||
updateViewportWidth()
|
||||
bindViewportListener()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
unbindViewportListener()
|
||||
})
|
||||
|
||||
return {
|
||||
viewportWidth: computed(() => viewportWidth.value),
|
||||
isMobile: computed(() => viewportWidth.value <= ADMIN_MOBILE_BREAKPOINT)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createApp } from 'vue'
|
||||
import { useGlobalConfirmEnter } from './useConfirmEnter'
|
||||
|
||||
/**
|
||||
* Purpose: visibleRects supports useConfirmEnter.test.ts by holding or executing the visible rects page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const visibleRects = [{
|
||||
bottom: 100,
|
||||
height: 100,
|
||||
left: 0,
|
||||
right: 100,
|
||||
top: 0,
|
||||
width: 100,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({})
|
||||
}] as DOMRect[]
|
||||
|
||||
/**
|
||||
* Purpose: makeVisible supports useConfirmEnter.test.ts by holding or executing the make visible page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const makeVisible = (element: HTMLElement) => {
|
||||
vi.spyOn(element, 'getClientRects').mockReturnValue(visibleRects as unknown as DOMRectList)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: setDesktopViewport supports useConfirmEnter.test.ts by holding or executing the set desktop viewport page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const setDesktopViewport = () => {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: 1280
|
||||
})
|
||||
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
|
||||
matches: query === '(pointer: coarse)' ? false : false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
dispatchEvent: vi.fn()
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: setMobileViewport supports useConfirmEnter.test.ts by holding or executing the set mobile viewport page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const setMobileViewport = () => {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: 640
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: setCoarsePointer supports useConfirmEnter.test.ts by holding or executing the set coarse pointer page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const setCoarsePointer = () => {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: 1280
|
||||
})
|
||||
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
|
||||
matches: query === '(pointer: coarse)',
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
dispatchEvent: vi.fn()
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: mountGlobalConfirmEnter supports useConfirmEnter.test.ts by holding or executing the mount global confirm enter page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const mountGlobalConfirmEnter = () => {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
|
||||
const app = createApp({
|
||||
setup() {
|
||||
useGlobalConfirmEnter()
|
||||
return () => null
|
||||
}
|
||||
})
|
||||
|
||||
app.mount(host)
|
||||
|
||||
return () => {
|
||||
app.unmount()
|
||||
host.remove()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: createModal supports useConfirmEnter.test.ts by holding or executing the create modal page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const createModal = ({
|
||||
zIndex = 1000,
|
||||
buttonClass = '',
|
||||
disabled = false,
|
||||
ariaDisabled = false,
|
||||
footerClass = 'ant-modal-footer'
|
||||
}: {
|
||||
zIndex?: number
|
||||
buttonClass?: string
|
||||
disabled?: boolean
|
||||
ariaDisabled?: boolean
|
||||
footerClass?: 'ant-modal-footer' | 'ant-modal-confirm-btns'
|
||||
} = {}) => {
|
||||
const wrap = document.createElement('div')
|
||||
wrap.className = 'ant-modal-wrap'
|
||||
wrap.style.zIndex = String(zIndex)
|
||||
|
||||
const footer = document.createElement('div')
|
||||
footer.className = footerClass
|
||||
|
||||
const button = document.createElement('button')
|
||||
button.type = 'button'
|
||||
button.className = `ant-btn ant-btn-primary ${buttonClass}`.trim()
|
||||
button.disabled = disabled
|
||||
if (ariaDisabled) {
|
||||
button.setAttribute('aria-disabled', 'true')
|
||||
}
|
||||
|
||||
const onClick = vi.fn()
|
||||
const click = vi.spyOn(button, 'click')
|
||||
button.addEventListener('click', onClick)
|
||||
|
||||
footer.appendChild(button)
|
||||
wrap.appendChild(footer)
|
||||
document.body.appendChild(wrap)
|
||||
makeVisible(wrap)
|
||||
makeVisible(button)
|
||||
|
||||
return { wrap, button, click, onClick }
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: createKeyboardEvent supports useConfirmEnter.test.ts by holding or executing the create keyboard event page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const createKeyboardEvent = () => new KeyboardEvent('keydown', {
|
||||
key: 'Enter',
|
||||
bubbles: true,
|
||||
cancelable: true
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: pressEnter supports useConfirmEnter.test.ts by holding or executing the press enter page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const pressEnter = (target: EventTarget = document) => {
|
||||
const event = createKeyboardEvent()
|
||||
target.dispatchEvent(event)
|
||||
return event
|
||||
}
|
||||
|
||||
describe('useGlobalConfirmEnter', () => {
|
||||
let unmount: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
setDesktopViewport()
|
||||
unmount = mountGlobalConfirmEnter()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
unmount?.()
|
||||
document.body.innerHTML = ''
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('clicks the visible top modal primary ok button when PC users press Enter', () => {
|
||||
const { onClick } = createModal()
|
||||
|
||||
const event = pressEnter()
|
||||
|
||||
expect(onClick).toHaveBeenCalledTimes(1)
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
})
|
||||
|
||||
it('does not click the ok button when Enter starts inside textarea or contenteditable elements', () => {
|
||||
const { onClick } = createModal()
|
||||
|
||||
const textarea = document.createElement('textarea')
|
||||
document.body.appendChild(textarea)
|
||||
pressEnter(textarea)
|
||||
|
||||
const editable = document.createElement('div')
|
||||
editable.setAttribute('contenteditable', 'true')
|
||||
document.body.appendChild(editable)
|
||||
pressEnter(editable)
|
||||
|
||||
expect(onClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
'ant-select-dropdown',
|
||||
'ant-picker-dropdown',
|
||||
'ant-dropdown',
|
||||
'ant-popover'
|
||||
])('does not click the ok button while %s is open', (dropdownClass) => {
|
||||
const { onClick } = createModal()
|
||||
const popup = document.createElement('div')
|
||||
popup.className = dropdownClass
|
||||
document.body.appendChild(popup)
|
||||
|
||||
pressEnter()
|
||||
|
||||
expect(onClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not click disabled or loading ok buttons', () => {
|
||||
const disabledModal = createModal({ disabled: true })
|
||||
pressEnter()
|
||||
expect(disabledModal.click).not.toHaveBeenCalled()
|
||||
expect(disabledModal.onClick).not.toHaveBeenCalled()
|
||||
disabledModal.wrap.remove()
|
||||
|
||||
const ariaDisabledModal = createModal({ ariaDisabled: true })
|
||||
pressEnter()
|
||||
expect(ariaDisabledModal.click).not.toHaveBeenCalled()
|
||||
expect(ariaDisabledModal.onClick).not.toHaveBeenCalled()
|
||||
ariaDisabledModal.wrap.remove()
|
||||
|
||||
const loadingModal = createModal({ buttonClass: 'ant-btn-loading' })
|
||||
pressEnter()
|
||||
expect(loadingModal.click).not.toHaveBeenCalled()
|
||||
expect(loadingModal.onClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not click the ok button on mobile width or coarse pointer devices', () => {
|
||||
const mobileModal = createModal()
|
||||
setMobileViewport()
|
||||
pressEnter()
|
||||
expect(mobileModal.onClick).not.toHaveBeenCalled()
|
||||
mobileModal.wrap.remove()
|
||||
|
||||
const coarsePointerModal = createModal()
|
||||
setCoarsePointer()
|
||||
pressEnter()
|
||||
expect(coarsePointerModal.onClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clicks only the z-index and DOM-top modal when multiple modals are visible', () => {
|
||||
const firstModal = createModal({ zIndex: 1000 })
|
||||
const secondModal = createModal({ zIndex: 1000 })
|
||||
const topZIndexModal = createModal({ zIndex: 1200 })
|
||||
|
||||
pressEnter()
|
||||
|
||||
expect(firstModal.onClick).not.toHaveBeenCalled()
|
||||
expect(secondModal.onClick).not.toHaveBeenCalled()
|
||||
expect(topZIndexModal.onClick).toHaveBeenCalledTimes(1)
|
||||
|
||||
topZIndexModal.wrap.remove()
|
||||
pressEnter()
|
||||
|
||||
expect(firstModal.onClick).not.toHaveBeenCalled()
|
||||
expect(secondModal.onClick).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* Purpose: ComputedRef supports useConfirmEnter.ts by holding or executing the computed ref page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, type ComputedRef } from 'vue'
|
||||
|
||||
/**
|
||||
* Purpose: UseConfirmEnterOptions supports useConfirmEnter.ts by holding or executing the use confirm enter options page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
interface UseConfirmEnterOptions {
|
||||
enabled: ComputedRef<boolean>
|
||||
onConfirm: (event: KeyboardEvent) => void
|
||||
isConfirmDisabled?: () => boolean
|
||||
isTopLayer?: () => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: CONFIRM_ENTER_DISABLED_CLASS supports useConfirmEnter.ts by holding or executing the confirm enter disabled class page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const CONFIRM_ENTER_DISABLED_CLASS = 'confirm-enter-disabled'
|
||||
/**
|
||||
* Purpose: DESKTOP_MIN_WIDTH supports useConfirmEnter.ts by holding or executing the desktop min width page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DESKTOP_MIN_WIDTH = 960
|
||||
|
||||
/**
|
||||
* Purpose: isEditableTarget supports useConfirmEnter.ts by holding or executing the is editable target page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isEditableTarget = (target: EventTarget | null) => {
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (target.isContentEditable) {
|
||||
return true
|
||||
}
|
||||
|
||||
return target.tagName.toLowerCase() === 'textarea' || Boolean(target.closest('[contenteditable="true"]'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hasOpenPickerOrDropdown supports useConfirmEnter.ts by holding or executing the has open picker or dropdown page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const hasOpenPickerOrDropdown = () => {
|
||||
return Boolean(document.querySelector([
|
||||
'.ant-select-dropdown:not(.ant-select-dropdown-hidden)',
|
||||
'.ant-picker-dropdown:not(.ant-picker-dropdown-hidden)',
|
||||
'.ant-cascader-dropdown:not(.ant-cascader-dropdown-hidden)',
|
||||
'.ant-dropdown:not(.ant-dropdown-hidden)',
|
||||
'.ant-popover:not(.ant-popover-hidden)'
|
||||
].join(',')))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isDesktopViewport supports useConfirmEnter.ts by holding or executing the is desktop viewport page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isDesktopViewport = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false
|
||||
}
|
||||
|
||||
const coarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false
|
||||
return window.innerWidth > DESKTOP_MIN_WIDTH && !coarsePointer
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isVisibleElement supports useConfirmEnter.ts by holding or executing the is visible element page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isVisibleElement = (element: Element) => {
|
||||
if (!(element instanceof HTMLElement)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const style = window.getComputedStyle(element)
|
||||
return style.display !== 'none'
|
||||
&& style.visibility !== 'hidden'
|
||||
&& style.opacity !== '0'
|
||||
&& element.getClientRects().length > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isDisabledButton supports useConfirmEnter.ts by holding or executing the is disabled button page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isDisabledButton = (button: HTMLButtonElement) => {
|
||||
return button.disabled
|
||||
|| button.getAttribute('aria-disabled') === 'true'
|
||||
|| button.classList.contains('ant-btn-loading')
|
||||
|| button.classList.contains('ant-btn-disabled')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getTopModalWrap supports useConfirmEnter.ts by holding or executing the get top modal wrap page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getTopModalWrap = () => {
|
||||
const modals = Array.from(document.querySelectorAll<HTMLElement>('.ant-modal-wrap'))
|
||||
.filter(isVisibleElement)
|
||||
|
||||
if (!modals.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const sortedModals = modals
|
||||
.map((modal, index) => {
|
||||
const zIndex = Number.parseInt(window.getComputedStyle(modal).zIndex || '0', 10)
|
||||
return {
|
||||
modal,
|
||||
index,
|
||||
zIndex: Number.isNaN(zIndex) ? 0 : zIndex
|
||||
}
|
||||
})
|
||||
.sort((left, right) => left.zIndex - right.zIndex || left.index - right.index)
|
||||
|
||||
return sortedModals[sortedModals.length - 1]?.modal ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getTopModalConfirmButton supports useConfirmEnter.ts by holding or executing the get top modal confirm button page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getTopModalConfirmButton = () => {
|
||||
const topModal = getTopModalWrap()
|
||||
if (!topModal || topModal.classList.contains(CONFIRM_ENTER_DISABLED_CLASS)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const button = topModal.querySelector<HTMLButtonElement>([
|
||||
'.ant-modal-confirm-btns .ant-btn-primary',
|
||||
'.ant-modal-footer .ant-btn-primary'
|
||||
].join(','))
|
||||
|
||||
if (!button || !isVisibleElement(button) || isDisabledButton(button)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return button
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: useConfirmEnter supports useConfirmEnter.ts by holding or executing the use confirm enter page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const useConfirmEnter = ({
|
||||
enabled,
|
||||
onConfirm,
|
||||
isConfirmDisabled,
|
||||
isTopLayer
|
||||
}: UseConfirmEnterOptions) => {
|
||||
const canConfirm = computed(() => (
|
||||
enabled.value
|
||||
&& !(isConfirmDisabled?.() ?? false)
|
||||
&& (isTopLayer?.() ?? true)
|
||||
))
|
||||
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key !== 'Enter'
|
||||
|| event.defaultPrevented
|
||||
|| event.shiftKey
|
||||
|| event.ctrlKey
|
||||
|| event.altKey
|
||||
|| event.metaKey
|
||||
|| event.isComposing
|
||||
|| !canConfirm.value
|
||||
|| isEditableTarget(event.target)
|
||||
|| hasOpenPickerOrDropdown()
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
onConfirm(event)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('keydown', handleKeydown)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', handleKeydown)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: useGlobalConfirmEnter supports useConfirmEnter.ts by holding or executing the use global confirm enter page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const useGlobalConfirmEnter = () => {
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key !== 'Enter'
|
||||
|| event.defaultPrevented
|
||||
|| event.shiftKey
|
||||
|| event.ctrlKey
|
||||
|| event.altKey
|
||||
|| event.metaKey
|
||||
|| event.isComposing
|
||||
|| (event as KeyboardEvent & { keyCode?: number }).keyCode === 229
|
||||
|| !isDesktopViewport()
|
||||
|| isEditableTarget(event.target)
|
||||
|| hasOpenPickerOrDropdown()
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const confirmButton = getTopModalConfirmButton()
|
||||
if (!confirmButton) {
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
confirmButton.click()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('keydown', handleKeydown)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', handleKeydown)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@/api/file', () => ({
|
||||
fileApi: {
|
||||
getSignedUrl: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/api/shop', () => ({
|
||||
shopApi: {
|
||||
getShopById: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
import { shopApi } from '@/api/shop'
|
||||
import { DEFAULT_SHOP_THEME } from '@/utils/shop-theme'
|
||||
import { useShopTheme } from './useShopTheme'
|
||||
|
||||
describe('useShopTheme', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
vi.clearAllMocks()
|
||||
document.documentElement.removeAttribute('style')
|
||||
})
|
||||
|
||||
it('uses the first preset as the default visible theme', async () => {
|
||||
const { resetShopTheme } = useShopTheme()
|
||||
|
||||
resetShopTheme()
|
||||
|
||||
expect(DEFAULT_SHOP_THEME.primaryColor).toBe('#E8B4B8')
|
||||
expect(DEFAULT_SHOP_THEME.secondaryColor).toBe('#C5A059')
|
||||
expect(DEFAULT_SHOP_THEME.accentColor).toBe('#4A443F')
|
||||
expect(DEFAULT_SHOP_THEME.pageBgColor).toBe('#FDFBF9')
|
||||
expect(DEFAULT_SHOP_THEME.cardBgColor).toBe('#FFFFFF')
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8')
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#C5A059')
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-neutral')).toBe('#4A443F')
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-tertiary')).toBe('#FDFBF9')
|
||||
})
|
||||
|
||||
it('refreshes the admin theme from the cached admin shop context', async () => {
|
||||
localStorage.setItem('adminAccessToken', 'admin-token')
|
||||
localStorage.setItem('adminUserInfo', JSON.stringify({ shopId: 42 }))
|
||||
vi.mocked(shopApi.getShopById).mockResolvedValue({
|
||||
themePrimaryColor: '#123456',
|
||||
themeSecondaryColor: '#ABCDEF',
|
||||
themeAccentColor: '#345678',
|
||||
themePageBgColor: '#F7FAFC',
|
||||
themeCardBgColor: '#FFFFFF'
|
||||
} as never)
|
||||
|
||||
const { refreshShopTheme } = useShopTheme()
|
||||
|
||||
await refreshShopTheme({ mode: 'admin' })
|
||||
|
||||
expect(shopApi.getShopById).toHaveBeenCalledWith('42')
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#123456')
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#ABCDEF')
|
||||
})
|
||||
|
||||
it('keeps the default theme for login pages without a shop context', async () => {
|
||||
const { refreshShopTheme } = useShopTheme()
|
||||
|
||||
await refreshShopTheme({ mode: 'admin' })
|
||||
|
||||
expect(shopApi.getShopById).not.toHaveBeenCalled()
|
||||
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
import { readonly, shallowRef } from 'vue'
|
||||
import { fileApi } from '@/api/file'
|
||||
/**
|
||||
* Purpose: ShopVO supports useShopTheme.ts by holding or executing the shop vo page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { shopApi, type ShopVO } from '@/api/shop'
|
||||
import {
|
||||
applyShopTheme,
|
||||
DEFAULT_SHOP_THEME,
|
||||
resolveShopTheme,
|
||||
SHOP_THEME_CHANGED_EVENT,
|
||||
type ResolvedShopTheme
|
||||
} from '@/utils/shop-theme'
|
||||
|
||||
type ShopThemeMode = 'auto' | 'admin' | 'customer'
|
||||
|
||||
export interface RefreshShopThemeOptions {
|
||||
mode?: ShopThemeMode
|
||||
shopId?: string | number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: currentTheme supports useShopTheme.ts by holding or executing the current theme page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentTheme = shallowRef<ResolvedShopTheme>(DEFAULT_SHOP_THEME)
|
||||
let cleanupThemeSync: (() => void) | undefined
|
||||
/**
|
||||
* Purpose: refreshSequence supports useShopTheme.ts by holding or executing the refresh sequence page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let refreshSequence = 0
|
||||
|
||||
applyShopTheme(DEFAULT_SHOP_THEME)
|
||||
|
||||
/**
|
||||
* Purpose: useShopTheme supports useShopTheme.ts by holding or executing the use shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function useShopTheme() {
|
||||
return {
|
||||
currentTheme: readonly(currentTheme),
|
||||
refreshShopTheme,
|
||||
resetShopTheme,
|
||||
setupShopThemeSync
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: refreshShopTheme supports useShopTheme.ts by holding or executing the refresh shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function refreshShopTheme(options: RefreshShopThemeOptions = {}) {
|
||||
const mode = resolveThemeMode(options.mode)
|
||||
const token = readToken(mode)
|
||||
const userInfo = readStoredUserInfo(mode)
|
||||
const shopId = options.shopId === undefined ? userInfo?.shopId : options.shopId
|
||||
|
||||
if (!token || !shopId) {
|
||||
resetShopTheme()
|
||||
return
|
||||
}
|
||||
|
||||
const sequence = ++refreshSequence
|
||||
try {
|
||||
const shop = await shopApi.getShopById(String(shopId))
|
||||
if (sequence !== refreshSequence) {
|
||||
return
|
||||
}
|
||||
await applyThemeFromShop(shop)
|
||||
} catch {
|
||||
if (sequence === refreshSequence) {
|
||||
resetShopTheme()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resetShopTheme supports useShopTheme.ts by holding or executing the reset shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function resetShopTheme() {
|
||||
refreshSequence += 1
|
||||
currentTheme.value = DEFAULT_SHOP_THEME
|
||||
applyShopTheme(DEFAULT_SHOP_THEME)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: setupShopThemeSync supports useShopTheme.ts by holding or executing the setup shop theme sync page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function setupShopThemeSync() {
|
||||
if (cleanupThemeSync || typeof window === 'undefined') {
|
||||
return cleanupThemeSync || (() => {})
|
||||
}
|
||||
|
||||
const handleThemeEvent = () => {
|
||||
void refreshShopTheme()
|
||||
}
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if ([
|
||||
'accessToken',
|
||||
'userInfo',
|
||||
'refreshToken',
|
||||
'adminAccessToken',
|
||||
'adminRefreshToken',
|
||||
'adminUserInfo'
|
||||
].includes(event.key || '')) {
|
||||
void refreshShopTheme()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent)
|
||||
window.addEventListener('storage', handleStorage)
|
||||
window.addEventListener('focus', handleThemeEvent)
|
||||
|
||||
cleanupThemeSync = () => {
|
||||
window.removeEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent)
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
window.removeEventListener('focus', handleThemeEvent)
|
||||
cleanupThemeSync = undefined
|
||||
}
|
||||
return cleanupThemeSync
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: applyThemeFromShop supports useShopTheme.ts by holding or executing the apply theme from shop page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function applyThemeFromShop(shop: ShopVO) {
|
||||
const theme = resolveShopTheme(shop)
|
||||
currentTheme.value = theme
|
||||
const backgroundImageUrl = await resolveBackgroundImageUrl(theme.backgroundImageFileId)
|
||||
applyShopTheme(theme, backgroundImageUrl)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveBackgroundImageUrl supports useShopTheme.ts by holding or executing the resolve background image url page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function resolveBackgroundImageUrl(fileId?: string) {
|
||||
if (!fileId) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return await fileApi.getSignedUrl(fileId, 120) as unknown as string
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: readToken supports useShopTheme.ts by holding or executing the read token page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function resolveThemeMode(mode: ShopThemeMode = 'auto'): Exclude<ShopThemeMode, 'auto'> {
|
||||
if (mode !== 'auto') {
|
||||
return mode
|
||||
}
|
||||
if (typeof window !== 'undefined' && window.location.pathname.startsWith('/admin')) {
|
||||
return 'admin'
|
||||
}
|
||||
return 'customer'
|
||||
}
|
||||
|
||||
function readToken(mode: Exclude<ShopThemeMode, 'auto'>) {
|
||||
if (typeof window === 'undefined') {
|
||||
return ''
|
||||
}
|
||||
if (mode === 'admin') {
|
||||
return localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken') || ''
|
||||
}
|
||||
return localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: readStoredUserInfo supports useShopTheme.ts by holding or executing the read stored user info page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function readStoredUserInfo(mode: Exclude<ShopThemeMode, 'auto'>): { shopId?: string | number } | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null
|
||||
}
|
||||
const raw = localStorage.getItem(mode === 'admin' ? 'adminUserInfo' : 'userInfo')
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw) as { shopId?: string | number }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { adminNavigationItems, adminPermissionRouteMap, findAdminNavigationItemByPath, ADMIN_DASHBOARD_PATH } from './admin-navigation'
|
||||
|
||||
describe('admin-navigation', () => {
|
||||
it('keeps dashboard landing and permission routes aligned', () => {
|
||||
expect(ADMIN_DASHBOARD_PATH).toBe('/admin/dashboard')
|
||||
expect(findAdminNavigationItemByPath('/admin/products')?.label).toBe('作品管理')
|
||||
expect(adminPermissionRouteMap.some(item => item.code === 'shop:view' && item.path === '/admin/shops')).toBe(true)
|
||||
expect(adminNavigationItems[0]?.path).toBe('/admin')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
export type AdminNavIconKey =
|
||||
| 'home'
|
||||
| 'dashboard'
|
||||
| 'user'
|
||||
| 'shop'
|
||||
| 'gift'
|
||||
| 'message'
|
||||
| 'security'
|
||||
| 'tag'
|
||||
| 'shopping'
|
||||
| 'calendar'
|
||||
| 'tool'
|
||||
| 'team'
|
||||
|
||||
export interface AdminNavigationItem {
|
||||
path: string
|
||||
iconKey: AdminNavIconKey
|
||||
label: string
|
||||
permissionCode: string
|
||||
}
|
||||
|
||||
export const ADMIN_HOME_PATH = '/admin'
|
||||
export const ADMIN_DASHBOARD_PATH = '/admin/dashboard'
|
||||
|
||||
export const adminNavigationItems: AdminNavigationItem[] = [
|
||||
{ path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' },
|
||||
{ path: ADMIN_DASHBOARD_PATH, iconKey: 'dashboard', label: '仪表盘', permissionCode: 'dashboard:view' },
|
||||
{ path: '/admin/users', iconKey: 'user', label: '用户管理', permissionCode: 'user:view' },
|
||||
{ path: '/admin/products', iconKey: 'shop', label: '作品管理', permissionCode: 'product:view' },
|
||||
{ path: '/admin/coupons', iconKey: 'gift', label: '优惠券管理', permissionCode: 'coupon:view' },
|
||||
{ path: '/admin/comments', iconKey: 'message', label: '评论管理', permissionCode: 'comment:view' },
|
||||
{ path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' },
|
||||
{ path: '/admin/permissions', iconKey: 'security', label: '权限管理', permissionCode: 'permission:view' },
|
||||
{ path: '/admin/tags', iconKey: 'tag', label: '标签管理', permissionCode: 'tag:view' },
|
||||
{ path: '/admin/orders', iconKey: 'shopping', label: '订单管理', permissionCode: 'order:view' },
|
||||
{ path: '/admin/schedules', iconKey: 'calendar', label: '排班管理', permissionCode: 'schedule:view' },
|
||||
{ path: '/admin/after-sales', iconKey: 'message', label: '售后处理', permissionCode: 'after_sale:view' },
|
||||
{ path: '/admin/inventory', iconKey: 'tool', label: '库存管理', permissionCode: 'inventory:view' },
|
||||
{ path: '/admin/campaigns', iconKey: 'gift', label: '活动管理', permissionCode: 'campaign:view' },
|
||||
{ path: '/admin/nail-artists', iconKey: 'team', label: '美甲师管理', permissionCode: 'nail_artist:view' },
|
||||
{ path: '/admin/messages', iconKey: 'message', label: '消息发布', permissionCode: 'message:view' },
|
||||
{ path: '/admin/announcements', iconKey: 'message', label: '公告管理', permissionCode: 'announcement:view' },
|
||||
{ path: '/admin/vip-recharge-plans', iconKey: 'gift', label: 'VIP充值配置', permissionCode: 'user:vip:manage' },
|
||||
{ path: '/admin/messagehub-push-configs', iconKey: 'message', label: '参数管理', permissionCode: 'messagehub:config:manage' },
|
||||
{ path: '/admin/legal-agreements', iconKey: 'security', label: '协议管理', permissionCode: 'legal_agreement:manage' }
|
||||
]
|
||||
|
||||
export const adminPermissionRouteMap = adminNavigationItems
|
||||
.filter(item => item.permissionCode)
|
||||
.map(item => ({
|
||||
code: item.permissionCode,
|
||||
path: item.path
|
||||
}))
|
||||
|
||||
export const findAdminNavigationItemByPath = (path: string) =>
|
||||
adminNavigationItems.find(item => item.path === path)
|
||||
@@ -0,0 +1,58 @@
|
||||
import zhCN from 'ant-design-vue/es/locale/zh_CN'
|
||||
|
||||
/**
|
||||
* Purpose: baseCalendar supports antdv-locale.ts by holding or executing the base calendar page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const baseCalendar = (zhCN.Calendar || { lang: {} }) as any
|
||||
/**
|
||||
* Purpose: baseDatePicker supports antdv-locale.ts by holding or executing the base date picker page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const baseDatePicker = (zhCN.DatePicker || { lang: {}, timePickerLocale: {} }) as any
|
||||
/**
|
||||
* Purpose: baseTimePicker supports antdv-locale.ts by holding or executing the base time picker page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const baseTimePicker = (zhCN.TimePicker || {}) as any
|
||||
|
||||
const antdLocale: any = {
|
||||
...zhCN,
|
||||
Modal: {
|
||||
...zhCN.Modal,
|
||||
okText: '确认',
|
||||
cancelText: zhCN.Modal?.cancelText || '取消',
|
||||
justOkText: zhCN.Modal?.justOkText || '知道了'
|
||||
},
|
||||
Popconfirm: {
|
||||
...zhCN.Popconfirm,
|
||||
okText: '确认',
|
||||
cancelText: zhCN.Popconfirm?.cancelText || '取消'
|
||||
},
|
||||
Calendar: {
|
||||
...baseCalendar,
|
||||
lang: {
|
||||
...baseCalendar.lang,
|
||||
ok: '确认',
|
||||
now: '现在时间'
|
||||
}
|
||||
},
|
||||
DatePicker: {
|
||||
...baseDatePicker,
|
||||
lang: {
|
||||
...baseDatePicker.lang,
|
||||
ok: '确认',
|
||||
now: '现在时间'
|
||||
},
|
||||
timePickerLocale: {
|
||||
...baseDatePicker.timePickerLocale,
|
||||
now: '现在时间'
|
||||
}
|
||||
},
|
||||
TimePicker: {
|
||||
...baseTimePicker,
|
||||
now: '现在时间'
|
||||
}
|
||||
}
|
||||
|
||||
export default antdLocale
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Purpose: normalizeBaseUrl supports api.ts by holding or executing the normalize base url page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function normalizeBaseUrl(value: string | undefined, fallbackValue: string) {
|
||||
const target = String(value || fallbackValue).trim()
|
||||
return target.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: DEFAULT_API_BASE_URL supports api.ts by holding or executing the default api base url page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEFAULT_API_BASE_URL = import.meta.env.DEV ? '/api' : 'https://yunail.art/api'
|
||||
/**
|
||||
* Purpose: DEFAULT_ADMIN_API_BASE_URL supports api.ts by holding or executing the default admin api base url page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEFAULT_ADMIN_API_BASE_URL = import.meta.env.DEV ? '/admin/api' : 'https://yunail.art/admin/api'
|
||||
|
||||
/**
|
||||
* Purpose: API_CONFIG supports api.ts by holding or executing the api config page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const API_CONFIG = {
|
||||
mode: import.meta.env.MODE,
|
||||
apiBaseUrl: normalizeBaseUrl(import.meta.env.VITE_API_BASE_URL, DEFAULT_API_BASE_URL),
|
||||
adminApiBaseUrl: normalizeBaseUrl(import.meta.env.VITE_ADMIN_API_BASE_URL, DEFAULT_ADMIN_API_BASE_URL)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: API_BASE_URL supports api.ts by holding or executing the api base url page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const API_BASE_URL = API_CONFIG.apiBaseUrl
|
||||
/**
|
||||
* Purpose: ADMIN_API_BASE_URL supports api.ts by holding or executing the admin api base url page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ADMIN_API_BASE_URL = API_CONFIG.adminApiBaseUrl
|
||||
@@ -0,0 +1,12 @@
|
||||
function normalizeBrandValue(value: string | undefined, fallbackValue: string): string {
|
||||
const target = String(value || fallbackValue).trim()
|
||||
return target || fallbackValue
|
||||
}
|
||||
|
||||
export const BRAND_CONFIG = {
|
||||
appName: normalizeBrandValue(import.meta.env.VITE_APP_NAME, 'Jayu Artist'),
|
||||
appNameEn: normalizeBrandValue(import.meta.env.VITE_APP_NAME_EN, 'Jiayu Designer'),
|
||||
appTitle: normalizeBrandValue(import.meta.env.VITE_APP_TITLE, 'Jayu Artist'),
|
||||
adminAppName: normalizeBrandValue(import.meta.env.VITE_ADMIN_APP_NAME, 'Jayu Artist管理台'),
|
||||
appShortName: normalizeBrandValue(import.meta.env.VITE_APP_SHORT_NAME, 'YN')
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Purpose: DEFAULT_AVATAR supports index.ts by holding or executing the default avatar page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const DEFAULT_AVATAR = 'https://api.dicebear.com/7.x/avataaars/svg?seed=default'
|
||||
/**
|
||||
* Purpose: DEFAULT_PRODUCT_IMAGE supports index.ts by holding or executing the default product image page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const DEFAULT_PRODUCT_IMAGE = '/assets/images/default-product.png'
|
||||
/**
|
||||
* Purpose: DEFAULT_SHOP_IMAGE supports index.ts by holding or executing the default shop image page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const DEFAULT_SHOP_IMAGE = '/assets/images/default-shop.png'
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import 'ant-design-vue/dist/reset.css'
|
||||
import './styles/admin-mobile.css'
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { BRAND_CONFIG } from './config/brand'
|
||||
|
||||
document.title = BRAND_CONFIG.appTitle
|
||||
|
||||
/**
|
||||
* Purpose: app supports main.ts by holding or executing the app page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const app = createApp(App)
|
||||
/**
|
||||
* Purpose: pinia supports main.ts by holding or executing the pinia page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const pinia = createPinia()
|
||||
|
||||
app.use(pinia)
|
||||
app.use(router)
|
||||
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,371 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import {
|
||||
canAccessAdminRoute,
|
||||
clearAdminBootstrapSession,
|
||||
ensureAdminAuthBootstrap,
|
||||
getAdminBootstrapSnapshot,
|
||||
resolveAdminLandingPath,
|
||||
} from '@/utils/admin-auth-bootstrap'
|
||||
|
||||
/**
|
||||
* Purpose: router supports index.ts by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'auth',
|
||||
component: () => import('../views/AuthView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/home',
|
||||
name: 'home',
|
||||
component: () => import('../views/HomeView.vue'),
|
||||
meta: { requiresAuth: false, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/products',
|
||||
name: 'products',
|
||||
component: () => import('../views/ProductListView.vue'),
|
||||
meta: { requiresAuth: false, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/product/:id',
|
||||
name: 'product-detail',
|
||||
component: () => import('../views/ProductDetailView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/cart',
|
||||
name: 'cart',
|
||||
component: () => import('../views/CartView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
name: 'profile',
|
||||
component: () => import('../views/ProfileView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/shop/:id',
|
||||
name: 'shop-detail',
|
||||
component: () => import('../views/ShopDetailView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/shop/:shopId/artists',
|
||||
name: 'shop-artists',
|
||||
component: () => import('../views/ArtistListView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/artist/:id',
|
||||
name: 'artist-profile',
|
||||
component: () => import('../views/ArtistProfileView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/wishlist',
|
||||
name: 'wishlist',
|
||||
component: () => import('../views/WishlistView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/orders',
|
||||
name: 'orders',
|
||||
component: () => import('../views/OrderView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/orders/:id',
|
||||
name: 'order-detail',
|
||||
component: () => import('../views/OrderDetailView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/after-sales',
|
||||
name: 'after-sales',
|
||||
component: () => import('../views/AfterSalesView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/after-sale/apply',
|
||||
name: 'after-sale-apply',
|
||||
component: () => import('../views/AfterSaleApplyView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/service-progress',
|
||||
name: 'service-progress',
|
||||
component: () => import('../views/ServiceProgressView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/help',
|
||||
name: 'help',
|
||||
component: () => import('../views/HelpView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/artist-orders',
|
||||
name: 'artist-orders',
|
||||
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',
|
||||
component: () => import('../views/SettingsView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/settings/account',
|
||||
name: 'account-settings',
|
||||
component: () => import('../views/AccountSettingsView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/settings/password',
|
||||
name: 'password-settings',
|
||||
component: () => import('../views/PasswordSettingsView.vue'),
|
||||
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
|
||||
},
|
||||
{
|
||||
path: '/coupons',
|
||||
name: 'coupons',
|
||||
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',
|
||||
component: () => import('../views/admin/AdminLoginView.vue'),
|
||||
meta: { requiresAuth: false, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: '/admin',
|
||||
component: () => import('../views/admin/AdminLayout.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true },
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
name: 'admin',
|
||||
component: () => import('../views/admin/HomeView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: 'admin-dashboard',
|
||||
component: () => import('../views/admin/DashboardView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'dashboard:view' }
|
||||
},
|
||||
{
|
||||
path: 'users',
|
||||
name: 'admin-users',
|
||||
component: () => import('../views/admin/UsersView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:view' }
|
||||
},
|
||||
{
|
||||
path: 'products',
|
||||
name: 'admin-products',
|
||||
component: () => import('../views/admin/ProductsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'product:view' }
|
||||
},
|
||||
{
|
||||
path: 'coupons',
|
||||
name: 'admin-coupons',
|
||||
component: () => import('../views/admin/CouponsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'coupon:view' }
|
||||
},
|
||||
{
|
||||
path: 'comments',
|
||||
name: 'admin-comments',
|
||||
component: () => import('../views/admin/CommentsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'comment:view' }
|
||||
},
|
||||
{
|
||||
path: 'shops',
|
||||
name: 'admin-shops',
|
||||
component: () => import('../views/admin/ShopsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'shop:view' }
|
||||
},
|
||||
{
|
||||
path: 'permissions',
|
||||
name: 'admin-permissions',
|
||||
component: () => import('../views/admin/PermissionsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'permission:view' }
|
||||
},
|
||||
{
|
||||
path: 'orders',
|
||||
name: 'admin-orders',
|
||||
component: () => import('../views/admin/OrdersView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'order:view' }
|
||||
},
|
||||
{
|
||||
path: 'schedules',
|
||||
name: 'admin-schedules',
|
||||
component: () => import('../views/admin/SchedulesView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'schedule:view' }
|
||||
},
|
||||
{
|
||||
path: 'after-sales',
|
||||
name: 'admin-after-sales',
|
||||
component: () => import('../views/admin/AfterSalesView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'after_sale:view' }
|
||||
},
|
||||
{
|
||||
path: 'inventory',
|
||||
name: 'admin-inventory',
|
||||
component: () => import('../views/admin/InventoryView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'inventory:view' }
|
||||
},
|
||||
{
|
||||
path: 'campaigns',
|
||||
name: 'admin-campaigns',
|
||||
component: () => import('../views/admin/CampaignsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'campaign:view' }
|
||||
},
|
||||
{
|
||||
path: 'manage',
|
||||
name: 'admin-manage',
|
||||
component: () => import('../views/admin/ManageView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: 'profile',
|
||||
name: 'admin-profile',
|
||||
component: () => import('../views/admin/ProfileView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
|
||||
},
|
||||
{
|
||||
path: 'tags',
|
||||
name: 'admin-tags',
|
||||
component: () => import('../views/admin/TagsView.vue'),
|
||||
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'tag:view' }
|
||||
},
|
||||
{
|
||||
path: 'nail-artists',
|
||||
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' }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
component: () => import('../views/NotFoundView.vue'),
|
||||
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
router.beforeEach(async (to) => {
|
||||
const isAdminRoute = Boolean(to.meta.isAdmin)
|
||||
const requiresAuth = Boolean(to.meta.requiresAuth)
|
||||
|
||||
if (isAdminRoute) {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
|
||||
if (to.path === '/admin/login') {
|
||||
if (!snapshot.token || !snapshot.userInfo) {
|
||||
return true
|
||||
}
|
||||
|
||||
const state = await ensureAdminAuthBootstrap()
|
||||
return state === 'ready' ? resolveAdminLandingPath() : true
|
||||
}
|
||||
|
||||
if (requiresAuth && (!snapshot.token || !snapshot.userInfo)) {
|
||||
clearAdminBootstrapSession()
|
||||
return '/admin/login'
|
||||
}
|
||||
|
||||
const bootstrapState = await ensureAdminAuthBootstrap()
|
||||
if (bootstrapState !== 'ready') {
|
||||
return '/admin/login'
|
||||
}
|
||||
|
||||
if (!canAccessAdminRoute(to.path, to.meta.permissionCode as string | undefined)) {
|
||||
return resolveAdminLandingPath()
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
|
||||
|
||||
if (requiresAuth && !token) {
|
||||
return '/'
|
||||
}
|
||||
|
||||
if (to.path === '/' && token) {
|
||||
return '/home'
|
||||
}
|
||||
|
||||
if (requiresAuth && token) {
|
||||
const userInfo = localStorage.getItem('userInfo')
|
||||
if (!userInfo) {
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
sessionStorage.removeItem('accessToken')
|
||||
return '/'
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,342 @@
|
||||
:root {
|
||||
--primary-color: #E8B4B8;
|
||||
--theme-primary: #E8B4B8;
|
||||
--theme-secondary: #C5A059;
|
||||
--theme-accent: #4A443F;
|
||||
--theme-neutral: #4A443F;
|
||||
--theme-tertiary: #FDFBF9;
|
||||
--theme-primary-action: #766361;
|
||||
--theme-primary-soft: #FAEFF0;
|
||||
--theme-secondary-soft: #EADCC2;
|
||||
--theme-page-bg: #FDFBF9;
|
||||
--theme-card-bg: #FFFFFF;
|
||||
--theme-border: #F9EAEC;
|
||||
--theme-gradient: linear-gradient(135deg, #766361 0%, #C5A059 100%);
|
||||
--theme-gradient-soft: linear-gradient(145deg, #FFFFFF 0%, #EADCC2 58%, #F5E0E0 100%);
|
||||
--theme-button-shadow: 0 12px 28px rgba(232, 180, 184, 0.26);
|
||||
--theme-focus-shadow: 0 0 0 3px rgba(232, 180, 184, 0.2);
|
||||
--theme-background-image: none;
|
||||
--bg-color: #FDFBF9;
|
||||
--secondary-bg-color: #EADCC2;
|
||||
--surface-color: #FFFFFF;
|
||||
--text-primary: #4A443F;
|
||||
--text-secondary: #6B6662;
|
||||
--border-radius-base: 10px;
|
||||
--border-radius-large: 30px;
|
||||
--frontend-min-safe-width: 320px;
|
||||
--frontend-page-max-width: 430px;
|
||||
--frontend-content-max-width: 1120px;
|
||||
--admin-content-max-width: 1440px;
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
img,
|
||||
video,
|
||||
canvas,
|
||||
svg {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
min-width: var(--frontend-min-safe-width);
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
background:
|
||||
radial-gradient(circle at 50% 0%, color-mix(in srgb, var(--theme-primary) 24%, transparent), transparent 34%),
|
||||
linear-gradient(180deg, var(--theme-tertiary), color-mix(in srgb, var(--theme-secondary) 12%, var(--theme-tertiary)));
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.mobile-container {
|
||||
width: 100%;
|
||||
min-width: var(--frontend-min-safe-width);
|
||||
max-width: none;
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
background:
|
||||
radial-gradient(circle at 82% 2%, color-mix(in srgb, var(--theme-primary) 30%, transparent), transparent 28%),
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 74%, transparent), color-mix(in srgb, var(--theme-page-bg) 98%, var(--theme-card-bg))),
|
||||
var(--theme-background-image),
|
||||
var(--bg-color);
|
||||
background-size: auto, cover, cover, auto;
|
||||
background-position: center top;
|
||||
position: relative;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.jayu-cloud-page {
|
||||
min-height: 100vh;
|
||||
padding: 18px 18px calc(88px + env(safe-area-inset-bottom, 0px));
|
||||
color: var(--text-primary);
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.7), rgba(253, 251, 249, 0.96)),
|
||||
var(--theme-background-image),
|
||||
var(--theme-page-bg);
|
||||
background-size: cover, cover, auto;
|
||||
background-position: center top;
|
||||
}
|
||||
|
||||
.jayu-cloud-page--no-nav {
|
||||
padding-bottom: calc(28px + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
|
||||
.jayu-cloud-section {
|
||||
margin-top: 22px;
|
||||
}
|
||||
|
||||
.jayu-cloud-section-head {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.jayu-cloud-kicker {
|
||||
display: block;
|
||||
color: var(--theme-primary-action);
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.jayu-cloud-title {
|
||||
display: block;
|
||||
color: var(--text-primary);
|
||||
font-size: 21px;
|
||||
font-weight: 760;
|
||||
line-height: 1.18;
|
||||
}
|
||||
|
||||
.jayu-cloud-subtitle {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.jayu-cloud-glass-card {
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(255, 255, 255, 0.9);
|
||||
border-radius: 24px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
|
||||
box-shadow: 0 20px 44px rgba(74, 68, 63, 0.1);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
.jayu-cloud-icon-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
color: var(--theme-neutral);
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 78%, transparent);
|
||||
box-shadow: 0 10px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
|
||||
cursor: pointer;
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.jayu-cloud-icon-button:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.nav-button, .icon-btn, .back-btn, .jayu-cloud-icon-button) :where(.anticon),
|
||||
.app-container--phone-shell :where(.header, .shop-topbar, .detail-header, .artist-topbar, .artist-list-topbar, .auth-topbar, .not-found-topbar, .cart-topbar, .vip-header) :where(.ant-btn .anticon, button .anticon),
|
||||
.app-container--admin :where(.mobile-icon-btn, .mobile-avatar-btn) :where(.anticon) {
|
||||
font-size: 21px !important;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.bottom-nav .nav-icon) {
|
||||
width: 40px;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.bottom-nav .nav-icon .anticon) {
|
||||
font-size: 25px !important;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.app-container--admin :where(.mobile-tabbar__item .anticon) {
|
||||
font-size: 21px !important;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.nav-button, .icon-btn, .back-btn, .jayu-cloud-icon-button, .bottom-nav .nav-icon) :where(.anticon svg),
|
||||
.app-container--admin :where(.mobile-icon-btn, .mobile-avatar-btn, .mobile-tabbar__item) :where(.anticon svg) {
|
||||
display: block;
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
}
|
||||
|
||||
.jayu-cloud-page-titlebar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 12px 18px 8px;
|
||||
}
|
||||
|
||||
.jayu-cloud-page-titlebar__title {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
color: var(--text-primary);
|
||||
font-size: 16px;
|
||||
font-weight: 780;
|
||||
}
|
||||
|
||||
.jayu-cloud-status-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 26px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--theme-border);
|
||||
border-radius: 999px;
|
||||
color: var(--theme-primary-action);
|
||||
background: var(--theme-primary-soft);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.jayu-cloud-bottom-action {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin: 24px -18px -18px;
|
||||
padding: 14px 18px calc(14px + env(safe-area-inset-bottom, 0px));
|
||||
border-top: 1px solid var(--theme-border);
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.ant-card) {
|
||||
border-color: var(--theme-border);
|
||||
border-radius: 24px;
|
||||
background: rgba(255, 255, 255, 0.86);
|
||||
box-shadow: 0 18px 42px rgba(74, 68, 63, 0.09);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.ant-btn-primary) {
|
||||
border-color: transparent;
|
||||
background: var(--theme-gradient);
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.ant-btn-primary:hover, .ant-btn-primary:focus) {
|
||||
border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.ant-input, .ant-input-affix-wrapper, .ant-select-selector, .ant-picker) {
|
||||
border-color: var(--theme-border);
|
||||
border-radius: 14px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent);
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.ant-input:hover, .ant-input:focus, .ant-input-affix-wrapper:hover, .ant-input-affix-wrapper-focused, .ant-picker:hover, .ant-picker-focused) {
|
||||
border-color: var(--theme-primary);
|
||||
box-shadow: var(--theme-focus-shadow);
|
||||
}
|
||||
|
||||
.app-container--phone-shell :where(.ant-tag) {
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.app-container--phone-shell .header {
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
|
||||
border-bottom-color: var(--theme-border);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame {
|
||||
width: 100%;
|
||||
min-width: var(--frontend-min-safe-width);
|
||||
min-height: 100vh;
|
||||
margin: 0 auto;
|
||||
background: var(--theme-page-bg);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame--hidden-nav {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
body {
|
||||
background:
|
||||
radial-gradient(circle at 18% 8%, rgba(254, 212, 136, 0.28), transparent 30%),
|
||||
radial-gradient(circle at 82% 12%, rgba(232, 180, 184, 0.24), transparent 34%),
|
||||
var(--secondary-bg-color);
|
||||
}
|
||||
|
||||
.app-container--phone-shell {
|
||||
align-items: center;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.mobile-container {
|
||||
max-width: var(--frontend-page-max-width);
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame {
|
||||
width: min(100%, var(--frontend-page-max-width));
|
||||
min-height: 100vh;
|
||||
margin: 0 auto;
|
||||
overflow: clip;
|
||||
border: 1px solid rgba(212, 194, 195, 0.72);
|
||||
border-radius: 32px;
|
||||
box-shadow: 0 28px 80px rgba(74, 68, 63, 0.14);
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame > .bottom-nav,
|
||||
.jayu-cloud-phone-frame > .page-content .header,
|
||||
.jayu-cloud-phone-frame > .page-content .header-bg,
|
||||
.jayu-cloud-phone-frame > .page-content .gallery-header,
|
||||
.jayu-cloud-phone-frame > .page-content .order-header {
|
||||
left: 50%;
|
||||
right: auto;
|
||||
width: var(--frontend-page-max-width);
|
||||
max-width: calc(100vw - 48px);
|
||||
transform: translateX(-50%) translateZ(0);
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame > .page-content .header,
|
||||
.jayu-cloud-phone-frame > .page-content .header-bg,
|
||||
.jayu-cloud-phone-frame > .page-content .gallery-header,
|
||||
.jayu-cloud-phone-frame > .page-content .order-header {
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame > .page-content .header,
|
||||
.jayu-cloud-phone-frame > .page-content .gallery-header,
|
||||
.jayu-cloud-phone-frame > .page-content .order-header {
|
||||
border-top-left-radius: 32px;
|
||||
border-top-right-radius: 32px;
|
||||
}
|
||||
|
||||
.jayu-cloud-phone-frame > .bottom-nav {
|
||||
bottom: 0;
|
||||
border-bottom-right-radius: 32px;
|
||||
border-bottom-left-radius: 32px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
:root {
|
||||
--admin-mobile-ink: var(--text-primary);
|
||||
--admin-mobile-surface: var(--theme-page-bg);
|
||||
--admin-mobile-surface-alt: var(--theme-primary-soft);
|
||||
--admin-mobile-card: var(--theme-card-bg);
|
||||
--admin-mobile-border: var(--theme-border);
|
||||
--admin-mobile-muted: var(--text-secondary);
|
||||
--admin-mobile-accent: var(--theme-primary);
|
||||
--admin-mobile-accent-strong: var(--theme-accent);
|
||||
--admin-mobile-accent-soft: var(--theme-primary-soft);
|
||||
--admin-mobile-shell-start: var(--theme-primary);
|
||||
--admin-mobile-shell-mid: var(--theme-accent);
|
||||
--admin-mobile-shell-end: color-mix(in srgb, var(--theme-accent) 78%, var(--text-primary));
|
||||
--admin-mobile-shell-glass: color-mix(in srgb, var(--theme-primary) 88%, transparent);
|
||||
--admin-mobile-shell-soft: color-mix(in srgb, var(--theme-card-bg) 18%, transparent);
|
||||
--admin-mobile-radius: 24px;
|
||||
--admin-mobile-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
.admin-page-intro {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
margin-bottom: 18px;
|
||||
padding: 20px 18px;
|
||||
color: var(--theme-card-bg);
|
||||
background:
|
||||
radial-gradient(circle at top right, color-mix(in srgb, var(--theme-card-bg) 20%, transparent), transparent 38%),
|
||||
radial-gradient(circle at left top, color-mix(in srgb, var(--theme-secondary) 22%, transparent), transparent 42%),
|
||||
linear-gradient(
|
||||
155deg,
|
||||
var(--admin-mobile-shell-start) 0%,
|
||||
var(--admin-mobile-shell-mid) 56%,
|
||||
var(--admin-mobile-shell-end) 100%
|
||||
);
|
||||
border-radius: 24px;
|
||||
box-shadow: 0 18px 40px rgba(146, 103, 82, 0.2);
|
||||
}
|
||||
|
||||
.admin-page-intro__eyebrow {
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
color: rgba(255, 248, 241, 0.74);
|
||||
}
|
||||
|
||||
.admin-page-intro__title {
|
||||
margin: 0;
|
||||
font-size: clamp(20px, 4vw, 26px);
|
||||
line-height: 1.08;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.admin-page-intro__subtitle {
|
||||
margin: 0;
|
||||
line-height: 1.65;
|
||||
color: rgba(255, 248, 241, 0.82);
|
||||
}
|
||||
|
||||
.shops .admin-page-intro__subtitle,
|
||||
.permissions .admin-page-intro__subtitle,
|
||||
.orders .admin-page-intro__subtitle,
|
||||
.nail-artists .admin-page-intro__subtitle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-page-intro__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-page-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 34px;
|
||||
padding: 0 12px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 16%, transparent);
|
||||
color: var(--theme-card-bg);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.admin-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin-toolbar--stacked {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.admin-toolbar__grow {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-mobile-card-list {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.admin-mobile-card {
|
||||
padding: 16px;
|
||||
background: var(--admin-mobile-card);
|
||||
border: 1px solid var(--admin-mobile-border);
|
||||
border-radius: 22px;
|
||||
box-shadow: 0 12px 28px rgba(144, 103, 84, 0.09);
|
||||
}
|
||||
|
||||
.admin-mobile-card__cover {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
border-radius: 18px;
|
||||
object-fit: cover;
|
||||
flex-shrink: 0;
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.admin-mobile-card__cover--wide {
|
||||
width: 100%;
|
||||
height: 148px;
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.admin-mobile-card__head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin-mobile-card__head--media {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.admin-mobile-card__body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-mobile-card__title {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
color: var(--admin-mobile-ink);
|
||||
}
|
||||
|
||||
.admin-mobile-card__subtitle {
|
||||
margin-top: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--admin-mobile-muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.admin-mobile-card__description {
|
||||
margin-top: 10px;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.admin-mobile-card__rows {
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.admin-mobile-card__row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: 13px;
|
||||
color: var(--admin-mobile-muted);
|
||||
}
|
||||
|
||||
.admin-mobile-card__row span:first-child {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.admin-mobile-card__row strong,
|
||||
.admin-mobile-card__row b {
|
||||
min-width: 0;
|
||||
color: var(--admin-mobile-ink);
|
||||
font-weight: 600;
|
||||
text-align: right;
|
||||
word-break: normal;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.admin-mobile-card__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.admin-mobile-card__badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 30px;
|
||||
padding: 0 12px;
|
||||
border-radius: 999px;
|
||||
background: var(--admin-mobile-accent-soft);
|
||||
color: var(--theme-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin-mobile-grid {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.admin-mobile-grid--two {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.admin-mobile-stat {
|
||||
padding: 16px;
|
||||
background: var(--admin-mobile-card);
|
||||
border: 1px solid var(--admin-mobile-border);
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 10px 24px rgba(144, 103, 84, 0.08);
|
||||
}
|
||||
|
||||
.admin-mobile-stat__label {
|
||||
font-size: 12px;
|
||||
color: var(--admin-mobile-muted);
|
||||
}
|
||||
|
||||
.admin-mobile-stat__value {
|
||||
margin-top: 10px;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: var(--admin-mobile-ink);
|
||||
}
|
||||
|
||||
.admin-mobile-section-card {
|
||||
padding: 18px;
|
||||
background: var(--admin-mobile-card);
|
||||
border: 1px solid var(--admin-mobile-border);
|
||||
border-radius: 22px;
|
||||
box-shadow: 0 12px 28px rgba(144, 103, 84, 0.09);
|
||||
}
|
||||
|
||||
.admin-mobile-section-card__title {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: var(--admin-mobile-ink);
|
||||
}
|
||||
|
||||
.admin-mobile-section-card__subtitle {
|
||||
margin-top: 6px;
|
||||
color: var(--admin-mobile-muted);
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal {
|
||||
top: 0 !important;
|
||||
max-width: 100dvw !important;
|
||||
width: 100dvw !important;
|
||||
margin: 0;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal-content {
|
||||
min-height: 100vh;
|
||||
border-radius: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
padding: 18px 18px 14px;
|
||||
background: var(--theme-card-bg);
|
||||
border-bottom: 1px solid var(--admin-mobile-border);
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal-title {
|
||||
padding-right: 24px;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--admin-mobile-ink);
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal-close {
|
||||
top: 12px;
|
||||
inset-inline-end: 12px;
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal-body {
|
||||
padding: 16px 16px 104px;
|
||||
}
|
||||
|
||||
.admin-mobile-modal .ant-modal-footer {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
padding: 14px 16px calc(14px + env(safe-area-inset-bottom));
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 94%, transparent);
|
||||
border-top: 1px solid var(--admin-mobile-border);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.admin-mobile-fab {
|
||||
position: fixed;
|
||||
right: 18px;
|
||||
bottom: var(--admin-mobile-fab-bottom, calc(96px + env(safe-area-inset-bottom)));
|
||||
z-index: 120;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--theme-gradient);
|
||||
color: #ffffff;
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
.admin-mobile-fab .anticon {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
body {
|
||||
background: var(--admin-mobile-surface);
|
||||
}
|
||||
|
||||
.admin-mobile-grid--two {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.admin-mobile-grid--two {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.bottom-nav {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
height: 60px;
|
||||
background: white;
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
|
||||
z-index: 1000;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Purpose: ACCOUNT_REGEX supports account.ts by holding or executing the account regex page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ACCOUNT_REGEX = /^[A-Za-z0-9]+$/
|
||||
/**
|
||||
* Purpose: ACCOUNT_SANITIZE_REGEX supports account.ts by holding or executing the account sanitize regex page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const ACCOUNT_SANITIZE_REGEX = /[^A-Za-z0-9]/g
|
||||
|
||||
/**
|
||||
* Purpose: ACCOUNT_RULE_MESSAGE supports account.ts by holding or executing the account rule message page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ACCOUNT_RULE_MESSAGE = '账号只能包含字母和数字'
|
||||
|
||||
/**
|
||||
* Purpose: sanitizeAccountInput supports account.ts by holding or executing the sanitize account input page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const sanitizeAccountInput = (value: string) => (value || '').replace(ACCOUNT_SANITIZE_REGEX, '')
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Purpose: LoadingInstance supports action-loading.ts by holding or executing the loading instance page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { ElLoading, type LoadingInstance } from 'element-plus'
|
||||
import 'element-plus/es/components/loading/style/css'
|
||||
|
||||
/**
|
||||
* Purpose: GlobalLoadingOptions supports action-loading.ts by holding or executing the global loading options page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface GlobalLoadingOptions {
|
||||
text?: string
|
||||
lock?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: activeLoadingCount supports action-loading.ts by holding or executing the active loading count page or API role.
|
||||
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
let activeLoadingCount = 0
|
||||
let loadingInstance: LoadingInstance | null = null
|
||||
|
||||
/**
|
||||
* Purpose: openGlobalLoading supports action-loading.ts by holding or executing the open global loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const openGlobalLoading = (options?: GlobalLoadingOptions) => {
|
||||
activeLoadingCount += 1
|
||||
|
||||
if (typeof window === 'undefined' || loadingInstance) {
|
||||
return
|
||||
}
|
||||
|
||||
loadingInstance = ElLoading.service({
|
||||
lock: options?.lock ?? true,
|
||||
text: options?.text ?? '\u52a0\u8f7d\u4e2d',
|
||||
background: 'rgba(255, 255, 255, 0.72)'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: closeGlobalLoading supports action-loading.ts by holding or executing the close global loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const closeGlobalLoading = () => {
|
||||
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
|
||||
|
||||
if (activeLoadingCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
loadingInstance?.close()
|
||||
loadingInstance = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: runWithGlobalLoading supports action-loading.ts by holding or executing the run with global loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const runWithGlobalLoading = async <T>(
|
||||
task: (() => Promise<T>) | Promise<T>,
|
||||
options?: GlobalLoadingOptions
|
||||
) => {
|
||||
openGlobalLoading(options)
|
||||
|
||||
try {
|
||||
if (typeof task === 'function') {
|
||||
return await task()
|
||||
}
|
||||
|
||||
return await task
|
||||
} finally {
|
||||
closeGlobalLoading()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import {
|
||||
clearAdminSessionStorage,
|
||||
getAdminAccessToken,
|
||||
isBootstrapAdminUser,
|
||||
loadCachedAdminUserInfo,
|
||||
} from '@/utils/admin-session'
|
||||
import { ADMIN_DASHBOARD_PATH, adminPermissionRouteMap } from '@/config/admin-navigation'
|
||||
import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions'
|
||||
import {
|
||||
clearStoredPermissions,
|
||||
fetchUserPermissionsStrict,
|
||||
getStoredUserPermissions,
|
||||
} from '@/utils/permission'
|
||||
|
||||
|
||||
/**
|
||||
* Purpose: AuthBootstrapState supports admin-auth-bootstrap.ts by holding or executing the auth bootstrap state page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export type AuthBootstrapState = 'pending' | 'ready' | 'invalid'
|
||||
|
||||
/**
|
||||
* Purpose: adminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the admin bootstrap state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const adminBootstrapState = ref<AuthBootstrapState>('pending')
|
||||
let bootstrapPromise: Promise<AuthBootstrapState> | null = null
|
||||
|
||||
|
||||
/**
|
||||
* Purpose: useAdminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the use admin bootstrap state page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const useAdminBootstrapState = () => computed(() => adminBootstrapState.value)
|
||||
|
||||
/**
|
||||
* Purpose: invalidateAdminBootstrap supports admin-auth-bootstrap.ts by holding or executing the invalidate admin bootstrap page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const invalidateAdminBootstrap = () => {
|
||||
adminBootstrapState.value = 'pending'
|
||||
bootstrapPromise = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: clearAdminBootstrapSession supports admin-auth-bootstrap.ts by holding or executing the clear admin bootstrap session page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const clearAdminBootstrapSession = () => {
|
||||
clearAdminSessionStorage()
|
||||
clearStoredPermissions()
|
||||
adminBootstrapState.value = 'invalid'
|
||||
bootstrapPromise = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getAdminBootstrapSnapshot supports admin-auth-bootstrap.ts by holding or executing the get admin bootstrap snapshot page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const getAdminBootstrapSnapshot = () => {
|
||||
const userInfo = loadCachedAdminUserInfo()
|
||||
return {
|
||||
token: getAdminAccessToken(),
|
||||
userInfo,
|
||||
isBootstrapAdmin: isBootstrapAdminUser(userInfo),
|
||||
isPlatformAdmin: Number(userInfo?.type) === 4,
|
||||
permissions: getStoredUserPermissions() || [],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hasAdminPermission supports admin-auth-bootstrap.ts by holding or executing the has admin permission page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const hasAdminPermission = (permissionCode?: string) => {
|
||||
if (!permissionCode) {
|
||||
return true
|
||||
}
|
||||
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (snapshot.isBootstrapAdmin || (snapshot.isPlatformAdmin && isAllowedForShoplessPlatformAdmin(permissionCode))) {
|
||||
return isAllowedForShoplessPlatformAdmin(permissionCode)
|
||||
}
|
||||
|
||||
return snapshot.permissions.includes(permissionCode)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveAdminLandingPath supports admin-auth-bootstrap.ts by holding or executing the resolve admin landing path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const resolveAdminLandingPath = () => {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) {
|
||||
return '/admin'
|
||||
}
|
||||
if (snapshot.isBootstrapAdmin) {
|
||||
return ADMIN_DASHBOARD_PATH
|
||||
}
|
||||
|
||||
const matchedRoute = adminPermissionRouteMap.find(item => snapshot.permissions.includes(item.code))
|
||||
return matchedRoute?.path || '/admin'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: canAccessAdminRoute supports admin-auth-bootstrap.ts by holding or executing the can access admin route page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const 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 hasAdminPermission(permissionCode)
|
||||
}
|
||||
|
||||
return hasAdminPermission(permissionCode)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ensureAdminAuthBootstrap supports admin-auth-bootstrap.ts by holding or executing the ensure admin auth bootstrap page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const ensureAdminAuthBootstrap = async (force = false): Promise<AuthBootstrapState> => {
|
||||
const snapshot = getAdminBootstrapSnapshot()
|
||||
if (!snapshot.token || !snapshot.userInfo) {
|
||||
clearAdminBootstrapSession()
|
||||
return 'invalid'
|
||||
}
|
||||
|
||||
if (snapshot.isBootstrapAdmin) {
|
||||
clearStoredPermissions()
|
||||
adminBootstrapState.value = 'ready'
|
||||
bootstrapPromise = null
|
||||
return 'ready'
|
||||
}
|
||||
|
||||
const cachedPermissions = getStoredUserPermissions()
|
||||
if (!force && cachedPermissions) {
|
||||
adminBootstrapState.value = 'ready'
|
||||
return 'ready'
|
||||
}
|
||||
|
||||
if (!force && bootstrapPromise) {
|
||||
return bootstrapPromise
|
||||
}
|
||||
|
||||
adminBootstrapState.value = 'pending'
|
||||
bootstrapPromise = (async () => {
|
||||
try {
|
||||
await fetchUserPermissionsStrict()
|
||||
adminBootstrapState.value = 'ready'
|
||||
return 'ready' as AuthBootstrapState
|
||||
} catch (error) {
|
||||
console.error('Failed to bootstrap admin permissions:', error)
|
||||
clearAdminBootstrapSession()
|
||||
return 'invalid' as AuthBootstrapState
|
||||
} finally {
|
||||
bootstrapPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return bootstrapPromise
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
buildAdminUploadFileList,
|
||||
buildSignedImageUrlMap,
|
||||
getRecordImageUrls,
|
||||
resolveSignedImageUrls
|
||||
} from './admin-image-assets'
|
||||
|
||||
vi.mock('@/utils/signed-image-cache', () => ({
|
||||
parseImageFileIds: (value?: string | null) => String(value || '').split(',').map(id => id.trim()).filter(Boolean),
|
||||
getCachedSignedImageUrl: async (fileId: string | number | null | undefined, fallback = '') =>
|
||||
fileId ? `signed-${fileId}` : fallback,
|
||||
getCachedSignedImageUrls: async (fileIds: Array<string | number | null | undefined>, fallback = '') => {
|
||||
const urls = fileIds.filter(Boolean).map(fileId => `signed-${fileId}`)
|
||||
return urls.length ? urls : (fallback ? [fallback] : [])
|
||||
}
|
||||
}))
|
||||
|
||||
describe('admin-image-assets', () => {
|
||||
it('resolves comma separated image ids with fallback policy', async () => {
|
||||
await expect(resolveSignedImageUrls('1, 2,,3', 'fallback.png', true)).resolves.toEqual([
|
||||
'signed-1',
|
||||
'signed-2',
|
||||
'signed-3'
|
||||
])
|
||||
await expect(resolveSignedImageUrls('', 'fallback.png', true)).resolves.toEqual(['fallback.png'])
|
||||
await expect(resolveSignedImageUrls('', 'fallback.png', false)).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('builds image url maps and respects cancellation', async () => {
|
||||
await expect(buildSignedImageUrlMap(
|
||||
[{ id: 7, imageFileIds: '10,11' }],
|
||||
'imageFileIds',
|
||||
'fallback.png',
|
||||
true,
|
||||
() => false
|
||||
)).resolves.toEqual({ 7: ['signed-10', 'signed-11'] })
|
||||
|
||||
await expect(buildSignedImageUrlMap(
|
||||
[{ id: 7, imageFileIds: '10,11' }],
|
||||
'imageFileIds',
|
||||
'fallback.png',
|
||||
true,
|
||||
() => true
|
||||
)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('returns mapped record images or fallback images', () => {
|
||||
expect(getRecordImageUrls({ id: 1 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['a.png'])
|
||||
expect(getRecordImageUrls({ id: 2 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['fallback.png'])
|
||||
})
|
||||
|
||||
it('builds upload file list from ids', async () => {
|
||||
await expect(buildAdminUploadFileList(['8', ' 9 '], '图片', 'fallback.png')).resolves.toEqual([
|
||||
{ uid: '8', fileId: '8', name: '图片1', status: 'done', url: 'signed-8' },
|
||||
{ uid: '9', fileId: '9', name: '图片2', status: 'done', url: 'signed-9' }
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
getCachedSignedImageUrl,
|
||||
getCachedSignedImageUrls,
|
||||
parseImageFileIds,
|
||||
refreshCachedSignedImageUrl
|
||||
} from '@/utils/signed-image-cache'
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
export interface AdminUploadFileItem {
|
||||
uid: string
|
||||
fileId: string
|
||||
name: string
|
||||
status: 'done'
|
||||
url: string
|
||||
}
|
||||
|
||||
export type SignedImageRecord = {
|
||||
id?: IdType
|
||||
imageFileIds?: string
|
||||
coverImageFileId?: string
|
||||
}
|
||||
|
||||
export type ImageFieldName = 'imageFileIds' | 'coverImageFileId'
|
||||
|
||||
export const resolveSignedImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback: string
|
||||
): Promise<string> => getCachedSignedImageUrl(fileId, fallback, 'admin')
|
||||
|
||||
export const refreshSignedImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback: string
|
||||
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'admin')
|
||||
|
||||
export const resolveSignedImageUrls = async (
|
||||
fileIdsValue: string | null | undefined,
|
||||
fallback: string,
|
||||
emptyFallback: boolean
|
||||
): Promise<string[]> => {
|
||||
const fileIds = parseImageFileIds(fileIdsValue)
|
||||
if (!fileIds.length) {
|
||||
return emptyFallback ? [fallback] : []
|
||||
}
|
||||
return getCachedSignedImageUrls(fileIds, fallback, 'admin')
|
||||
}
|
||||
|
||||
export const buildSignedImageUrlMap = async <TRecord extends SignedImageRecord>(
|
||||
records: TRecord[],
|
||||
fieldName: ImageFieldName,
|
||||
fallback: string,
|
||||
emptyFallback: boolean,
|
||||
isCancelled: () => boolean
|
||||
): Promise<Record<string, string[]> | null> => {
|
||||
const nextImageUrls: Record<string, string[]> = {}
|
||||
|
||||
for (const record of records) {
|
||||
if (isCancelled()) {
|
||||
return null
|
||||
}
|
||||
if (record.id === undefined || record.id === null) {
|
||||
continue
|
||||
}
|
||||
|
||||
nextImageUrls[String(record.id)] = await resolveSignedImageUrls(record[fieldName], fallback, emptyFallback)
|
||||
}
|
||||
|
||||
return nextImageUrls
|
||||
}
|
||||
|
||||
export const getRecordImageUrls = <TRecord extends { id?: IdType }>(
|
||||
record: TRecord,
|
||||
imageUrlMap: Record<string, string[]>,
|
||||
fallbackImages: string[]
|
||||
): string[] => {
|
||||
if (record.id === undefined || record.id === null) {
|
||||
return fallbackImages
|
||||
}
|
||||
return imageUrlMap[String(record.id)] || fallbackImages
|
||||
}
|
||||
|
||||
export const buildAdminUploadFileList = async (
|
||||
fileIds: string[],
|
||||
fileNamePrefix: string,
|
||||
fallback: string
|
||||
): Promise<AdminUploadFileItem[]> => {
|
||||
const fileList: AdminUploadFileItem[] = []
|
||||
|
||||
for (const [index, fileId] of fileIds.entries()) {
|
||||
const normalizedFileId = fileId.trim()
|
||||
if (!normalizedFileId) {
|
||||
continue
|
||||
}
|
||||
const url = await resolveSignedImageUrl(normalizedFileId, fallback)
|
||||
fileList.push({
|
||||
uid: normalizedFileId,
|
||||
fileId: normalizedFileId,
|
||||
name: `${fileNamePrefix}${index + 1}`,
|
||||
status: 'done',
|
||||
url
|
||||
})
|
||||
}
|
||||
|
||||
return fileList
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
/**
|
||||
* Purpose: AdminCachedUserInfo supports admin-session.ts by holding or executing the admin cached user info page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface AdminCachedUserInfo {
|
||||
id?: IdType
|
||||
type?: number
|
||||
account?: string
|
||||
nickname?: string
|
||||
avatar?: string
|
||||
shopId?: IdType
|
||||
shopName?: string
|
||||
shopAuthorizationExpireTime?: string
|
||||
shopAuthorizationExpired?: boolean
|
||||
shopIds?: IdType[]
|
||||
shopNames?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getAdminAccessToken supports admin-session.ts by holding or executing the get admin access token page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const getAdminAccessToken = () =>
|
||||
localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')
|
||||
|
||||
/**
|
||||
* Purpose: getAdminRefreshToken supports admin-session.ts by holding or executing the get admin refresh token page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const getAdminRefreshToken = () =>
|
||||
localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken')
|
||||
|
||||
/**
|
||||
* Purpose: loadCachedAdminUserInfo supports admin-session.ts by holding or executing the load cached admin user info page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const loadCachedAdminUserInfo = (): AdminCachedUserInfo | null => {
|
||||
const raw = localStorage.getItem('adminUserInfo')
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as AdminCachedUserInfo
|
||||
} catch (error) {
|
||||
console.error('Failed to parse cached admin user info:', error)
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isBootstrapAdminUser supports admin-session.ts by holding or executing the is bootstrap admin user page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isBootstrapAdminUser = (userInfo?: AdminCachedUserInfo | null) =>
|
||||
userInfo?.type === 4 && !userInfo?.shopId
|
||||
|
||||
/**
|
||||
* Purpose: isPlatformOverviewAdminUser supports admin-session.ts by holding or executing the is platform overview admin user page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isPlatformOverviewAdminUser = isBootstrapAdminUser
|
||||
|
||||
/**
|
||||
* Purpose: clearAdminSessionStorage supports admin-session.ts by holding or executing the clear admin session storage page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const clearAdminSessionStorage = () => {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
localStorage.removeItem('userPermissions')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
sessionStorage.removeItem('adminRefreshToken')
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyAdminTablePaginationChange, createAdminPagination } from './admin-table'
|
||||
|
||||
describe('admin-table', () => {
|
||||
it('creates default pagination state', () => {
|
||||
expect(createAdminPagination().current).toBe(1)
|
||||
expect(createAdminPagination().pageSize).toBe(10)
|
||||
})
|
||||
|
||||
it('applies pagination changes', () => {
|
||||
const pagination = createAdminPagination()
|
||||
const nextPagination = applyAdminTablePaginationChange(pagination, { current: 3, pageSize: 20 })
|
||||
expect(nextPagination.current).toBe(3)
|
||||
expect(nextPagination.pageSize).toBe(20)
|
||||
expect(pagination.current).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
export interface AdminPaginationState {
|
||||
current: number
|
||||
pageSize: number
|
||||
total: number
|
||||
showSizeChanger: boolean
|
||||
showQuickJumper: boolean
|
||||
showTotal: (total: number) => string
|
||||
}
|
||||
|
||||
export interface AdminTablePaginationChange {
|
||||
current?: number
|
||||
pageSize?: number
|
||||
}
|
||||
|
||||
export interface AdminPaginationPageChange {
|
||||
current: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export const createAdminPagination = (): AdminPaginationState => ({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
showTotal: (total: number) => `共 ${total} 条`
|
||||
})
|
||||
|
||||
export const applyAdminTablePaginationChange = (
|
||||
pagination: AdminPaginationState,
|
||||
change: AdminTablePaginationChange
|
||||
): AdminPaginationPageChange => ({
|
||||
current: change.current || pagination.current,
|
||||
pageSize: change.pageSize || pagination.pageSize
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getUploadResponse, resolveUploadedFileId } from './admin-upload-file'
|
||||
|
||||
describe('admin-upload-file', () => {
|
||||
it('resolves uploaded file id from response or file shape', () => {
|
||||
expect(resolveUploadedFileId({ response: { id: 7 } })).toBe('7')
|
||||
expect(resolveUploadedFileId({ fileId: '8' })).toBe('8')
|
||||
expect(resolveUploadedFileId({ uid: '9' })).toBe('9')
|
||||
expect(getUploadResponse(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
export interface AdminUploadResponseData {
|
||||
id?: string | number
|
||||
fileId?: string | number
|
||||
}
|
||||
|
||||
export interface AdminUploadResponse {
|
||||
id?: string | number
|
||||
fileId?: string | number
|
||||
data?: AdminUploadResponseData
|
||||
}
|
||||
|
||||
export interface AdminUploadFileLike {
|
||||
uid?: string | number
|
||||
url?: string
|
||||
thumbUrl?: string
|
||||
fileId?: string | number
|
||||
response?: AdminUploadResponse
|
||||
}
|
||||
|
||||
export interface AdminUploadTaskFile extends File {
|
||||
uid: string
|
||||
}
|
||||
|
||||
export const getUploadResponse = (file: AdminUploadFileLike | null | undefined): AdminUploadResponse | null => {
|
||||
if (!file || typeof file !== 'object') {
|
||||
return null
|
||||
}
|
||||
return file.response || null
|
||||
}
|
||||
|
||||
export const resolveUploadedFileId = (file: AdminUploadFileLike | null | undefined): string => {
|
||||
const response = getUploadResponse(file)
|
||||
const responseId = response?.id ?? response?.data?.id ?? response?.fileId ?? response?.data?.fileId ?? file?.fileId
|
||||
if (responseId !== undefined && responseId !== null && responseId !== '') {
|
||||
return String(responseId)
|
||||
}
|
||||
|
||||
const fileUid = String(file?.uid || '')
|
||||
if (/^\d+$/.test(fileUid)) {
|
||||
return fileUid
|
||||
}
|
||||
|
||||
const fileUrl = String(file?.url || '')
|
||||
if (/^\d+$/.test(fileUrl)) {
|
||||
return fileUrl
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { BUY_NOW_MODE, getBuyNowProductIdFromQuery, isBuyNowCartItem } from './buy-now'
|
||||
|
||||
describe('buy-now checkout mode', () => {
|
||||
it('reads the target product id only when cart query is in buyNow mode', () => {
|
||||
expect(getBuyNowProductIdFromQuery({ mode: BUY_NOW_MODE, productId: '1001' })).toBe('1001')
|
||||
expect(getBuyNowProductIdFromQuery({ mode: 'cart', productId: '1001' })).toBe('')
|
||||
})
|
||||
|
||||
it('uses the first query value when vue-router provides array values', () => {
|
||||
expect(getBuyNowProductIdFromQuery({ mode: [BUY_NOW_MODE], productId: ['2002', '3003'] })).toBe('2002')
|
||||
})
|
||||
|
||||
it('matches numeric and string product ids for cart selection', () => {
|
||||
expect(isBuyNowCartItem(1001, '1001')).toBe(true)
|
||||
expect(isBuyNowCartItem('1002', '1001')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
export const BUY_NOW_MODE = 'buyNow'
|
||||
|
||||
type QueryValue = string | string[] | null | undefined
|
||||
|
||||
const firstQueryValue = (value: QueryValue) => Array.isArray(value) ? value[0] : value
|
||||
|
||||
export const getBuyNowProductIdFromQuery = (query: Record<string, unknown>) => {
|
||||
const mode = firstQueryValue(query.mode as QueryValue)
|
||||
const productId = firstQueryValue(query.productId as QueryValue)
|
||||
return mode === BUY_NOW_MODE && productId ? String(productId) : ''
|
||||
}
|
||||
|
||||
export const isBuyNowCartItem = (itemProductId: unknown, buyNowProductId: string) => {
|
||||
return Boolean(buyNowProductId) && String(itemProductId || '') === String(buyNowProductId)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { cartApi } from '@/api/cart'
|
||||
import { toOptionalIdString } from '@/utils/id'
|
||||
|
||||
/**
|
||||
* Purpose: fetchCartProductIdSet supports cart-state.ts by holding or executing the fetch cart product id set page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const fetchCartProductIdSet = async () => {
|
||||
try {
|
||||
const response = await cartApi.getCartList() as unknown as Array<{ productId?: string | number }>
|
||||
return new Set(
|
||||
(Array.isArray(response) ? response : [])
|
||||
.map(item => toOptionalIdString(item && item.productId))
|
||||
.filter((id): id is string => Boolean(id))
|
||||
)
|
||||
} catch (error) {
|
||||
return new Set<string>()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hasCartProduct supports cart-state.ts by holding or executing the has cart product page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const hasCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
|
||||
const normalizedId = toOptionalIdString(productId)
|
||||
return Boolean(normalizedId && cartProductIdSet.has(normalizedId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: withAddedCartProduct supports cart-state.ts by holding or executing the with added cart product page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const withAddedCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
|
||||
const next = new Set(cartProductIdSet || [])
|
||||
const normalizedId = toOptionalIdString(productId)
|
||||
if (normalizedId) {
|
||||
next.add(normalizedId)
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createChunkUploadTask, type ChunkUploadApi } from './chunk-upload'
|
||||
|
||||
const createFile = (size: number) => new File([new Uint8Array(size)], 'large.png', {
|
||||
type: 'image/png',
|
||||
lastModified: 1
|
||||
})
|
||||
|
||||
describe('chunk-upload', () => {
|
||||
it('uploads chunks with the requested concurrency', async () => {
|
||||
const releaseCallbacks: Array<() => void> = []
|
||||
let activeUploads = 0
|
||||
let maxActiveUploads = 0
|
||||
|
||||
const api: ChunkUploadApi<string> = {
|
||||
initUpload: vi.fn().mockResolvedValue({
|
||||
uploadId: 'upload-1',
|
||||
chunkSize: 2,
|
||||
totalChunks: 4,
|
||||
uploadedChunks: []
|
||||
}),
|
||||
uploadChunk: vi.fn((_payload, config) => {
|
||||
activeUploads += 1
|
||||
maxActiveUploads = Math.max(maxActiveUploads, activeUploads)
|
||||
config?.onUploadProgress?.({ loaded: 2, total: 2 } as never)
|
||||
return new Promise(resolve => {
|
||||
releaseCallbacks.push(() => {
|
||||
activeUploads -= 1
|
||||
resolve(true)
|
||||
})
|
||||
})
|
||||
}),
|
||||
completeUpload: vi.fn().mockResolvedValue('done'),
|
||||
cancelUpload: vi.fn()
|
||||
}
|
||||
|
||||
const task = createChunkUploadTask({
|
||||
file: createFile(8),
|
||||
scene: 'test-image',
|
||||
concurrency: 3,
|
||||
api
|
||||
})
|
||||
|
||||
await vi.waitFor(() => expect(maxActiveUploads).toBe(3))
|
||||
while (releaseCallbacks.length) {
|
||||
releaseCallbacks.shift()?.()
|
||||
await Promise.resolve()
|
||||
}
|
||||
|
||||
await expect(task.promise).resolves.toMatchObject({
|
||||
response: 'done',
|
||||
uploadId: 'upload-1'
|
||||
})
|
||||
expect(api.uploadChunk).toHaveBeenCalledTimes(4)
|
||||
expect(api.completeUpload).toHaveBeenCalledWith('upload-1')
|
||||
})
|
||||
|
||||
it('skips already uploaded chunks', async () => {
|
||||
const api: ChunkUploadApi<string> = {
|
||||
initUpload: vi.fn().mockResolvedValue({
|
||||
uploadId: 'upload-2',
|
||||
chunkSize: 2,
|
||||
totalChunks: 3,
|
||||
uploadedChunks: [0, 2]
|
||||
}),
|
||||
uploadChunk: vi.fn().mockResolvedValue(true),
|
||||
completeUpload: vi.fn().mockResolvedValue('done')
|
||||
}
|
||||
|
||||
const task = createChunkUploadTask({
|
||||
file: createFile(6),
|
||||
scene: 'test-image',
|
||||
concurrency: 3,
|
||||
api
|
||||
})
|
||||
|
||||
await expect(task.promise).resolves.toMatchObject({ response: 'done' })
|
||||
expect(api.uploadChunk).toHaveBeenCalledTimes(1)
|
||||
expect(api.uploadChunk).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ chunkIndex: 1 }),
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { AxiosProgressEvent } from 'axios'
|
||||
|
||||
export interface ChunkUploadSession {
|
||||
uploadId: string
|
||||
chunkSize: number
|
||||
totalChunks: number
|
||||
uploadedChunks: number[]
|
||||
}
|
||||
|
||||
export interface ChunkUploadInitRequest {
|
||||
fileName: string
|
||||
fileSize: number
|
||||
contentType: string
|
||||
fileFingerprint: string
|
||||
scene: string
|
||||
}
|
||||
|
||||
export interface ChunkUploadApi<TResponse> {
|
||||
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
|
||||
uploadChunk: (
|
||||
payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
|
||||
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
|
||||
) => Promise<unknown>
|
||||
completeUpload: (uploadId: string) => Promise<TResponse>
|
||||
cancelUpload?: (uploadId: string) => Promise<unknown>
|
||||
}
|
||||
|
||||
export interface ChunkUploadOptions<TResponse> {
|
||||
file: File
|
||||
scene: string
|
||||
api: ChunkUploadApi<TResponse>
|
||||
concurrency: number
|
||||
preprocessFile?: (file: File) => Promise<File>
|
||||
onProgress?: (percent: number) => void
|
||||
}
|
||||
|
||||
export interface ChunkUploadResult<TResponse> {
|
||||
response: TResponse
|
||||
uploadId: string
|
||||
processedFile: File
|
||||
}
|
||||
|
||||
export interface ChunkUploadTask<TResponse> {
|
||||
promise: Promise<ChunkUploadResult<TResponse>>
|
||||
cancel: () => void
|
||||
getUploadId: () => string
|
||||
}
|
||||
|
||||
const computeFileFingerprint = async (file: File) => {
|
||||
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
|
||||
if (!window.crypto?.subtle) {
|
||||
return btoa(unescape(encodeURIComponent(fingerprintSeed)))
|
||||
}
|
||||
const buffer = new TextEncoder().encode(fingerprintSeed)
|
||||
const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
|
||||
const start = chunkIndex * chunkSize
|
||||
const end = Math.min(start + chunkSize, fileSize)
|
||||
return Math.max(end - start, 0)
|
||||
}
|
||||
|
||||
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) =>
|
||||
uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
|
||||
|
||||
const normalizeConcurrency = (concurrency: number) => {
|
||||
if (!Number.isFinite(concurrency) || concurrency < 1) {
|
||||
return 1
|
||||
}
|
||||
return Math.floor(concurrency)
|
||||
}
|
||||
|
||||
const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set<number>) => {
|
||||
const chunkIndexes: number[] = []
|
||||
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
|
||||
if (!uploadedChunkSet.has(chunkIndex)) {
|
||||
chunkIndexes.push(chunkIndex)
|
||||
}
|
||||
}
|
||||
return chunkIndexes
|
||||
}
|
||||
|
||||
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
|
||||
const abortController = new AbortController()
|
||||
let uploadId = ''
|
||||
let cancelled = false
|
||||
|
||||
const cleanupCancelledSession = async () => {
|
||||
if (uploadId && options.api.cancelUpload) {
|
||||
await options.api.cancelUpload(uploadId).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const promise = (async () => {
|
||||
const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file
|
||||
const fileFingerprint = await computeFileFingerprint(processedFile)
|
||||
const session = await options.api.initUpload({
|
||||
fileName: processedFile.name,
|
||||
fileSize: processedFile.size,
|
||||
contentType: processedFile.type || 'application/octet-stream',
|
||||
fileFingerprint,
|
||||
scene: options.scene
|
||||
})
|
||||
|
||||
uploadId = session.uploadId
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const uploadedChunkSet = new Set(session.uploadedChunks || [])
|
||||
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
|
||||
const uploadingChunkBytes = new Map<number, number>()
|
||||
const pendingChunkIndexes = createPendingChunkIndexes(session.totalChunks, uploadedChunkSet)
|
||||
const concurrency = Math.min(normalizeConcurrency(options.concurrency), Math.max(pendingChunkIndexes.length, 1))
|
||||
|
||||
const emitProgress = (limit: number) => {
|
||||
const inFlightBytes = Array.from(uploadingChunkBytes.values()).reduce((total, loaded) => total + loaded, 0)
|
||||
const percent = ((uploadedBytes + inFlightBytes) / Math.max(processedFile.size, 1)) * 100
|
||||
options.onProgress?.(Math.min(percent, limit))
|
||||
}
|
||||
|
||||
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
|
||||
|
||||
let nextChunkIndexCursor = 0
|
||||
const uploadNextChunk = async (): Promise<void> => {
|
||||
const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor]
|
||||
nextChunkIndexCursor += 1
|
||||
if (chunkIndex === undefined) {
|
||||
return
|
||||
}
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const start = chunkIndex * session.chunkSize
|
||||
const end = Math.min(start + session.chunkSize, processedFile.size)
|
||||
const chunk = processedFile.slice(start, end)
|
||||
const chunkBytes = end - start
|
||||
|
||||
await options.api.uploadChunk(
|
||||
{
|
||||
uploadId: session.uploadId,
|
||||
chunkIndex,
|
||||
totalChunks: session.totalChunks,
|
||||
chunk
|
||||
},
|
||||
{
|
||||
signal: abortController.signal,
|
||||
onUploadProgress: (event) => {
|
||||
const loaded = Math.min(event.loaded || 0, chunkBytes)
|
||||
uploadingChunkBytes.set(chunkIndex, loaded)
|
||||
emitProgress(99.9)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
uploadedChunkSet.add(chunkIndex)
|
||||
uploadedBytes += chunkBytes
|
||||
uploadingChunkBytes.delete(chunkIndex)
|
||||
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
|
||||
|
||||
await uploadNextChunk()
|
||||
}
|
||||
|
||||
await Promise.all(Array.from({ length: concurrency }, () => uploadNextChunk()))
|
||||
|
||||
if (cancelled) {
|
||||
await cleanupCancelledSession()
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
const response = await options.api.completeUpload(session.uploadId)
|
||||
options.onProgress?.(100)
|
||||
return {
|
||||
response,
|
||||
uploadId: session.uploadId,
|
||||
processedFile
|
||||
}
|
||||
})()
|
||||
|
||||
return {
|
||||
promise,
|
||||
cancel: () => {
|
||||
cancelled = true
|
||||
abortController.abort()
|
||||
if (uploadId && options.api.cancelUpload) {
|
||||
void options.api.cancelUpload(uploadId).catch(() => undefined)
|
||||
}
|
||||
},
|
||||
getUploadId: () => uploadId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildRatingStars, normalizeCommentRating } from './comment-review'
|
||||
|
||||
describe('comment review helpers', () => {
|
||||
it('normalizes comment ratings for display and submit', () => {
|
||||
expect(normalizeCommentRating(undefined)).toBe(5)
|
||||
expect(normalizeCommentRating(0)).toBe(1)
|
||||
expect(normalizeCommentRating(6)).toBe(5)
|
||||
expect(normalizeCommentRating('3')).toBe(3)
|
||||
})
|
||||
|
||||
it('builds filled and empty star states from a rating', () => {
|
||||
expect(buildRatingStars(3)).toEqual([true, true, true, false, false])
|
||||
expect(buildRatingStars(5)).toEqual([true, true, true, true, true])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
export const normalizeCommentRating = (value: unknown, fallback = 5) => {
|
||||
const numeric = Number(value ?? fallback)
|
||||
if (!Number.isFinite(numeric)) {
|
||||
return fallback
|
||||
}
|
||||
return Math.min(5, Math.max(1, Math.round(numeric)))
|
||||
}
|
||||
|
||||
export const buildRatingStars = (rating: unknown) => {
|
||||
const normalized = normalizeCommentRating(rating)
|
||||
return Array.from({ length: 5 }, (_, index) => index < normalized)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Purpose: DraftStorageMode supports form-draft.ts by holding or executing the draft storage mode page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export type DraftStorageMode = 'local' | 'session'
|
||||
|
||||
/**
|
||||
* Purpose: DraftRecord supports form-draft.ts by holding or executing the draft record page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface DraftRecord<T> {
|
||||
savedAt: number
|
||||
payload: T
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getStorage supports form-draft.ts by holding or executing the get storage page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage)
|
||||
|
||||
/**
|
||||
* Purpose: buildDraftStorageKey supports form-draft.ts by holding or executing the build draft storage key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const buildDraftStorageKey = (...parts: Array<string | number | undefined | null>) => {
|
||||
const normalizedParts = parts
|
||||
.filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0)
|
||||
.map(part => String(part).trim())
|
||||
return `jayucloud:draft:${normalizedParts.join(':')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: saveDraftRecord supports form-draft.ts by holding or executing the save draft record page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const saveDraftRecord = <T>(key: string, payload: T, mode: DraftStorageMode = 'local') => {
|
||||
const record: DraftRecord<T> = {
|
||||
savedAt: Date.now(),
|
||||
payload
|
||||
}
|
||||
getStorage(mode).setItem(key, JSON.stringify(record))
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: loadDraftRecord supports form-draft.ts by holding or executing the load draft record page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const loadDraftRecord = <T>(key: string, mode: DraftStorageMode = 'local') => {
|
||||
const rawValue = getStorage(mode).getItem(key)
|
||||
if (!rawValue) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(rawValue) as DraftRecord<T>
|
||||
} catch {
|
||||
getStorage(mode).removeItem(key)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: clearDraftRecord supports form-draft.ts by holding or executing the clear draft record page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => {
|
||||
getStorage(mode).removeItem(key)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Purpose: IdType supports id.ts by holding or executing the id type page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export type IdType = string | number
|
||||
|
||||
/**
|
||||
* Purpose: isEmptyId supports id.ts by holding or executing the is empty id page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isEmptyId = (value: unknown): value is undefined | null | '' => {
|
||||
return value === undefined || value === null || `${value}`.trim() === ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toIdString supports id.ts by holding or executing the to id string page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const toIdString = (value: IdType) => String(value)
|
||||
|
||||
// 前端统一把雪花 ID 视为字符串语义处理,避免任何 Number 转换带来的精度污染。
|
||||
export const toOptionalIdString = (value: unknown) => {
|
||||
if (isEmptyId(value)) {
|
||||
return undefined
|
||||
}
|
||||
return String(value).trim()
|
||||
}
|
||||
|
||||
// 比较 ID 时统一做字符串归一化,兼容接口返回 string / number 两种情况。
|
||||
export const sameId = (left: unknown, right: unknown) => {
|
||||
const leftId = toOptionalIdString(left)
|
||||
const rightId = toOptionalIdString(right)
|
||||
return leftId !== undefined && leftId === rightId
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* Purpose: DEFAULT_MAX_IMAGE_SIZE supports image-upload.ts by holding or executing the default max image size page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
|
||||
/**
|
||||
* Purpose: AUTO_COMPRESS_TYPES supports image-upload.ts by holding or executing the auto compress types page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
|
||||
|
||||
/**
|
||||
* Purpose: inferImageMimeType supports image-upload.ts by holding or executing the infer image mime type page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const inferImageMimeType = (file: File) => {
|
||||
if (file.type) return file.type.toLowerCase()
|
||||
const name = file.name.toLowerCase().split(/[?#]/)[0] || ''
|
||||
if (name.endsWith('.jpg') || name.endsWith('.jpeg')) return 'image/jpeg'
|
||||
if (name.endsWith('.png')) return 'image/png'
|
||||
if (name.endsWith('.webp')) return 'image/webp'
|
||||
if (name.endsWith('.gif')) return 'image/gif'
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ImageCompressionResult supports image-upload.ts by holding or executing the image compression result page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ImageCompressionResult {
|
||||
file: File
|
||||
originalSize: number
|
||||
finalSize: number
|
||||
compressed: boolean
|
||||
converted: boolean
|
||||
skippedReason?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: QUALITY_STEPS supports image-upload.ts by holding or executing the quality steps page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
|
||||
/**
|
||||
* Purpose: SCALE_STEPS supports image-upload.ts by holding or executing the scale steps page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
|
||||
|
||||
/**
|
||||
* Purpose: loadImageElement supports image-upload.ts by holding or executing the load image element page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const loadImageElement = (file: File) => {
|
||||
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const image = new Image()
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
|
||||
image.onload = () => {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
resolve(image)
|
||||
}
|
||||
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
reject(new Error('图片读取失败'))
|
||||
}
|
||||
|
||||
image.src = objectUrl
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: canvasToBlob supports image-upload.ts by holding or executing the canvas to blob page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => {
|
||||
return new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (!blob) {
|
||||
reject(new Error('图片压缩失败'))
|
||||
return
|
||||
}
|
||||
resolve(blob)
|
||||
},
|
||||
type,
|
||||
quality
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getOutputExtension supports image-upload.ts by holding or executing the get output extension page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getOutputExtension = (type: string) => {
|
||||
if (type === 'image/png') {
|
||||
return '.png'
|
||||
}
|
||||
if (type === 'image/webp') {
|
||||
return '.webp'
|
||||
}
|
||||
return '.jpg'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildOutputName supports image-upload.ts by holding or executing the build output name page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const buildOutputName = (fileName: string, type: string) => {
|
||||
const extension = getOutputExtension(type)
|
||||
const dotIndex = fileName.lastIndexOf('.')
|
||||
const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName
|
||||
return `${baseName}${extension}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: drawImageToCanvas supports image-upload.ts by holding or executing the draw image to canvas page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) {
|
||||
throw new Error('无法初始化图片压缩画布')
|
||||
}
|
||||
|
||||
if (mimeType !== 'image/png') {
|
||||
context.fillStyle = '#ffffff'
|
||||
context.fillRect(0, 0, width, height)
|
||||
}
|
||||
|
||||
context.drawImage(image, 0, 0, width, height)
|
||||
return canvas
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toCompressedFile supports image-upload.ts by holding or executing the to compressed file page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
|
||||
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
|
||||
type: mimeType,
|
||||
lastModified: sourceFile.lastModified
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getPreferredMimeTypes supports image-upload.ts by holding or executing the get preferred mime types page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const getPreferredMimeTypes = (file: File) => {
|
||||
if (file.type === 'image/png') {
|
||||
return ['image/png', 'image/jpeg']
|
||||
}
|
||||
if (file.type === 'image/webp') {
|
||||
return ['image/webp', 'image/jpeg']
|
||||
}
|
||||
return ['image/jpeg']
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: formatFileSize supports image-upload.ts by holding or executing the format file size page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const formatFileSize = (bytes: number) => {
|
||||
if (bytes >= 1024 * 1024) {
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
|
||||
}
|
||||
return `${(bytes / 1024).toFixed(0)}KB`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: compressImageIfNeeded supports image-upload.ts by holding or executing the compress image if needed page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const compressImageIfNeeded = async (
|
||||
file: File,
|
||||
maxSize = DEFAULT_MAX_IMAGE_SIZE
|
||||
): Promise<ImageCompressionResult> => {
|
||||
const sourceType = inferImageMimeType(file)
|
||||
if (!sourceType.startsWith('image/')) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false,
|
||||
skippedReason: '仅支持图片文件上传'
|
||||
}
|
||||
}
|
||||
|
||||
if (file.size <= maxSize) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false
|
||||
}
|
||||
}
|
||||
|
||||
if (!AUTO_COMPRESS_TYPES.has(sourceType)) {
|
||||
return {
|
||||
file,
|
||||
originalSize: file.size,
|
||||
finalSize: file.size,
|
||||
compressed: false,
|
||||
converted: false,
|
||||
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
|
||||
}
|
||||
}
|
||||
|
||||
const image = await loadImageElement(file)
|
||||
const preferredMimeTypes = getPreferredMimeTypes(new File([file], file.name, { type: sourceType || file.type }))
|
||||
let bestBlob: Blob | null = null
|
||||
let bestMimeType = sourceType || file.type
|
||||
|
||||
for (const scale of SCALE_STEPS) {
|
||||
const width = Math.max(1, Math.round(image.naturalWidth * scale))
|
||||
const height = Math.max(1, Math.round(image.naturalHeight * scale))
|
||||
|
||||
for (const mimeType of preferredMimeTypes) {
|
||||
const canvas = drawImageToCanvas(image, width, height, mimeType)
|
||||
const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS
|
||||
|
||||
for (const quality of qualitySteps) {
|
||||
const blob = await canvasToBlob(canvas, mimeType, quality)
|
||||
|
||||
if (!bestBlob || blob.size < bestBlob.size) {
|
||||
bestBlob = blob
|
||||
bestMimeType = mimeType
|
||||
}
|
||||
|
||||
if (blob.size <= maxSize) {
|
||||
const compressedFile = toCompressedFile(blob, file, mimeType)
|
||||
return {
|
||||
file: compressedFile,
|
||||
originalSize: file.size,
|
||||
finalSize: blob.size,
|
||||
compressed: true,
|
||||
converted: mimeType !== file.type
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestBlob) {
|
||||
throw new Error('图片压缩失败')
|
||||
}
|
||||
|
||||
const compressedFile = toCompressedFile(bestBlob, file, bestMimeType)
|
||||
return {
|
||||
file: compressedFile,
|
||||
originalSize: file.size,
|
||||
finalSize: bestBlob.size,
|
||||
compressed: true,
|
||||
converted: bestMimeType !== file.type
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: MAX_IMAGE_UPLOAD_SIZE supports image-upload.ts by holding or executing the max image upload size page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveOrderReviewFocus } from './order-review-focus'
|
||||
|
||||
const orders = [
|
||||
{
|
||||
id: 10,
|
||||
items: [
|
||||
{ id: 1001, productTitle: '猫眼款' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 11,
|
||||
items: [
|
||||
{ id: 1101, productTitle: '法式款' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
describe('resolveOrderReviewFocus', () => {
|
||||
it('focuses the exact pending review from message query parameters', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [{ id: 99, orderId: 10, orderItemId: 1001 }],
|
||||
orderReviews: {},
|
||||
query: { reviewId: 99 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('pending')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.focusOrderItemId).toBe('1001')
|
||||
expect(result.focusReviewId).toBe('99')
|
||||
})
|
||||
|
||||
it('reports a friendly submitted state when the reminder was already handled', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [],
|
||||
orderReviews: {
|
||||
10: [{ id: 99, orderId: 10, orderItemId: 1001, status: 1 }]
|
||||
},
|
||||
query: { reviewId: 99 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('submitted')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.focusOrderItemId).toBe('1001')
|
||||
expect(result.message).toContain('已处理')
|
||||
})
|
||||
|
||||
it('chooses the first pending review for profile pending-review entry', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [{ id: 88, orderId: 11, orderItemId: 1101 }],
|
||||
orderReviews: {},
|
||||
query: { review: 'pending' }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('pending')
|
||||
expect(result.focusOrderId).toBe('11')
|
||||
expect(result.focusOrderItemId).toBe('1101')
|
||||
expect(result.focusReviewId).toBe('88')
|
||||
})
|
||||
|
||||
it('keeps an order-level focus when only orderId is provided', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [],
|
||||
orderReviews: {},
|
||||
query: { orderId: 10 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('order')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.focusOrderItemId).toBe('')
|
||||
})
|
||||
|
||||
it('keeps the order visible when a review id is stale but orderId still exists', () => {
|
||||
const result = resolveOrderReviewFocus({
|
||||
orders,
|
||||
pendingReviews: [],
|
||||
orderReviews: {},
|
||||
query: { orderId: 10, reviewId: 404 }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('missing')
|
||||
expect(result.focusOrderId).toBe('10')
|
||||
expect(result.message).toContain('失效')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { OrderArtistReviewVO } from '@/api/order'
|
||||
|
||||
type QueryValue = string | number | null | undefined | Array<string | number | null | undefined>
|
||||
|
||||
interface OrderLike {
|
||||
id?: unknown
|
||||
items?: Array<{ id?: unknown }>
|
||||
}
|
||||
|
||||
interface ResolveOrderReviewFocusOptions {
|
||||
orders: OrderLike[]
|
||||
pendingReviews: OrderArtistReviewVO[]
|
||||
orderReviews: Record<string, OrderArtistReviewVO[]>
|
||||
query: Record<string, QueryValue>
|
||||
}
|
||||
|
||||
export interface OrderReviewFocusResult {
|
||||
status: 'none' | 'pending' | 'submitted' | 'missing' | 'order'
|
||||
focusOrderId: string
|
||||
focusOrderItemId: string
|
||||
focusReviewId: string
|
||||
message: string
|
||||
}
|
||||
|
||||
const toText = (value: QueryValue | unknown) => {
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] === undefined || value[0] === null ? '' : String(value[0])
|
||||
}
|
||||
return value === undefined || value === null ? '' : String(value)
|
||||
}
|
||||
|
||||
const sameId = (left: unknown, right: unknown) => {
|
||||
const leftText = toText(left)
|
||||
const rightText = toText(right)
|
||||
return leftText !== '' && leftText === rightText
|
||||
}
|
||||
|
||||
const flattenSubmittedReviews = (orderReviews: Record<string, OrderArtistReviewVO[]>) => {
|
||||
return Object.values(orderReviews).flat().filter(review => Number(review.status) === 1 || Boolean(review.rating))
|
||||
}
|
||||
|
||||
const findOrder = (orders: OrderLike[], orderId: string) => {
|
||||
return orders.find(order => sameId(order.id, orderId))
|
||||
}
|
||||
|
||||
const buildResult = (
|
||||
status: OrderReviewFocusResult['status'],
|
||||
review?: OrderArtistReviewVO,
|
||||
fallbackOrderId = '',
|
||||
message = ''
|
||||
): OrderReviewFocusResult => ({
|
||||
status,
|
||||
focusOrderId: toText(review?.orderId) || fallbackOrderId,
|
||||
focusOrderItemId: toText(review?.orderItemId),
|
||||
focusReviewId: toText(review?.id),
|
||||
message
|
||||
})
|
||||
|
||||
export const resolveOrderReviewFocus = ({
|
||||
orders,
|
||||
pendingReviews,
|
||||
orderReviews,
|
||||
query
|
||||
}: ResolveOrderReviewFocusOptions): OrderReviewFocusResult => {
|
||||
const reviewId = toText(query.reviewId)
|
||||
const orderId = toText(query.orderId)
|
||||
const orderItemId = toText(query.orderItemId)
|
||||
const reviewMode = toText(query.review)
|
||||
const submittedReviews = flattenSubmittedReviews(orderReviews)
|
||||
|
||||
if (reviewId) {
|
||||
const pending = pendingReviews.find(review => sameId(review.id, reviewId))
|
||||
if (pending) {
|
||||
return buildResult('pending', pending, '', '已为你定位到待评价订单。')
|
||||
}
|
||||
const submitted = submittedReviews.find(review => sameId(review.id, reviewId))
|
||||
if (submitted) {
|
||||
return buildResult('submitted', submitted, '', '这条评价提醒已处理,可查看已评价内容。')
|
||||
}
|
||||
return {
|
||||
status: 'missing',
|
||||
focusOrderId: findOrder(orders, orderId) ? orderId : '',
|
||||
focusOrderItemId: orderItemId,
|
||||
focusReviewId: reviewId,
|
||||
message: '这条评价提醒已失效,可在订单页查看最新状态。'
|
||||
}
|
||||
}
|
||||
|
||||
if (reviewMode === 'pending') {
|
||||
const firstPending = pendingReviews[0]
|
||||
if (firstPending) {
|
||||
return buildResult('pending', firstPending, '', '已为你定位到待评价订单。')
|
||||
}
|
||||
return {
|
||||
status: 'missing',
|
||||
focusOrderId: '',
|
||||
focusOrderItemId: '',
|
||||
focusReviewId: '',
|
||||
message: '暂无待评价订单。'
|
||||
}
|
||||
}
|
||||
|
||||
if (orderId && findOrder(orders, orderId)) {
|
||||
return {
|
||||
status: 'order',
|
||||
focusOrderId: orderId,
|
||||
focusOrderItemId: orderItemId,
|
||||
focusReviewId: '',
|
||||
message: ''
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'none',
|
||||
focusOrderId: '',
|
||||
focusOrderItemId: '',
|
||||
focusReviewId: '',
|
||||
message: ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { permissionApi } from '@/api/permission'
|
||||
import { computed, ref } from 'vue'
|
||||
import { isBootstrapAdminUser, loadCachedAdminUserInfo } from '@/utils/admin-session'
|
||||
import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions'
|
||||
|
||||
/**
|
||||
* Purpose: USER_PERMISSIONS_STORAGE_KEY supports permission.ts by holding or executing the user permissions storage key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const USER_PERMISSIONS_STORAGE_KEY = 'userPermissions'
|
||||
|
||||
/**
|
||||
* Purpose: readPermissionsFromStorage supports permission.ts by holding or executing the read permissions from storage page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const readPermissionsFromStorage = () => {
|
||||
const raw = localStorage.getItem(USER_PERMISSIONS_STORAGE_KEY)
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
return Array.isArray(parsed) ? parsed.map(item => String(item)) : null
|
||||
} catch (error) {
|
||||
console.error('Failed to parse stored user permissions:', error)
|
||||
localStorage.removeItem(USER_PERMISSIONS_STORAGE_KEY)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: userPermissions supports permission.ts by holding or executing the user permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const userPermissions = ref<string[]>(readPermissionsFromStorage() || [])
|
||||
/**
|
||||
* Purpose: loadingPermissions supports permission.ts by holding or executing the loading permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const loadingPermissions = ref(false)
|
||||
|
||||
/**
|
||||
* Purpose: isPlatformAdminUser supports permission.ts by holding or executing the is platform admin user page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const isPlatformAdminUser = () => Number(loadCachedAdminUserInfo()?.type) === 4
|
||||
|
||||
/**
|
||||
* Purpose: getStoredUserPermissions supports permission.ts by holding or executing the get stored user permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const getStoredUserPermissions = () => readPermissionsFromStorage()
|
||||
|
||||
/**
|
||||
* Purpose: setStoredUserPermissions supports permission.ts by holding or executing the set stored user permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const setStoredUserPermissions = (permissions: string[]) => {
|
||||
userPermissions.value = Array.from(new Set((permissions || []).map(code => String(code))))
|
||||
localStorage.setItem(USER_PERMISSIONS_STORAGE_KEY, JSON.stringify(userPermissions.value))
|
||||
return userPermissions.value
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: clearStoredPermissions supports permission.ts by holding or executing the clear stored permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const clearStoredPermissions = () => {
|
||||
userPermissions.value = []
|
||||
localStorage.removeItem(USER_PERMISSIONS_STORAGE_KEY)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: fetchUserPermissionsStrict supports permission.ts by holding or executing the fetch user permissions strict page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const fetchUserPermissionsStrict = async () => {
|
||||
loadingPermissions.value = true
|
||||
try {
|
||||
const permissions = await permissionApi.getUserPermissions()
|
||||
const normalizedPermissions = permissions && Array.isArray(permissions)
|
||||
? permissions.map(permission => permission.permissionCode)
|
||||
: []
|
||||
|
||||
return setStoredUserPermissions(normalizedPermissions)
|
||||
} finally {
|
||||
loadingPermissions.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: usePermission supports permission.ts by holding or executing the use permission page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const usePermission = () => {
|
||||
const hasPermission = (permissionCode: string) => {
|
||||
if (isBootstrapAdminUser(loadCachedAdminUserInfo())) {
|
||||
return isAllowedForShoplessPlatformAdmin(permissionCode)
|
||||
}
|
||||
if (isPlatformAdminUser() && isAllowedForShoplessPlatformAdmin(permissionCode)) {
|
||||
return isAllowedForShoplessPlatformAdmin(permissionCode)
|
||||
}
|
||||
return userPermissions.value.includes(permissionCode)
|
||||
}
|
||||
|
||||
const hasAnyPermission = (permissionCodes: string[]) => {
|
||||
if (isBootstrapAdminUser(loadCachedAdminUserInfo())) {
|
||||
return permissionCodes.some(isAllowedForShoplessPlatformAdmin)
|
||||
}
|
||||
if (isPlatformAdminUser() && permissionCodes.some(isAllowedForShoplessPlatformAdmin)) {
|
||||
return permissionCodes.some(isAllowedForShoplessPlatformAdmin)
|
||||
}
|
||||
return permissionCodes.some(code => userPermissions.value.includes(code))
|
||||
}
|
||||
|
||||
const hasAllPermissions = (permissionCodes: string[]) => {
|
||||
if (isBootstrapAdminUser(loadCachedAdminUserInfo())) {
|
||||
return permissionCodes.every(isAllowedForShoplessPlatformAdmin)
|
||||
}
|
||||
if (isPlatformAdminUser() && permissionCodes.every(isAllowedForShoplessPlatformAdmin)) {
|
||||
return permissionCodes.every(isAllowedForShoplessPlatformAdmin)
|
||||
}
|
||||
return permissionCodes.every(code => userPermissions.value.includes(code))
|
||||
}
|
||||
|
||||
const loadUserPermissions = async () => {
|
||||
try {
|
||||
return await fetchUserPermissionsStrict()
|
||||
} catch (error) {
|
||||
console.error('加载用户权限失败:', error)
|
||||
clearStoredPermissions()
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const clearPermissions = () => {
|
||||
clearStoredPermissions()
|
||||
}
|
||||
|
||||
return {
|
||||
userPermissions: computed(() => userPermissions.value),
|
||||
loadingPermissions: computed(() => loadingPermissions.value),
|
||||
hasPermission,
|
||||
hasAnyPermission,
|
||||
hasAllPermissions,
|
||||
loadUserPermissions,
|
||||
clearPermissions
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Purpose: SHOPLESS_ADMIN_ALLOWED_PREFIXES supports platform-admin-permissions.ts by holding or executing the shopless admin allowed prefixes page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const SHOPLESS_ADMIN_ALLOWED_PREFIXES = ['user:', 'shop:', 'permission:', 'message:', 'announcement:']
|
||||
/**
|
||||
* Purpose: SHOPLESS_ADMIN_ALLOWED_PERMISSIONS supports platform-admin-permissions.ts by holding or executing the shopless admin allowed permissions page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const SHOPLESS_ADMIN_ALLOWED_PERMISSIONS = [
|
||||
'messagehub:config:manage',
|
||||
'security:audit:view',
|
||||
'legal_agreement:manage'
|
||||
]
|
||||
|
||||
/**
|
||||
* Purpose: isAllowedForShoplessPlatformAdmin supports platform-admin-permissions.ts by holding or executing the is allowed for shopless platform admin page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const isAllowedForShoplessPlatformAdmin = (permissionCode: string) =>
|
||||
permissionCode === 'dashboard:view'
|
||||
|| permissionCode.endsWith(':view')
|
||||
|| SHOPLESS_ADMIN_ALLOWED_PERMISSIONS.includes(permissionCode)
|
||||
|| SHOPLESS_ADMIN_ALLOWED_PREFIXES.some(prefix => permissionCode.startsWith(prefix))
|
||||
@@ -0,0 +1,69 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const publicGetSignedUrl = vi.fn()
|
||||
|
||||
vi.mock('@/api/file', () => ({
|
||||
fileApi: {
|
||||
getSignedUrl: publicGetSignedUrl
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/api/admin', () => ({
|
||||
adminFileApi: {
|
||||
getSignedUrl: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
describe('public-image-assets', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
publicGetSignedUrl.mockResolvedValue({ data: 'img.yunail.art/signed.jpg?token=1' })
|
||||
})
|
||||
|
||||
it('prefers direct image urls over signing file ids', async () => {
|
||||
const { resolvePublicImageUrls } = await import('./public-image-assets')
|
||||
|
||||
await expect(resolvePublicImageUrls({
|
||||
imageUrls: ['http://img.yunail.art/direct.jpg'],
|
||||
imageFileIds: '42'
|
||||
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg'])
|
||||
expect(publicGetSignedUrl).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('normalizes direct image urls without scheme', async () => {
|
||||
const { resolvePublicImageUrls } = await import('./public-image-assets')
|
||||
|
||||
await expect(resolvePublicImageUrls({
|
||||
imageUrls: ['img.yunail.art/direct.jpg?token=1']
|
||||
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg?token=1'])
|
||||
})
|
||||
|
||||
it('signs public file ids when direct urls are missing', async () => {
|
||||
const { resolvePublicImageUrls, resolvePublicImageUrlsSync } = await import('./public-image-assets')
|
||||
|
||||
expect(resolvePublicImageUrlsSync({ imageFileIds: '42' }, 'fallback.png')).toEqual(['fallback.png'])
|
||||
await expect(resolvePublicImageUrls({ imageFileIds: '42' }, 'fallback.png')).resolves.toEqual([
|
||||
'http://img.yunail.art/signed.jpg?token=1'
|
||||
])
|
||||
expect(publicGetSignedUrl).toHaveBeenCalledWith('42')
|
||||
})
|
||||
|
||||
it('extracts legacy file ids from old file urls', async () => {
|
||||
const { getDirectPublicImageUrls, getPublicImageFileIds } = await import('./public-image-assets')
|
||||
|
||||
const record = {
|
||||
imageUrl: '/api/file/get/325517232303947776',
|
||||
imageFileIds: '325517232303947776,325517220106911744'
|
||||
}
|
||||
|
||||
expect(getDirectPublicImageUrls(record)).toEqual([])
|
||||
expect(getPublicImageFileIds(record)).toEqual(['325517232303947776', '325517220106911744'])
|
||||
})
|
||||
|
||||
it('uses fallback when no image source is available', async () => {
|
||||
const { resolvePublicImageUrls } = await import('./public-image-assets')
|
||||
|
||||
await expect(resolvePublicImageUrls({}, 'fallback.png')).resolves.toEqual(['fallback.png'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import {
|
||||
extractLegacyFileId,
|
||||
getCachedSignedImageUrl,
|
||||
getCachedSignedImageUrlSync,
|
||||
parseImageFileIds,
|
||||
refreshCachedSignedImageUrl
|
||||
} from '@/utils/signed-image-cache'
|
||||
|
||||
export interface PublicImageRecord {
|
||||
imageUrls?: string[] | string | null
|
||||
imageFileIds?: string[] | string | null
|
||||
coverImageUrl?: string | null
|
||||
coverImageUrls?: string[] | string | null
|
||||
coverImageFileId?: string[] | string | null
|
||||
imageUrl?: string | null
|
||||
}
|
||||
|
||||
const normalizePublicUrl = (value: unknown): string => {
|
||||
const source = String(value || '').replace(/[`]/g, '').trim()
|
||||
if (!source) return ''
|
||||
if (/^\/?api\/file\/get\/\d+/i.test(source)) return ''
|
||||
if (/^(https?:)?\/\//i.test(source) || /^(data|blob):/i.test(source) || source.startsWith('/')) {
|
||||
return source.startsWith('//') ? `http:${source}` : source
|
||||
}
|
||||
if (source.includes('/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|#|$)/i.test(source)) {
|
||||
return `http://${source}`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const normalizeUrlList = (value: unknown): string[] => {
|
||||
const rawValues = Array.isArray(value) ? value : String(value || '').split(',')
|
||||
return Array.from(new Set(rawValues.map(normalizePublicUrl).filter(Boolean)))
|
||||
}
|
||||
|
||||
export const getPublicImageFileIds = (record: PublicImageRecord): string[] => {
|
||||
const rawFileIds = [
|
||||
...(Array.isArray(record.coverImageFileId) ? record.coverImageFileId : parseImageFileIds(String(record.coverImageFileId || ''))),
|
||||
...(Array.isArray(record.imageFileIds) ? record.imageFileIds : parseImageFileIds(String(record.imageFileIds || ''))),
|
||||
extractLegacyFileId(record.coverImageUrl),
|
||||
extractLegacyFileId(record.imageUrl)
|
||||
]
|
||||
return Array.from(new Set(rawFileIds.map(id => String(id || '').trim()).filter(Boolean)))
|
||||
}
|
||||
|
||||
export const getDirectPublicImageUrls = (record: PublicImageRecord): string[] => {
|
||||
return Array.from(new Set([
|
||||
...normalizeUrlList(record.coverImageUrls),
|
||||
...normalizeUrlList(record.coverImageUrl),
|
||||
...normalizeUrlList(record.imageUrls),
|
||||
...normalizeUrlList(record.imageUrl)
|
||||
]))
|
||||
}
|
||||
|
||||
export const resolvePublicImageUrlsSync = (
|
||||
record: PublicImageRecord,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): string[] => {
|
||||
const directUrls = getDirectPublicImageUrls(record)
|
||||
if (directUrls.length) return directUrls
|
||||
|
||||
const cachedUrls = getPublicImageFileIds(record)
|
||||
.map(fileId => getCachedSignedImageUrlSync(fileId, 'public'))
|
||||
.filter(Boolean)
|
||||
if (cachedUrls.length) return cachedUrls
|
||||
|
||||
return fallback ? [fallback] : []
|
||||
}
|
||||
|
||||
export const resolvePublicImageUrls = async (
|
||||
record: PublicImageRecord,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): Promise<string[]> => {
|
||||
const directUrls = getDirectPublicImageUrls(record)
|
||||
if (directUrls.length) return directUrls
|
||||
|
||||
const signedUrls = await Promise.all(getPublicImageFileIds(record).map(fileId => getCachedSignedImageUrl(fileId, '', 'public')))
|
||||
const usableUrls = signedUrls.filter(Boolean)
|
||||
if (usableUrls.length) return usableUrls
|
||||
|
||||
return fallback ? [fallback] : []
|
||||
}
|
||||
|
||||
export const resolvePublicImageUrl = async (
|
||||
record: PublicImageRecord,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): Promise<string> => {
|
||||
const urls = await resolvePublicImageUrls(record, fallback)
|
||||
return urls[0] || fallback
|
||||
}
|
||||
|
||||
export const refreshPublicImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback = DEFAULT_PRODUCT_IMAGE
|
||||
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'public')
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildRecoveryActions, getRecoveryMessage, recoveryRouteFor } from './recovery'
|
||||
|
||||
describe('recovery utils', () => {
|
||||
it('normalizes error messages with fallback text', () => {
|
||||
expect(getRecoveryMessage(new Error('网络开小差了'), '请求失败')).toBe('网络开小差了')
|
||||
expect(getRecoveryMessage('', '请求失败')).toBe('请求失败')
|
||||
})
|
||||
|
||||
it('adds default routes and primary action state', () => {
|
||||
const actions = buildRecoveryActions([
|
||||
{ key: 'retry', text: '重试' },
|
||||
{ key: 'orders', text: '查看订单' },
|
||||
{ key: 'cart', text: '返回购物车' }
|
||||
])
|
||||
const retryAction = actions[0]
|
||||
const ordersAction = actions[1]
|
||||
const cartAction = actions[2]
|
||||
|
||||
expect(retryAction?.primary).toBe(true)
|
||||
expect(ordersAction?.route).toBe('/orders')
|
||||
expect(cartAction?.route).toBe('/cart')
|
||||
expect(recoveryRouteFor('products')).toBe('/products')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
export type RecoveryActionKey = 'retry' | 'orders' | 'cart' | 'products' | 'profile' | 'contact'
|
||||
|
||||
export interface RecoveryAction {
|
||||
key: RecoveryActionKey
|
||||
text: string
|
||||
route?: string
|
||||
primary?: boolean
|
||||
}
|
||||
|
||||
const DEFAULT_ROUTES: Record<string, string> = {
|
||||
orders: '/orders',
|
||||
cart: '/cart',
|
||||
products: '/products',
|
||||
profile: '/profile'
|
||||
}
|
||||
|
||||
export const getRecoveryMessage = (error: unknown, fallbackMessage: string): string => {
|
||||
if (error instanceof Error && error.message.trim()) {
|
||||
return error.message.trim()
|
||||
}
|
||||
if (typeof error === 'string' && error.trim()) {
|
||||
return error.trim()
|
||||
}
|
||||
if (error && typeof error === 'object' && 'message' in error) {
|
||||
const message = String((error as { message?: unknown }).message || '').trim()
|
||||
if (message) {
|
||||
return message
|
||||
}
|
||||
}
|
||||
return fallbackMessage
|
||||
}
|
||||
|
||||
export const recoveryRouteFor = (key: RecoveryActionKey): string => DEFAULT_ROUTES[key] || ''
|
||||
|
||||
export const buildRecoveryActions = (actions: RecoveryAction[]): RecoveryAction[] => (
|
||||
actions
|
||||
.filter(action => action.key && action.text)
|
||||
.map((action, index) => ({
|
||||
...action,
|
||||
route: action.route || recoveryRouteFor(action.key),
|
||||
primary: action.primary ?? index === 0
|
||||
}))
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import type { InternalAxiosRequestConfig } from 'axios'
|
||||
import { createHash, createHmac } from 'node:crypto'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { attachRequestSignature } from './request-signature'
|
||||
|
||||
describe('request signature', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
it('falls back when Web Crypto subtle digest is unavailable', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
|
||||
vi.stubGlobal('crypto', {
|
||||
randomUUID: () => 'fallback-id'
|
||||
})
|
||||
|
||||
const config = {
|
||||
method: 'post',
|
||||
baseURL: '/api',
|
||||
url: '/order/checkout-preview',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
data: {
|
||||
items: []
|
||||
}
|
||||
} as unknown as InternalAxiosRequestConfig
|
||||
|
||||
await attachRequestSignature(config, 'access-token')
|
||||
|
||||
const headers = config.headers as Record<string, string>
|
||||
const payloadHash = createHash('sha256').update(JSON.stringify({ items: [] })).digest('hex')
|
||||
const canonical = [
|
||||
'POST',
|
||||
'/order/checkout-preview',
|
||||
'1700000000000',
|
||||
'1700000000000-fallback-id',
|
||||
payloadHash
|
||||
].join('\n')
|
||||
const expectedSignature = createHmac('sha256', 'access-token').update(canonical).digest('hex')
|
||||
|
||||
expect(headers['X-Timestamp']).toBe('1700000000000')
|
||||
expect(headers['X-Nonce']).toBe('1700000000000-fallback-id')
|
||||
expect(headers['X-Sign-Version']).toBe('v1')
|
||||
expect(headers['X-Signature']).toBe(expectedSignature)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,474 @@
|
||||
import type { InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
/**
|
||||
* Purpose: HEADER_TIMESTAMP supports request-signature.ts by holding or executing the header timestamp page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_TIMESTAMP = 'X-Timestamp'
|
||||
/**
|
||||
* Purpose: HEADER_NONCE supports request-signature.ts by holding or executing the header nonce page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_NONCE = 'X-Nonce'
|
||||
/**
|
||||
* Purpose: HEADER_SIGNATURE supports request-signature.ts by holding or executing the header signature page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_SIGNATURE = 'X-Signature'
|
||||
/**
|
||||
* Purpose: HEADER_SIGNATURE_VERSION supports request-signature.ts by holding or executing the header signature version page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
||||
/**
|
||||
* Purpose: DEVICE_ID_HEADER supports request-signature.ts by holding or executing the device id header page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEVICE_ID_HEADER = 'X-Device-Id'
|
||||
/**
|
||||
* Purpose: DEVICE_ID_STORAGE_KEY supports request-signature.ts by holding or executing the device id storage key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const DEVICE_ID_STORAGE_KEY = 'jayucloud-device-id'
|
||||
/**
|
||||
* Purpose: SIGNATURE_VERSION supports request-signature.ts by holding or executing the signature version page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const SIGNATURE_VERSION = 'v1'
|
||||
|
||||
/**
|
||||
* Purpose: HeaderContainer supports request-signature.ts by holding or executing the header container page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
type HeaderContainer = Record<string, unknown> & {
|
||||
set?: (name: string, value: string) => void
|
||||
get?: (name: string) => unknown
|
||||
}
|
||||
|
||||
const SHA256_K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
])
|
||||
|
||||
/**
|
||||
* Purpose: RequestSignatureOptions supports request-signature.ts by holding or executing the request signature options page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
interface RequestSignatureOptions {
|
||||
authFree?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isSafeMethod supports request-signature.ts by holding or executing the is safe method page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function isSafeMethod(method?: string) {
|
||||
return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase())
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toHex supports request-signature.ts by holding or executing the to hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function toHex(bytes: ArrayBuffer | Uint8Array) {
|
||||
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
|
||||
return Array.from(view)
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
|
||||
function encodeUtf8(text: string) {
|
||||
return new TextEncoder().encode(text)
|
||||
}
|
||||
|
||||
function rightRotate(value: number, bits: number) {
|
||||
return (value >>> bits) | (value << (32 - bits))
|
||||
}
|
||||
|
||||
function concatBytes(left: Uint8Array, right: Uint8Array) {
|
||||
const result = new Uint8Array(left.length + right.length)
|
||||
result.set(left, 0)
|
||||
result.set(right, left.length)
|
||||
return result
|
||||
}
|
||||
|
||||
function sha256Bytes(input: Uint8Array) {
|
||||
const paddedLength = Math.ceil((input.length + 9) / 64) * 64
|
||||
const padded = new Uint8Array(paddedLength)
|
||||
padded.set(input)
|
||||
padded[input.length] = 0x80
|
||||
|
||||
const bitLength = input.length * 8
|
||||
const view = new DataView(padded.buffer)
|
||||
view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false)
|
||||
view.setUint32(paddedLength - 4, bitLength >>> 0, false)
|
||||
|
||||
let h0 = 0x6a09e667
|
||||
let h1 = 0xbb67ae85
|
||||
let h2 = 0x3c6ef372
|
||||
let h3 = 0xa54ff53a
|
||||
let h4 = 0x510e527f
|
||||
let h5 = 0x9b05688c
|
||||
let h6 = 0x1f83d9ab
|
||||
let h7 = 0x5be0cd19
|
||||
const words = new Uint32Array(64)
|
||||
|
||||
for (let offset = 0; offset < paddedLength; offset += 64) {
|
||||
for (let index = 0; index < 16; index++) {
|
||||
words[index] = view.getUint32(offset + index * 4, false)
|
||||
}
|
||||
for (let index = 16; index < 64; index++) {
|
||||
const word15 = words[index - 15]!
|
||||
const word2 = words[index - 2]!
|
||||
const s0 = rightRotate(word15, 7) ^ rightRotate(word15, 18) ^ (word15 >>> 3)
|
||||
const s1 = rightRotate(word2, 17) ^ rightRotate(word2, 19) ^ (word2 >>> 10)
|
||||
words[index] = (words[index - 16]! + s0 + words[index - 7]! + s1) >>> 0
|
||||
}
|
||||
|
||||
let a = h0
|
||||
let b = h1
|
||||
let c = h2
|
||||
let d = h3
|
||||
let e = h4
|
||||
let f = h5
|
||||
let g = h6
|
||||
let h = h7
|
||||
|
||||
for (let index = 0; index < 64; index++) {
|
||||
const s1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)
|
||||
const ch = (e & f) ^ (~e & g)
|
||||
const temp1 = (h + s1 + ch + SHA256_K[index]! + words[index]!) >>> 0
|
||||
const s0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)
|
||||
const maj = (a & b) ^ (a & c) ^ (b & c)
|
||||
const temp2 = (s0 + maj) >>> 0
|
||||
h = g
|
||||
g = f
|
||||
f = e
|
||||
e = (d + temp1) >>> 0
|
||||
d = c
|
||||
c = b
|
||||
b = a
|
||||
a = (temp1 + temp2) >>> 0
|
||||
}
|
||||
|
||||
h0 = (h0 + a) >>> 0
|
||||
h1 = (h1 + b) >>> 0
|
||||
h2 = (h2 + c) >>> 0
|
||||
h3 = (h3 + d) >>> 0
|
||||
h4 = (h4 + e) >>> 0
|
||||
h5 = (h5 + f) >>> 0
|
||||
h6 = (h6 + g) >>> 0
|
||||
h7 = (h7 + h) >>> 0
|
||||
}
|
||||
|
||||
const output = new Uint8Array(32)
|
||||
const outputView = new DataView(output.buffer)
|
||||
;[h0, h1, h2, h3, h4, h5, h6, h7].forEach((value, index) => {
|
||||
outputView.setUint32(index * 4, value, false)
|
||||
})
|
||||
return output
|
||||
}
|
||||
|
||||
function hmacSha256Bytes(secret: string, message: string) {
|
||||
const blockSize = 64
|
||||
let key = encodeUtf8(secret)
|
||||
if (key.length > blockSize) {
|
||||
key = sha256Bytes(key)
|
||||
}
|
||||
|
||||
const paddedKey = new Uint8Array(blockSize)
|
||||
paddedKey.set(key)
|
||||
const outer = new Uint8Array(blockSize)
|
||||
const inner = new Uint8Array(blockSize)
|
||||
for (let index = 0; index < blockSize; index++) {
|
||||
outer[index] = paddedKey[index]! ^ 0x5c
|
||||
inner[index] = paddedKey[index]! ^ 0x36
|
||||
}
|
||||
return sha256Bytes(concatBytes(outer, sha256Bytes(concatBytes(inner, encodeUtf8(message)))))
|
||||
}
|
||||
|
||||
function getSubtleCrypto() {
|
||||
return globalThis.crypto?.subtle
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sha256Hex supports request-signature.ts by holding or executing the sha256 hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function sha256Hex(text: string) {
|
||||
const subtle = getSubtleCrypto()
|
||||
if (!subtle) {
|
||||
return toHex(sha256Bytes(encodeUtf8(text)))
|
||||
}
|
||||
const digest = await subtle.digest('SHA-256', encodeUtf8(text))
|
||||
return toHex(digest)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hmacSha256Hex supports request-signature.ts by holding or executing the hmac sha256 hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
async function hmacSha256Hex(secret: string, message: string) {
|
||||
const subtle = getSubtleCrypto()
|
||||
if (!subtle) {
|
||||
return toHex(hmacSha256Bytes(secret, message))
|
||||
}
|
||||
const key = await subtle.importKey(
|
||||
'raw',
|
||||
encodeUtf8(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const signature = await subtle.sign('HMAC', key, encodeUtf8(message))
|
||||
return toHex(signature)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: randomNonce supports request-signature.ts by holding or executing the random nonce page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function randomNonce() {
|
||||
if (typeof globalThis.crypto?.randomUUID === 'function') {
|
||||
return `${Date.now()}-${globalThis.crypto.randomUUID()}`
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getDeviceId supports request-signature.ts by holding or executing the get device id page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function getDeviceId() {
|
||||
try {
|
||||
const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY)
|
||||
if (stored) {
|
||||
return stored
|
||||
}
|
||||
const next = `web-${randomNonce()}`
|
||||
localStorage.setItem(DEVICE_ID_STORAGE_KEY, next)
|
||||
return next
|
||||
} catch {
|
||||
return `web-${randomNonce()}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: setHeader supports request-signature.ts by holding or executing the set header page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function setHeader(config: InternalAxiosRequestConfig, name: string, value: string) {
|
||||
const headers = config.headers as HeaderContainer | undefined
|
||||
if (headers && typeof headers.set === 'function') {
|
||||
headers.set(name, value)
|
||||
return
|
||||
}
|
||||
config.headers = {
|
||||
...(headers || {}),
|
||||
[name]: value
|
||||
} as InternalAxiosRequestConfig['headers']
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: getHeader supports request-signature.ts by holding or executing the get header page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function getHeader(config: InternalAxiosRequestConfig, name: string) {
|
||||
const headers = config.headers as HeaderContainer | undefined
|
||||
if (!headers) {
|
||||
return ''
|
||||
}
|
||||
if (typeof headers.get === 'function') {
|
||||
const value = headers.get(name)
|
||||
if (value !== undefined && value !== null) {
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
return String(headers[name] || headers[name.toLowerCase()] || '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: extractPath supports request-signature.ts by holding or executing the extract path page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function extractPath(value?: string) {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
try {
|
||||
return new URL(value, window.location.origin).pathname
|
||||
} catch {
|
||||
return value.split('?')[0] || ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: joinAxiosPath supports request-signature.ts by holding or executing the join axios path page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function joinAxiosPath(baseUrl?: string, requestUrl?: string) {
|
||||
if (requestUrl && /^[a-z][a-z\d+\-.]*:\/\//i.test(requestUrl)) {
|
||||
return extractPath(requestUrl)
|
||||
}
|
||||
|
||||
const basePath = extractPath(baseUrl).replace(/^\/+|\/+$/g, '')
|
||||
const requestPath = extractPath(requestUrl).replace(/^\/+|\/+$/g, '')
|
||||
const joined = [basePath, requestPath].filter(Boolean).join('/')
|
||||
return joined ? `/${joined}` : '/'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toBackendRequestPath supports request-signature.ts by holding or executing the to backend request path page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function toBackendRequestPath(baseUrl?: string, requestUrl?: string) {
|
||||
const path = joinAxiosPath(baseUrl, requestUrl)
|
||||
if (path === '/admin/api') {
|
||||
return '/admin'
|
||||
}
|
||||
if (path.startsWith('/admin/api/')) {
|
||||
return `/admin/${path.slice('/admin/api/'.length)}`
|
||||
}
|
||||
if (path === '/api/admin') {
|
||||
return '/admin'
|
||||
}
|
||||
if (path.startsWith('/api/admin/')) {
|
||||
return `/admin/${path.slice('/api/admin/'.length)}`
|
||||
}
|
||||
if (path === '/api') {
|
||||
return '/'
|
||||
}
|
||||
if (path.startsWith('/api/')) {
|
||||
return `/${path.slice('/api/'.length)}`
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: appendParam supports request-signature.ts by holding or executing the append param page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function appendParam(target: Record<string, unknown[]>, key: string, value: unknown) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return
|
||||
}
|
||||
if (!target[key]) {
|
||||
target[key] = []
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(item => appendParam(target, key, item))
|
||||
return
|
||||
}
|
||||
target[key].push(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: collectParams supports request-signature.ts by holding or executing the collect params page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function collectParams(source: unknown, target: Record<string, unknown[]>) {
|
||||
if (!source) {
|
||||
return
|
||||
}
|
||||
if (source instanceof URLSearchParams) {
|
||||
source.forEach((value, key) => appendParam(target, key, value))
|
||||
return
|
||||
}
|
||||
if (source instanceof FormData) {
|
||||
source.forEach((value, key) => {
|
||||
if (!(value instanceof Blob)) {
|
||||
appendParam(target, key, value)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
if (typeof source === 'object') {
|
||||
Object.entries(source as Record<string, unknown>).forEach(([key, value]) => appendParam(target, key, value))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildCanonicalParams supports request-signature.ts by holding or executing the build canonical params page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function buildCanonicalParams(...sources: unknown[]) {
|
||||
const params: Record<string, unknown[]> = {}
|
||||
sources.forEach(source => collectParams(source, params))
|
||||
return Object.keys(params)
|
||||
.sort()
|
||||
.map(key => {
|
||||
const normalized = params[key]
|
||||
?.map(value => String(value))
|
||||
.sort()
|
||||
.join(',') || ''
|
||||
return `${key}=${normalized}`
|
||||
})
|
||||
.join('&')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: buildJsonPayload supports request-signature.ts by holding or executing the build json payload page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function buildJsonPayload(data: unknown) {
|
||||
if (data === undefined || data === null || data === '') {
|
||||
return ''
|
||||
}
|
||||
if (typeof data === 'string') {
|
||||
return data
|
||||
}
|
||||
return JSON.stringify(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolvePayload supports request-signature.ts by holding or executing the resolve payload page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function resolvePayload(config: InternalAxiosRequestConfig) {
|
||||
const contentType = getHeader(config, 'Content-Type').toLowerCase()
|
||||
const jsonPayload = contentType.includes('application/json') ? buildJsonPayload(config.data) : ''
|
||||
if (jsonPayload) {
|
||||
return jsonPayload
|
||||
}
|
||||
return buildCanonicalParams(config.params, config.data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: attachRequestSignature supports request-signature.ts by holding or executing the attach request signature page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export async function attachRequestSignature(
|
||||
config: InternalAxiosRequestConfig,
|
||||
accessToken?: string | null,
|
||||
options: RequestSignatureOptions = {}
|
||||
) {
|
||||
setHeader(config, DEVICE_ID_HEADER, getDeviceId())
|
||||
|
||||
const method = String(config.method || 'GET').toUpperCase()
|
||||
if (!accessToken || options.authFree || isSafeMethod(method)) {
|
||||
return config
|
||||
}
|
||||
|
||||
const timestamp = String(Date.now())
|
||||
const nonce = randomNonce()
|
||||
const payloadHash = await sha256Hex(resolvePayload(config))
|
||||
const canonical = [
|
||||
method,
|
||||
toBackendRequestPath(config.baseURL, config.url),
|
||||
timestamp,
|
||||
nonce,
|
||||
payloadHash
|
||||
].join('\n')
|
||||
|
||||
setHeader(config, HEADER_TIMESTAMP, timestamp)
|
||||
setHeader(config, HEADER_NONCE, nonce)
|
||||
setHeader(config, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical))
|
||||
setHeader(config, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION)
|
||||
return config
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { extractRichText, renderRichContent } from './rich-content'
|
||||
|
||||
describe('rich content helpers', () => {
|
||||
it('renders markdown into html', () => {
|
||||
const html = renderRichContent('# 标题\n\n- 甲\n- 乙\n\n**加粗** [链接](https://example.com)')
|
||||
|
||||
expect(html).toContain('<h1>标题</h1>')
|
||||
expect(html).toContain('<ul>')
|
||||
expect(html).toContain('<strong>加粗</strong>')
|
||||
expect(html).toContain('<a href="https://example.com"')
|
||||
})
|
||||
|
||||
it('keeps safe html and strips scripts', () => {
|
||||
const html = renderRichContent('<p>hello <strong>world</strong></p><script>alert(1)</script>')
|
||||
|
||||
expect(html).toBe('<p>hello <strong>world</strong></p>')
|
||||
})
|
||||
|
||||
it('extracts plain text from rich content', () => {
|
||||
expect(extractRichText('<p>Hello <strong>world</strong></p>')).toBe('Hello world')
|
||||
expect(extractRichText('## 标题\n\n内容')).toBe('标题 内容')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
const HTML_TAG_PATTERN = /<\/?[a-z][\s\S]*>/i
|
||||
const DANGEROUS_TAGS = new Set(['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'textarea', 'select', 'svg', 'math'])
|
||||
const ALLOWED_TAGS = new Set([
|
||||
'a',
|
||||
'blockquote',
|
||||
'br',
|
||||
'code',
|
||||
'del',
|
||||
'div',
|
||||
'em',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'hr',
|
||||
'img',
|
||||
'li',
|
||||
'ol',
|
||||
'p',
|
||||
'pre',
|
||||
'span',
|
||||
'strong',
|
||||
'table',
|
||||
'tbody',
|
||||
'td',
|
||||
'th',
|
||||
'thead',
|
||||
'tr',
|
||||
'ul'
|
||||
])
|
||||
const GLOBAL_ATTRS = new Set(['class', 'title'])
|
||||
const TAG_ATTRS: Record<string, Set<string>> = {
|
||||
a: new Set(['href', 'target', 'rel', 'title']),
|
||||
img: new Set(['src', 'alt', 'title']),
|
||||
td: new Set(['colspan', 'rowspan']),
|
||||
th: new Set(['colspan', 'rowspan'])
|
||||
}
|
||||
|
||||
const escapeHtml = (value: string) => value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
|
||||
const escapeAttr = (value: string) => escapeHtml(value).replace(/`/g, '`')
|
||||
|
||||
const isSafeUrl = (value: string) => {
|
||||
const normalized = value.trim().replace(/[\u0000-\u001F\u007F\s]+/g, '')
|
||||
if (!normalized) return false
|
||||
if (normalized.startsWith('#')) return true
|
||||
if (normalized.startsWith('/') && !normalized.startsWith('//')) return true
|
||||
if (/^(https?:|mailto:|tel:)/i.test(normalized)) return true
|
||||
return /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(normalized)
|
||||
}
|
||||
|
||||
const isAllowedAttr = (tagName: string, attrName: string) => {
|
||||
if (attrName.startsWith('on')) return false
|
||||
return GLOBAL_ATTRS.has(attrName) || TAG_ATTRS[tagName]?.has(attrName)
|
||||
}
|
||||
|
||||
const sanitizeFallback = (html: string) => html
|
||||
.replace(/<\s*(script|style|iframe|object|embed|svg|math)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, '')
|
||||
.replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '')
|
||||
.replace(/\s+(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi, '')
|
||||
|
||||
export const sanitizeRichHtml = (html: string) => {
|
||||
const source = html.trim()
|
||||
if (!source) return ''
|
||||
|
||||
if (typeof DOMParser === 'undefined') {
|
||||
return sanitizeFallback(source)
|
||||
}
|
||||
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(source, 'text/html')
|
||||
|
||||
const walk = (node: Node) => {
|
||||
if (node.nodeType === Node.COMMENT_NODE) {
|
||||
node.parentNode?.removeChild(node)
|
||||
return
|
||||
}
|
||||
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) {
|
||||
return
|
||||
}
|
||||
|
||||
const element = node as HTMLElement
|
||||
const tagName = element.tagName.toLowerCase()
|
||||
|
||||
if (DANGEROUS_TAGS.has(tagName)) {
|
||||
element.remove()
|
||||
return
|
||||
}
|
||||
|
||||
if (!ALLOWED_TAGS.has(tagName)) {
|
||||
const children = Array.from(element.childNodes)
|
||||
element.replaceWith(...children)
|
||||
children.forEach(walk)
|
||||
return
|
||||
}
|
||||
|
||||
Array.from(element.attributes).forEach(attribute => {
|
||||
const attrName = attribute.name.toLowerCase()
|
||||
const attrValue = attribute.value
|
||||
|
||||
if (!isAllowedAttr(tagName, attrName)) {
|
||||
element.removeAttribute(attribute.name)
|
||||
return
|
||||
}
|
||||
|
||||
if ((attrName === 'href' || attrName === 'src') && !isSafeUrl(attrValue)) {
|
||||
element.removeAttribute(attribute.name)
|
||||
}
|
||||
})
|
||||
|
||||
if (tagName === 'a' && element.getAttribute('href')) {
|
||||
element.setAttribute('target', '_blank')
|
||||
element.setAttribute('rel', 'noopener noreferrer')
|
||||
}
|
||||
|
||||
Array.from(element.childNodes).forEach(walk)
|
||||
}
|
||||
|
||||
Array.from(doc.body.childNodes).forEach(walk)
|
||||
return doc.body.innerHTML.trim()
|
||||
}
|
||||
|
||||
const renderInlineMarkdown = (value: string) => {
|
||||
let html = escapeHtml(value)
|
||||
|
||||
html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
||||
html = html.replace(/__([^_]+)__/g, '<strong>$1</strong>')
|
||||
html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>')
|
||||
html = html.replace(/_([^_]+)_/g, '<em>$1</em>')
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, label: string, url: string) => {
|
||||
const href = url.replace(/&/g, '&')
|
||||
if (!isSafeUrl(href)) {
|
||||
return label
|
||||
}
|
||||
return `<a href="${escapeAttr(href)}" target="_blank" rel="noopener noreferrer">${label}</a>`
|
||||
})
|
||||
|
||||
return html.replace(/\n/g, '<br>')
|
||||
}
|
||||
|
||||
const markdownToHtml = (markdown: string) => {
|
||||
const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
|
||||
const html: string[] = []
|
||||
const paragraphs: string[] = []
|
||||
const listItems: string[] = []
|
||||
let listTag: 'ul' | 'ol' | '' = ''
|
||||
let inCodeFence = false
|
||||
let codeLines: string[] = []
|
||||
|
||||
const flushParagraph = () => {
|
||||
if (!paragraphs.length) return
|
||||
html.push(`<p>${renderInlineMarkdown(paragraphs.join('\n'))}</p>`)
|
||||
paragraphs.length = 0
|
||||
}
|
||||
|
||||
const flushList = () => {
|
||||
if (!listTag || !listItems.length) return
|
||||
html.push(`<${listTag}>${listItems.map(item => `<li>${renderInlineMarkdown(item)}</li>`).join('')}</${listTag}>`)
|
||||
listItems.length = 0
|
||||
listTag = ''
|
||||
}
|
||||
|
||||
const flushCodeFence = () => {
|
||||
html.push(`<pre><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`)
|
||||
codeLines = []
|
||||
}
|
||||
|
||||
lines.forEach(line => {
|
||||
if (/^```/.test(line.trim())) {
|
||||
if (inCodeFence) {
|
||||
inCodeFence = false
|
||||
flushCodeFence()
|
||||
} else {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
inCodeFence = true
|
||||
codeLines = []
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (inCodeFence) {
|
||||
codeLines.push(line)
|
||||
return
|
||||
}
|
||||
|
||||
if (!line.trim()) {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
return
|
||||
}
|
||||
|
||||
const heading = /^(#{1,6})\s+(.+)$/.exec(line)
|
||||
if (heading) {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
const level = heading[1]!.length
|
||||
html.push(`<h${level}>${renderInlineMarkdown(heading[2]!.trim())}</h${level}>`)
|
||||
return
|
||||
}
|
||||
|
||||
const blockquote = /^>\s?(.*)$/.exec(line)
|
||||
if (blockquote) {
|
||||
flushParagraph()
|
||||
flushList()
|
||||
html.push(`<blockquote>${renderInlineMarkdown(blockquote[1] || '')}</blockquote>`)
|
||||
return
|
||||
}
|
||||
|
||||
const unordered = /^\s*[-*+]\s+(.+)$/.exec(line)
|
||||
if (unordered) {
|
||||
flushParagraph()
|
||||
if (listTag && listTag !== 'ul') flushList()
|
||||
listTag = 'ul'
|
||||
listItems.push(unordered[1] || '')
|
||||
return
|
||||
}
|
||||
|
||||
const ordered = /^\s*\d+\.\s+(.+)$/.exec(line)
|
||||
if (ordered) {
|
||||
flushParagraph()
|
||||
if (listTag && listTag !== 'ol') flushList()
|
||||
listTag = 'ol'
|
||||
listItems.push(ordered[1] || '')
|
||||
return
|
||||
}
|
||||
|
||||
flushList()
|
||||
paragraphs.push(line)
|
||||
})
|
||||
|
||||
if (inCodeFence) {
|
||||
flushCodeFence()
|
||||
}
|
||||
flushParagraph()
|
||||
flushList()
|
||||
|
||||
return html.join('')
|
||||
}
|
||||
|
||||
export const renderRichContent = (content?: string | null) => {
|
||||
const source = String(content || '').trim()
|
||||
if (!source) return ''
|
||||
|
||||
const html = HTML_TAG_PATTERN.test(source) ? source : markdownToHtml(source)
|
||||
return sanitizeRichHtml(html)
|
||||
}
|
||||
|
||||
export const extractRichText = (content?: string | null) => {
|
||||
const html = renderRichContent(content)
|
||||
if (!html) return ''
|
||||
const spacedHtml = html
|
||||
.replace(/<br\s*\/?>/gi, ' ')
|
||||
.replace(/<\/(p|div|h[1-6]|li|blockquote|tr)>/gi, ' </$1>')
|
||||
|
||||
if (typeof DOMParser === 'undefined') {
|
||||
return spacedHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(spacedHtml, 'text/html')
|
||||
return (doc.body.textContent || '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* Purpose: SHOP_THEME_CHANGED_EVENT supports shop-theme.ts by holding or executing the shop theme changed event page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export const SHOP_THEME_CHANGED_EVENT = 'jayu-cloud-shop-theme-updated'
|
||||
|
||||
/**
|
||||
* Purpose: ShopThemeSource supports shop-theme.ts by holding or executing the shop theme source page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ShopThemeSource {
|
||||
themePrimaryColor?: string | null
|
||||
themeSecondaryColor?: string | null
|
||||
themeAccentColor?: string | null
|
||||
themePageBgColor?: string | null
|
||||
themeCardBgColor?: string | null
|
||||
themeBackgroundImageFileId?: string | number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: ResolvedShopTheme supports shop-theme.ts by holding or executing the resolved shop theme page or API role.
|
||||
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export interface ResolvedShopTheme {
|
||||
primaryColor: string
|
||||
secondaryColor: string
|
||||
accentColor: string
|
||||
tertiaryColor: string
|
||||
neutralColor: string
|
||||
pageBgColor: string
|
||||
cardBgColor: string
|
||||
textPrimary: string
|
||||
textSecondary: string
|
||||
borderColor: string
|
||||
primarySoftColor: string
|
||||
secondarySoftColor: string
|
||||
primaryActionColor: string
|
||||
gradient: string
|
||||
softGradient: string
|
||||
backgroundImageFileId?: string
|
||||
cssVars: Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: HEX_COLOR_PATTERN supports shop-theme.ts by holding or executing the hex color pattern page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/
|
||||
|
||||
export const DEFAULT_SHOP_THEME: ResolvedShopTheme = resolveShopThemeSource()
|
||||
|
||||
/**
|
||||
* Purpose: resolveShopTheme supports shop-theme.ts by holding or executing the resolve shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function resolveShopTheme(source?: ShopThemeSource | null): ResolvedShopTheme {
|
||||
return resolveShopThemeSource(source)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: applyShopTheme supports shop-theme.ts by holding or executing the apply shop theme page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function applyShopTheme(theme: ResolvedShopTheme, backgroundImageUrl?: string | null) {
|
||||
if (typeof document === 'undefined') {
|
||||
return
|
||||
}
|
||||
const root = document.documentElement
|
||||
Object.entries(theme.cssVars).forEach(([key, value]) => {
|
||||
root.style.setProperty(key, value)
|
||||
})
|
||||
root.style.setProperty('--theme-background-image', backgroundImageUrl ? `url("${backgroundImageUrl}")` : 'none')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: notifyShopThemeChanged supports shop-theme.ts by holding or executing the notify shop theme changed page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
export function notifyShopThemeChanged() {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
window.dispatchEvent(new Event(SHOP_THEME_CHANGED_EVENT))
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: resolveShopThemeSource supports shop-theme.ts by holding or executing the resolve shop theme source page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function resolveShopThemeSource(source?: ShopThemeSource | null): ResolvedShopTheme {
|
||||
const normalizedPrimaryColor = normalizeHexColor(source?.themePrimaryColor)
|
||||
const primaryColor = normalizedPrimaryColor || '#E8B4B8'
|
||||
const secondaryColor = normalizeHexColor(source?.themeSecondaryColor)
|
||||
|| (normalizedPrimaryColor ? mixColor(primaryColor, '#C5A059', 0.35) : '#C5A059')
|
||||
const neutralColor = normalizeHexColor(source?.themeAccentColor)
|
||||
|| (normalizedPrimaryColor ? mixColor('#4A443F', primaryColor, 0.14) : '#4A443F')
|
||||
const accentColor = neutralColor
|
||||
const tertiaryColor = normalizeHexColor(source?.themePageBgColor) || '#FDFBF9'
|
||||
const pageBgColor = tertiaryColor
|
||||
const cardBgColor = normalizeHexColor(source?.themeCardBgColor) || '#FFFFFF'
|
||||
const textPrimary = readableTextColor(pageBgColor, neutralColor)
|
||||
const textSecondary = textPrimary === neutralColor
|
||||
? mixColor(neutralColor, cardBgColor, 0.18)
|
||||
: mixColor('#FFFFFF', primaryColor, 0.3)
|
||||
const borderColor = mixColor(primaryColor, cardBgColor, 0.72)
|
||||
const primarySoftColor = mixColor(primaryColor, cardBgColor, 0.78)
|
||||
const secondarySoftColor = mixColor(secondaryColor, pageBgColor, 0.66)
|
||||
const primaryActionColor = mixColor(neutralColor, primaryColor, 0.28)
|
||||
const gradient = `linear-gradient(135deg, ${primaryActionColor} 0%, ${secondaryColor} 100%)`
|
||||
const softGradient = `linear-gradient(145deg, ${cardBgColor} 0%, ${secondarySoftColor} 58%, ${mixColor(primaryColor, pageBgColor, 0.62)} 100%)`
|
||||
const backgroundImageFileId = source?.themeBackgroundImageFileId === undefined || source?.themeBackgroundImageFileId === null
|
||||
? undefined
|
||||
: String(source.themeBackgroundImageFileId).trim() || undefined
|
||||
|
||||
return {
|
||||
primaryColor,
|
||||
secondaryColor,
|
||||
accentColor,
|
||||
tertiaryColor,
|
||||
neutralColor,
|
||||
pageBgColor,
|
||||
cardBgColor,
|
||||
textPrimary,
|
||||
textSecondary,
|
||||
borderColor,
|
||||
primarySoftColor,
|
||||
secondarySoftColor,
|
||||
primaryActionColor,
|
||||
gradient,
|
||||
softGradient,
|
||||
backgroundImageFileId,
|
||||
cssVars: {
|
||||
'--primary-color': primaryColor,
|
||||
'--theme-primary': primaryColor,
|
||||
'--theme-secondary': secondaryColor,
|
||||
'--theme-accent': accentColor,
|
||||
'--theme-neutral': neutralColor,
|
||||
'--theme-tertiary': tertiaryColor,
|
||||
'--theme-primary-action': primaryActionColor,
|
||||
'--theme-primary-soft': primarySoftColor,
|
||||
'--theme-secondary-soft': secondarySoftColor,
|
||||
'--theme-page-bg': pageBgColor,
|
||||
'--theme-card-bg': cardBgColor,
|
||||
'--theme-border': borderColor,
|
||||
'--theme-gradient': gradient,
|
||||
'--theme-gradient-soft': softGradient,
|
||||
'--theme-button-shadow': `0 12px 28px ${rgba(primaryColor, 0.22)}`,
|
||||
'--theme-focus-shadow': `0 0 0 3px ${rgba(primaryColor, 0.16)}`,
|
||||
'--bg-color': pageBgColor,
|
||||
'--secondary-bg-color': mixColor(secondaryColor, pageBgColor, 0.58),
|
||||
'--surface-color': cardBgColor,
|
||||
'--text-primary': textPrimary,
|
||||
'--text-secondary': textSecondary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: normalizeHexColor supports shop-theme.ts by holding or executing the normalize hex color page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function normalizeHexColor(value?: string | null): string | undefined {
|
||||
if (!value) {
|
||||
return undefined
|
||||
}
|
||||
const normalized = value.trim()
|
||||
return HEX_COLOR_PATTERN.test(normalized) ? normalized.toUpperCase() : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: mixColor supports shop-theme.ts by holding or executing the mix color page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function mixColor(foreground: string, background: string, backgroundWeight: number): string {
|
||||
const fg = hexToRgb(foreground)
|
||||
const bg = hexToRgb(background)
|
||||
const weight = clamp(backgroundWeight, 0, 1)
|
||||
return rgbToHex({
|
||||
r: Math.round(fg.r * (1 - weight) + bg.r * weight),
|
||||
g: Math.round(fg.g * (1 - weight) + bg.g * weight),
|
||||
b: Math.round(fg.b * (1 - weight) + bg.b * weight)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: readableTextColor supports shop-theme.ts by holding or executing the readable text color page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function readableTextColor(background: string, preferred: string): string {
|
||||
return relativeLuminance(hexToRgb(background)) > 0.48 ? preferred : '#FFFFFF'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: rgba supports shop-theme.ts by holding or executing the rgba page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function rgba(color: string, alpha: number): string {
|
||||
const rgb = hexToRgb(color)
|
||||
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${clamp(alpha, 0, 1)})`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: relativeLuminance supports shop-theme.ts by holding or executing the relative luminance page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function relativeLuminance(rgb: { r: number; g: number; b: number }): number {
|
||||
const toLinearChannel = (value: number) => {
|
||||
const channel = value / 255
|
||||
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4)
|
||||
}
|
||||
const r = toLinearChannel(rgb.r)
|
||||
const g = toLinearChannel(rgb.g)
|
||||
const b = toLinearChannel(rgb.b)
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: hexToRgb supports shop-theme.ts by holding or executing the hex to rgb page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function hexToRgb(color: string): { r: number; g: number; b: number } {
|
||||
const value = color.replace('#', '')
|
||||
return {
|
||||
r: Number.parseInt(value.slice(0, 2), 16),
|
||||
g: Number.parseInt(value.slice(2, 4), 16),
|
||||
b: Number.parseInt(value.slice(4, 6), 16)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: rgbToHex supports shop-theme.ts by holding or executing the rgb to hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function rgbToHex(rgb: { r: number; g: number; b: number }): string {
|
||||
return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: toHex supports shop-theme.ts by holding or executing the to hex page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function toHex(value: number): string {
|
||||
return clamp(value, 0, 255).toString(16).padStart(2, '0').toUpperCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: clamp supports shop-theme.ts by holding or executing the clamp page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const publicGetSignedUrl = vi.fn()
|
||||
const adminGetSignedUrl = vi.fn()
|
||||
|
||||
vi.mock('@/api/file', () => ({
|
||||
fileApi: {
|
||||
getSignedUrl: publicGetSignedUrl
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/api/admin', () => ({
|
||||
adminFileApi: {
|
||||
getSignedUrl: adminGetSignedUrl
|
||||
}
|
||||
}))
|
||||
|
||||
describe('signed-image-cache', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
publicGetSignedUrl.mockResolvedValue({ data: 'https://public.test/image.jpg' })
|
||||
adminGetSignedUrl.mockResolvedValue('https://admin.test/image.jpg')
|
||||
})
|
||||
|
||||
it('keeps public and admin signed url cache entries isolated', async () => {
|
||||
const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache')
|
||||
|
||||
await expect(getCachedSignedImageUrl('42', '', 'public')).resolves.toBe('https://public.test/image.jpg')
|
||||
await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/image.jpg')
|
||||
|
||||
expect(publicGetSignedUrl).toHaveBeenCalledTimes(1)
|
||||
expect(adminGetSignedUrl).toHaveBeenCalledTimes(1)
|
||||
expect(getCachedSignedImageUrlSync('42', 'public')).toBe('https://public.test/image.jpg')
|
||||
expect(getCachedSignedImageUrlSync('42', 'admin')).toBe('https://admin.test/image.jpg')
|
||||
})
|
||||
|
||||
it('uses fallback when file id is empty or signing fails', async () => {
|
||||
const { getCachedSignedImageUrl } = await import('./signed-image-cache')
|
||||
|
||||
await expect(getCachedSignedImageUrl('', 'fallback.png', 'public')).resolves.toBe('fallback.png')
|
||||
publicGetSignedUrl.mockRejectedValueOnce(new Error('sign failed'))
|
||||
await expect(getCachedSignedImageUrl('99', 'fallback.png', 'public')).resolves.toBe('fallback.png')
|
||||
})
|
||||
|
||||
it('normalizes signed image urls without scheme', async () => {
|
||||
const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache')
|
||||
|
||||
adminGetSignedUrl.mockResolvedValueOnce('img.yunail.art/325517220106911744.jpg?e=1&token=test')
|
||||
|
||||
await expect(getCachedSignedImageUrl('325517232303947776', '', 'admin')).resolves.toBe(
|
||||
'http://img.yunail.art/325517220106911744.jpg?e=1&token=test'
|
||||
)
|
||||
expect(getCachedSignedImageUrlSync('325517232303947776', 'admin')).toBe(
|
||||
'http://img.yunail.art/325517220106911744.jpg?e=1&token=test'
|
||||
)
|
||||
})
|
||||
|
||||
it('refreshes a cached signed image url after clearing the old entry', async () => {
|
||||
const { getCachedSignedImageUrl, refreshCachedSignedImageUrl } = await import('./signed-image-cache')
|
||||
|
||||
adminGetSignedUrl
|
||||
.mockResolvedValueOnce('https://admin.test/old.jpg')
|
||||
.mockResolvedValueOnce('https://admin.test/new.jpg')
|
||||
|
||||
await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/old.jpg')
|
||||
await expect(refreshCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/new.jpg')
|
||||
expect(adminGetSignedUrl).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import { fileApi } from '@/api/file'
|
||||
import { adminFileApi } from '@/api/admin'
|
||||
import type { IdType } from '@/utils/id'
|
||||
|
||||
const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000
|
||||
|
||||
export type SignedImageSource = 'public' | 'admin'
|
||||
|
||||
type SignedImageCacheEntry = {
|
||||
url: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const signedImageUrlCache = new Map<string, SignedImageCacheEntry>()
|
||||
const pendingSignedImageUrlRequests = new Map<string, Promise<string>>()
|
||||
|
||||
const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim()
|
||||
const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}`
|
||||
const normalizeImageUrl = (url: string): string => {
|
||||
const trimmedUrl = url.trim()
|
||||
if (!trimmedUrl) return ''
|
||||
if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) {
|
||||
return trimmedUrl
|
||||
}
|
||||
return `http://${trimmedUrl}`
|
||||
}
|
||||
|
||||
const requestSignedImageUrl = (source: SignedImageSource, fileId: string): Promise<string> => {
|
||||
if (source === 'admin') {
|
||||
return adminFileApi.getSignedUrl(fileId)
|
||||
}
|
||||
return fileApi.getSignedUrl(fileId).then(response => String(response.data || ''))
|
||||
}
|
||||
|
||||
const getUsableCacheEntry = (key: string) => {
|
||||
const cached = signedImageUrlCache.get(key)
|
||||
if (!cached) return undefined
|
||||
if (cached.expiresAt <= Date.now()) {
|
||||
signedImageUrlCache.delete(key)
|
||||
return undefined
|
||||
}
|
||||
return cached.url
|
||||
}
|
||||
|
||||
export const parseImageFileIds = (value?: string | null): string[] =>
|
||||
String(value || '')
|
||||
.split(',')
|
||||
.map(id => id.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
export const getCachedSignedImageUrlSync = (
|
||||
fileId: IdType | null | undefined,
|
||||
source: SignedImageSource = 'public'
|
||||
): string => {
|
||||
const fileIdKey = normalizeFileId(fileId)
|
||||
if (!fileIdKey) return ''
|
||||
return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || ''
|
||||
}
|
||||
|
||||
export const getCachedSignedImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback = '',
|
||||
source: SignedImageSource = 'public'
|
||||
): Promise<string> => {
|
||||
const fileIdKey = normalizeFileId(fileId)
|
||||
if (!fileIdKey) return fallback
|
||||
const key = buildCacheKey(source, fileIdKey)
|
||||
|
||||
const cachedUrl = getUsableCacheEntry(key)
|
||||
if (cachedUrl) return cachedUrl
|
||||
|
||||
const pendingRequest = pendingSignedImageUrlRequests.get(key)
|
||||
if (pendingRequest) {
|
||||
return pendingRequest.then(url => url || fallback).catch(() => fallback)
|
||||
}
|
||||
|
||||
const request = requestSignedImageUrl(source, fileIdKey)
|
||||
.then(response => {
|
||||
const url = normalizeImageUrl(String(response || ''))
|
||||
if (url) {
|
||||
signedImageUrlCache.set(key, {
|
||||
url,
|
||||
expiresAt: Date.now() + SIGNED_IMAGE_CACHE_TTL_MS
|
||||
})
|
||||
}
|
||||
return url
|
||||
})
|
||||
.finally(() => {
|
||||
pendingSignedImageUrlRequests.delete(key)
|
||||
})
|
||||
|
||||
pendingSignedImageUrlRequests.set(key, request)
|
||||
return request.then(url => url || fallback).catch(() => fallback)
|
||||
}
|
||||
|
||||
export const clearCachedSignedImageUrl = (
|
||||
fileId: IdType | null | undefined,
|
||||
source: SignedImageSource = 'public'
|
||||
): void => {
|
||||
const fileIdKey = normalizeFileId(fileId)
|
||||
if (!fileIdKey) return
|
||||
const cacheKey = buildCacheKey(source, fileIdKey)
|
||||
signedImageUrlCache.delete(cacheKey)
|
||||
pendingSignedImageUrlRequests.delete(cacheKey)
|
||||
}
|
||||
|
||||
export const refreshCachedSignedImageUrl = async (
|
||||
fileId: IdType | null | undefined,
|
||||
fallback = '',
|
||||
source: SignedImageSource = 'public'
|
||||
): Promise<string> => {
|
||||
clearCachedSignedImageUrl(fileId, source)
|
||||
return getCachedSignedImageUrl(fileId, fallback, source)
|
||||
}
|
||||
|
||||
export const getCachedSignedImageUrls = async (
|
||||
fileIds: Array<IdType | null | undefined>,
|
||||
fallback = '',
|
||||
source: SignedImageSource = 'public'
|
||||
): Promise<string[]> => {
|
||||
const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source)))
|
||||
const validUrls = urls.filter(Boolean)
|
||||
return validUrls.length ? validUrls : (fallback ? [fallback] : [])
|
||||
}
|
||||
|
||||
export const getCachedSignedImageUrlsSync = (
|
||||
fileIds: Array<IdType | null | undefined>,
|
||||
source: SignedImageSource = 'public'
|
||||
): string[] =>
|
||||
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean)
|
||||
|
||||
export const extractLegacyFileId = (value?: string | null): string => {
|
||||
const source = String(value || '').replace(/<[^>]*>/g, '')
|
||||
return source.match(/\/api\/file\/get\/([^/?#"'<>]+)/)?.[1] || ''
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildSystemMessageActionPath } from './system-message-action'
|
||||
|
||||
describe('buildSystemMessageActionPath', () => {
|
||||
it('keeps safe review action paths with order and review query parameters', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
actionPath: '/orders?orderId=10&reviewId=99&orderItemId=1001',
|
||||
businessType: 'ORDER_ARTIST_REVIEW',
|
||||
businessId: 99
|
||||
})).toBe('/orders?orderId=10&reviewId=99&orderItemId=1001')
|
||||
})
|
||||
|
||||
it('uses reviewId fallback for review reminder messages when actionPath is absent', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'ORDER_ARTIST_REVIEW',
|
||||
businessId: 99
|
||||
})).toBe('/orders?reviewId=99&source=message')
|
||||
})
|
||||
|
||||
it('opens pending reviews when a review reminder has no business id', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'ORDER_ARTIST_REVIEW'
|
||||
})).toBe('/orders?review=pending&source=message')
|
||||
})
|
||||
|
||||
it('uses orderId fallback for generic order messages', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'ORDER',
|
||||
businessId: 10
|
||||
})).toBe('/orders/10')
|
||||
})
|
||||
|
||||
it('uses after-sale fallback for after-sale messages', () => {
|
||||
expect(buildSystemMessageActionPath({
|
||||
businessType: 'AFTER_SALE',
|
||||
businessId: 10
|
||||
})).toBe('/after-sales?orderId=10&source=message')
|
||||
})
|
||||
|
||||
it('keeps safe order detail and after-sale action paths', () => {
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/orders/10' })).toBe('/orders/10')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/after-sales?orderId=10' })).toBe('/after-sales?orderId=10')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/after-sale/apply?orderId=10&orderItemId=99' })).toBe('/after-sale/apply?orderId=10&orderItemId=99')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/service-progress?orderId=10' })).toBe('/service-progress?orderId=10')
|
||||
})
|
||||
|
||||
it('rejects unsafe or backend-only action paths', () => {
|
||||
expect(buildSystemMessageActionPath({ actionPath: '//evil.example/orders' })).toBe('')
|
||||
expect(buildSystemMessageActionPath({ actionPath: 'https://evil.example/orders' })).toBe('')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/admin/users' })).toBe('')
|
||||
expect(buildSystemMessageActionPath({ actionPath: '/orders-admin' })).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { SystemMessageVO } from '@/api/user'
|
||||
|
||||
type MessageLike = Pick<SystemMessageVO, 'actionPath' | 'businessType' | 'businessId'>
|
||||
|
||||
const USER_ACTION_PREFIXES = [
|
||||
'/orders',
|
||||
'/after-sales',
|
||||
'/after-sale/apply',
|
||||
'/service-progress',
|
||||
'/help',
|
||||
'/product/',
|
||||
'/shop/',
|
||||
'/coupons',
|
||||
'/vip-center',
|
||||
'/cart',
|
||||
'/notifications',
|
||||
'/wishlist',
|
||||
'/profile',
|
||||
'/settings',
|
||||
'/artist-orders',
|
||||
'/artist-calendar'
|
||||
]
|
||||
|
||||
const appendQuery = (path: string, query: Record<string, string | number | undefined>) => {
|
||||
const params = new URLSearchParams()
|
||||
Object.entries(query).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== '') {
|
||||
params.set(key, String(value))
|
||||
}
|
||||
})
|
||||
const queryString = params.toString()
|
||||
return queryString ? `${path}?${queryString}` : path
|
||||
}
|
||||
|
||||
const isAllowedUserActionPath = (actionPath: string) => {
|
||||
const pathOnly = actionPath.split('?')[0] || ''
|
||||
return USER_ACTION_PREFIXES.some(prefix => {
|
||||
if (prefix.endsWith('/')) {
|
||||
return pathOnly.startsWith(prefix)
|
||||
}
|
||||
return pathOnly === prefix || pathOnly.startsWith(`${prefix}/`)
|
||||
})
|
||||
}
|
||||
|
||||
export const normalizeSystemMessageActionPath = (value?: string) => {
|
||||
const actionPath = String(value || '').trim()
|
||||
if (!actionPath || !actionPath.startsWith('/') || actionPath.startsWith('//') || actionPath.includes('\\')) {
|
||||
return ''
|
||||
}
|
||||
return isAllowedUserActionPath(actionPath) ? actionPath : ''
|
||||
}
|
||||
|
||||
export const buildSystemMessageActionPath = (message: MessageLike) => {
|
||||
const actionPath = normalizeSystemMessageActionPath(message.actionPath)
|
||||
if (actionPath) {
|
||||
return actionPath
|
||||
}
|
||||
|
||||
const businessType = String(message.businessType || '').toUpperCase()
|
||||
const businessId = message.businessId === undefined || message.businessId === null ? '' : String(message.businessId)
|
||||
if (businessType === 'ORDER_ARTIST_REVIEW') {
|
||||
return businessId
|
||||
? appendQuery('/orders', { reviewId: businessId, source: 'message' })
|
||||
: appendQuery('/orders', { review: 'pending', source: 'message' })
|
||||
}
|
||||
if (businessType === 'ORDER' && businessId) {
|
||||
return `/orders/${encodeURIComponent(businessId)}`
|
||||
}
|
||||
if (businessType === 'ORDER_ARTIST_CHANGE' && businessId) {
|
||||
return appendQuery('/service-progress', { orderId: businessId, source: 'message' })
|
||||
}
|
||||
if (businessType === 'ORDER_ARTIST_CHANGE' || businessType === 'ORDER') {
|
||||
return appendQuery('/orders', { orderId: businessId || undefined, source: 'message' })
|
||||
}
|
||||
if (businessType === 'AFTER_SALE') {
|
||||
return appendQuery('/after-sales', { orderId: businessId || undefined, source: 'message' })
|
||||
}
|
||||
if (businessType === 'PRODUCT' && businessId) {
|
||||
return `/product/${encodeURIComponent(businessId)}`
|
||||
}
|
||||
if (businessType === 'SHOP' && businessId) {
|
||||
return `/shop/${encodeURIComponent(businessId)}`
|
||||
}
|
||||
if (businessType === 'VIP') {
|
||||
return '/vip-center'
|
||||
}
|
||||
if (businessType === 'COUPON') {
|
||||
return '/coupons'
|
||||
}
|
||||
if (businessType === 'CART') {
|
||||
return '/cart'
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
@@ -0,0 +1,835 @@
|
||||
<template>
|
||||
<div class="mobile-container">
|
||||
<!-- 头部区域 -->
|
||||
<header class="header">
|
||||
<a-button class="back-btn" type="text" @click="handleBackClick">
|
||||
<LeftOutlined :style="{ fontSize: '20px' }" />
|
||||
</a-button>
|
||||
<h1>账号设置</h1>
|
||||
<div class="empty"></div>
|
||||
</header>
|
||||
|
||||
<!-- 账号设置内容 -->
|
||||
<div class="account-settings">
|
||||
<!-- 账号设置选项 -->
|
||||
<a-card :bordered="false" class="settings-card">
|
||||
<a-list :data-source="accountSettings" :split="false">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item class="setting-item" @click="handleSettingClick(item.key)">
|
||||
<template #actions>
|
||||
<RightOutlined />
|
||||
</template>
|
||||
<a-list-item-meta>
|
||||
<template #avatar>
|
||||
<div class="setting-icon" :style="{ backgroundColor: item.bgColor }">
|
||||
<component :is="item.icon" />
|
||||
</div>
|
||||
</template>
|
||||
<template #title>
|
||||
<span>{{ item.title }}</span>
|
||||
</template>
|
||||
<template #description v-if="item.desc">
|
||||
<span>{{ item.desc }}</span>
|
||||
</template>
|
||||
</a-list-item-meta>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
</a-card>
|
||||
</div>
|
||||
|
||||
<!-- 绑定手机号弹窗 -->
|
||||
<a-modal
|
||||
v-model:visible="bindPhoneModalVisible"
|
||||
title="绑定手机号"
|
||||
@ok="handleBindPhoneSubmit"
|
||||
@cancel="handleBindPhoneCancel"
|
||||
:confirmLoading="bindPhoneLoading"
|
||||
>
|
||||
<DraftActions
|
||||
:saved-at="bindPhoneDraftSavedAt"
|
||||
@save="handleSaveBindPhoneDraft"
|
||||
@clear="handleClearBindPhoneDraft"
|
||||
/>
|
||||
<a-form layout="vertical">
|
||||
<a-form-item label="手机号" name="phone">
|
||||
<a-input
|
||||
v-model:value="bindPhoneForm.phone"
|
||||
placeholder="请输入手机号"
|
||||
:disabled="!!userInfo.phone"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="验证码" name="verificationCode">
|
||||
<a-input
|
||||
v-model:value="bindPhoneForm.verificationCode"
|
||||
placeholder="请输入验证码"
|
||||
>
|
||||
<template #suffix>
|
||||
<a-button
|
||||
type="link"
|
||||
:disabled="countdown > 0 || !bindPhoneForm.phone"
|
||||
@click="handleSendVerificationCode"
|
||||
>
|
||||
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
|
||||
</a-button>
|
||||
</template>
|
||||
</a-input>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
|
||||
<!-- 修改手机号弹窗 -->
|
||||
<a-modal
|
||||
v-model:visible="changePhoneModalVisible"
|
||||
title="修改手机号"
|
||||
@ok="handleChangePhoneSubmit"
|
||||
@cancel="handleChangePhoneCancel"
|
||||
:confirmLoading="changePhoneLoading"
|
||||
>
|
||||
<DraftActions
|
||||
:saved-at="changePhoneDraftSavedAt"
|
||||
@save="handleSaveChangePhoneDraft"
|
||||
@clear="handleClearChangePhoneDraft"
|
||||
/>
|
||||
<a-form layout="vertical">
|
||||
<a-form-item label="旧手机号">
|
||||
<a-input :value="userInfo.phone" disabled />
|
||||
</a-form-item>
|
||||
<a-form-item label="新手机号" name="newPhone">
|
||||
<a-input
|
||||
v-model:value="changePhoneForm.newPhone"
|
||||
placeholder="请输入新手机号"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="验证码" name="verificationCode">
|
||||
<a-input
|
||||
v-model:value="changePhoneForm.verificationCode"
|
||||
placeholder="请输入验证码"
|
||||
>
|
||||
<template #suffix>
|
||||
<a-button
|
||||
type="link"
|
||||
:disabled="countdown > 0 || !changePhoneForm.newPhone"
|
||||
@click="handleSendChangePhoneVerificationCode"
|
||||
>
|
||||
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
|
||||
</a-button>
|
||||
</template>
|
||||
</a-input>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
|
||||
<!-- 修改密码弹窗 -->
|
||||
<a-modal
|
||||
v-model:visible="changePasswordModalVisible"
|
||||
title="修改密码"
|
||||
@ok="handleChangePasswordSubmit"
|
||||
@cancel="handleChangePasswordCancel"
|
||||
:confirmLoading="changePasswordLoading"
|
||||
>
|
||||
<DraftActions
|
||||
:saved-at="changePasswordDraftSavedAt"
|
||||
@save="handleSaveChangePasswordDraft"
|
||||
@clear="handleClearChangePasswordDraft"
|
||||
/>
|
||||
<a-form layout="vertical">
|
||||
<a-form-item label="手机号">
|
||||
<a-input :value="userInfo.phone" disabled />
|
||||
</a-form-item>
|
||||
<a-form-item label="验证码" name="verificationCode">
|
||||
<a-input
|
||||
v-model:value="changePasswordForm.verificationCode"
|
||||
placeholder="请输入验证码"
|
||||
>
|
||||
<template #suffix>
|
||||
<a-button
|
||||
type="link"
|
||||
:disabled="countdown > 0"
|
||||
@click="handleSendChangePasswordVerificationCode"
|
||||
>
|
||||
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
|
||||
</a-button>
|
||||
</template>
|
||||
</a-input>
|
||||
</a-form-item>
|
||||
<a-form-item label="新密码" name="password">
|
||||
<a-input-password
|
||||
v-model:value="changePasswordForm.password"
|
||||
placeholder="请输入新密码"
|
||||
/>
|
||||
<div class="password-tip">
|
||||
密码长度至少8位,包含字母和数字
|
||||
</div>
|
||||
</a-form-item>
|
||||
<a-form-item label="确认密码" name="confirmPassword">
|
||||
<a-input-password
|
||||
v-model:value="changePasswordForm.confirmPassword"
|
||||
placeholder="请再次输入新密码"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
</div>
|
||||
</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'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import DraftActions from '@/components/DraftActions.vue'
|
||||
import { userApi } from '@/api/user'
|
||||
import type { UserVO } from '@/api/user'
|
||||
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
|
||||
/**
|
||||
* Purpose: router supports AccountSettingsView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
|
||||
// 用户信息
|
||||
const userInfo = ref<UserVO>({
|
||||
id: 0,
|
||||
nickname: '',
|
||||
account: '',
|
||||
avatar: '',
|
||||
type: 0,
|
||||
status: 0,
|
||||
createTime: '',
|
||||
updateTime: ''
|
||||
})
|
||||
|
||||
// 状态标识
|
||||
/** 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)
|
||||
/**
|
||||
* Purpose: bindPhoneDraftSavedAt supports AccountSettingsView.vue by holding or executing the bind phone draft saved at page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const bindPhoneDraftSavedAt = ref<number | null>(null)
|
||||
/**
|
||||
* Purpose: bindPhoneForm supports AccountSettingsView.vue by holding or executing the bind phone form page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const bindPhoneForm = reactive({
|
||||
phone: '',
|
||||
verificationCode: ''
|
||||
})
|
||||
|
||||
// 修改手机号表单
|
||||
/** 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)
|
||||
/**
|
||||
* Purpose: changePhoneDraftSavedAt supports AccountSettingsView.vue by holding or executing the change phone draft saved at page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const changePhoneDraftSavedAt = ref<number | null>(null)
|
||||
/**
|
||||
* Purpose: changePhoneForm supports AccountSettingsView.vue by holding or executing the change phone form page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const changePhoneForm = reactive({
|
||||
newPhone: '',
|
||||
verificationCode: ''
|
||||
})
|
||||
|
||||
// 修改密码表单
|
||||
/** 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)
|
||||
/**
|
||||
* Purpose: changePasswordDraftSavedAt supports AccountSettingsView.vue by holding or executing the change password draft saved at page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const changePasswordDraftSavedAt = ref<number | null>(null)
|
||||
/**
|
||||
* Purpose: changePasswordForm supports AccountSettingsView.vue by holding or executing the change password form page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const changePasswordForm = reactive({
|
||||
verificationCode: '',
|
||||
password: '',
|
||||
confirmPassword: ''
|
||||
})
|
||||
|
||||
/**
|
||||
* Purpose: restoreSessionDraft supports AccountSettingsView.vue by holding or executing the restore session draft page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const restoreSessionDraft = <T extends Record<string, any>>(key: string, target: T, savedAtRef: typeof bindPhoneDraftSavedAt) => {
|
||||
const draft = loadDraftRecord<T>(key, 'session')
|
||||
if (!draft) {
|
||||
savedAtRef.value = null
|
||||
return
|
||||
}
|
||||
Object.assign(target, draft.payload)
|
||||
savedAtRef.value = draft.savedAt
|
||||
message.success('已恢复暂存内容')
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: saveSessionDraft supports AccountSettingsView.vue by holding or executing the save session draft page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const saveSessionDraft = <T>(key: string, payload: T, savedAtRef: typeof bindPhoneDraftSavedAt, successMessage = '已暂存到当前会话') => {
|
||||
const draft = saveDraftRecord(key, payload, 'session')
|
||||
savedAtRef.value = draft.savedAt
|
||||
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
|
||||
if (showMessage) {
|
||||
message.success('已清除暂存')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: bindPhoneDraftKey supports AccountSettingsView.vue by holding or executing the bind phone draft key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const bindPhoneDraftKey = buildDraftStorageKey('account-settings', 'bind-phone')
|
||||
/**
|
||||
* Purpose: changePhoneDraftKey supports AccountSettingsView.vue by holding or executing the change phone draft key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const changePhoneDraftKey = buildDraftStorageKey('account-settings', 'change-phone')
|
||||
/**
|
||||
* Purpose: changePasswordDraftKey supports AccountSettingsView.vue by holding or executing the change password draft key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const 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',
|
||||
title: '修改手机号',
|
||||
icon: PhoneOutlined,
|
||||
bgColor: '#e6f7ff'
|
||||
},
|
||||
{
|
||||
key: 'changePassword',
|
||||
title: '修改密码',
|
||||
icon: LockOutlined,
|
||||
bgColor: '#f6ffed'
|
||||
},
|
||||
{
|
||||
key: 'deactivateAccount',
|
||||
title: '注销账号',
|
||||
icon: LockOutlined,
|
||||
bgColor: '#fff1f0'
|
||||
}
|
||||
])
|
||||
|
||||
// 根据用户状态动态更新账号设置选项
|
||||
/** updateAccountSettings is a local helper used by this page script. */
|
||||
const updateAccountSettings = () => {
|
||||
const settings = []
|
||||
|
||||
// 手机号相关
|
||||
if (!hasPhone.value) {
|
||||
settings.push({
|
||||
key: 'bindPhone',
|
||||
title: '绑定手机号',
|
||||
icon: PhoneOutlined,
|
||||
bgColor: '#e6f7ff'
|
||||
})
|
||||
} else {
|
||||
settings.push({
|
||||
key: 'changePhone',
|
||||
title: '修改手机号',
|
||||
icon: PhoneOutlined,
|
||||
bgColor: '#e6f7ff'
|
||||
})
|
||||
}
|
||||
|
||||
// 密码相关
|
||||
if (!hasPassword.value) {
|
||||
settings.push({
|
||||
key: 'setPassword',
|
||||
title: '设置密码',
|
||||
icon: LockOutlined,
|
||||
bgColor: '#fff7e6'
|
||||
})
|
||||
} else {
|
||||
settings.push({
|
||||
key: 'changePassword',
|
||||
title: '修改密码',
|
||||
icon: LockOutlined,
|
||||
bgColor: '#f6ffed'
|
||||
})
|
||||
}
|
||||
|
||||
// 注销账号
|
||||
settings.push({
|
||||
key: 'deactivateAccount',
|
||||
title: '注销账号',
|
||||
icon: LockOutlined,
|
||||
bgColor: '#fff1f0'
|
||||
})
|
||||
|
||||
accountSettings.value = settings
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
/** 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
|
||||
userInfo.value = response
|
||||
// 检查是否绑定手机号
|
||||
hasPhone.value = !!userInfo.value.phone
|
||||
// 检查是否设置密码(通过localStorage中的标识)
|
||||
hasPassword.value = localStorage.getItem('needSetPassword') !== 'true'
|
||||
// 更新账号设置选项
|
||||
updateAccountSettings()
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error)
|
||||
message.error('获取用户信息失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 处理返回
|
||||
/** 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':
|
||||
restoreSessionDraft(bindPhoneDraftKey, bindPhoneForm, bindPhoneDraftSavedAt)
|
||||
bindPhoneModalVisible.value = true
|
||||
break
|
||||
case 'changePhone':
|
||||
restoreSessionDraft(changePhoneDraftKey, changePhoneForm, changePhoneDraftSavedAt)
|
||||
changePhoneModalVisible.value = true
|
||||
break
|
||||
case 'setPassword':
|
||||
handleSetPassword()
|
||||
break
|
||||
case 'changePassword':
|
||||
restoreSessionDraft(changePasswordDraftKey, changePasswordForm, changePasswordDraftSavedAt)
|
||||
changePasswordModalVisible.value = true
|
||||
break
|
||||
case 'deactivateAccount':
|
||||
handleDeactivateAccount()
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 处理设置密码
|
||||
/** 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('请输入手机号')
|
||||
return
|
||||
}
|
||||
|
||||
const phoneRegex = /^1[3-9]\d{9}$/
|
||||
if (!phoneRegex.test(bindPhoneForm.phone)) {
|
||||
message.error('手机号格式不正确')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await runWithGlobalLoading(() => userApi.sendVerificationCode({
|
||||
phone: bindPhoneForm.phone,
|
||||
sceneCode: 'USER_BIND_PHONE_SMS_CODE'
|
||||
}))
|
||||
message.success('验证码发送成功')
|
||||
startCountdown()
|
||||
} catch (error) {
|
||||
console.error('发送验证码失败:', error)
|
||||
message.error('发送验证码失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 发送修改手机号验证码
|
||||
/** 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('请输入新手机号')
|
||||
return
|
||||
}
|
||||
|
||||
const phoneRegex = /^1[3-9]\d{9}$/
|
||||
if (!phoneRegex.test(changePhoneForm.newPhone)) {
|
||||
message.error('手机号格式不正确')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await runWithGlobalLoading(() => userApi.sendVerificationCode({
|
||||
phone: changePhoneForm.newPhone,
|
||||
sceneCode: 'USER_CHANGE_PHONE_SMS_CODE'
|
||||
}))
|
||||
message.success('验证码发送成功')
|
||||
startCountdown()
|
||||
} catch (error) {
|
||||
console.error('发送验证码失败:', error)
|
||||
message.error('发送验证码失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 发送修改密码验证码
|
||||
/** 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('请先绑定手机号')
|
||||
return
|
||||
}
|
||||
|
||||
const phone = userInfo.value.phone
|
||||
const phoneRegex = /^1[3-9]\d{9}$/
|
||||
if (!phoneRegex.test(phone)) {
|
||||
message.error('手机号格式不正确')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await runWithGlobalLoading(() => userApi.sendVerificationCode({
|
||||
phone,
|
||||
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
|
||||
}))
|
||||
message.success('验证码发送成功')
|
||||
startCountdown()
|
||||
} catch (error) {
|
||||
console.error('发送验证码失败:', error)
|
||||
message.error('发送验证码失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 开始倒计时
|
||||
/** startCountdown is a local helper used by this page script. */
|
||||
const startCountdown = () => {
|
||||
countdown.value = 60
|
||||
const timer = setInterval(() => {
|
||||
countdown.value--
|
||||
if (countdown.value <= 0) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
// 处理绑定手机号提交
|
||||
/** 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('请填写完整信息')
|
||||
return
|
||||
}
|
||||
|
||||
bindPhoneLoading.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await userApi.bindPhone({
|
||||
phone: bindPhoneForm.phone,
|
||||
verificationCode: bindPhoneForm.verificationCode
|
||||
})
|
||||
await fetchUserInfo()
|
||||
})
|
||||
message.success('手机号绑定成功')
|
||||
handleClearBindPhoneDraft(false)
|
||||
bindPhoneModalVisible.value = false
|
||||
} catch (error: any) {
|
||||
console.error('绑定手机号失败:', error)
|
||||
message.error(error.message || '绑定手机号失败')
|
||||
} finally {
|
||||
bindPhoneLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 处理绑定手机号取消
|
||||
/** handleBindPhoneCancel is a local helper used by this page script. */
|
||||
const handleBindPhoneCancel = () => {
|
||||
bindPhoneModalVisible.value = false
|
||||
bindPhoneForm.phone = ''
|
||||
bindPhoneForm.verificationCode = ''
|
||||
}
|
||||
|
||||
// 处理修改手机号提交
|
||||
/** 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('请填写完整信息')
|
||||
return
|
||||
}
|
||||
|
||||
changePhoneLoading.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await userApi.updatePhone({
|
||||
oldPhone: userInfo.value.phone!,
|
||||
newPhone: changePhoneForm.newPhone,
|
||||
verificationCode: changePhoneForm.verificationCode
|
||||
})
|
||||
await fetchUserInfo()
|
||||
})
|
||||
message.success('手机号修改成功')
|
||||
handleClearChangePhoneDraft(false)
|
||||
changePhoneModalVisible.value = false
|
||||
} catch (error: any) {
|
||||
console.error('修改手机号失败:', error)
|
||||
message.error(error.message || '修改手机号失败')
|
||||
} finally {
|
||||
changePhoneLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 处理修改手机号取消
|
||||
/** handleChangePhoneCancel is a local helper used by this page script. */
|
||||
const handleChangePhoneCancel = () => {
|
||||
changePhoneModalVisible.value = false
|
||||
changePhoneForm.newPhone = ''
|
||||
changePhoneForm.verificationCode = ''
|
||||
}
|
||||
|
||||
// 处理修改密码提交
|
||||
/** 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('请填写完整信息')
|
||||
return
|
||||
}
|
||||
|
||||
if (changePasswordForm.password !== changePasswordForm.confirmPassword) {
|
||||
message.error('两次输入的密码不一致')
|
||||
return
|
||||
}
|
||||
|
||||
changePasswordLoading.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(() => userApi.updatePassword({
|
||||
password: changePasswordForm.password,
|
||||
verificationCode: changePasswordForm.verificationCode
|
||||
}))
|
||||
message.success('密码修改成功')
|
||||
handleClearChangePasswordDraft(false)
|
||||
changePasswordModalVisible.value = false
|
||||
// 清除需要设置密码的标识
|
||||
localStorage.removeItem('needSetPassword')
|
||||
hasPassword.value = true
|
||||
updateAccountSettings()
|
||||
} catch (error: any) {
|
||||
console.error('修改密码失败:', error)
|
||||
message.error(error.message || '修改密码失败')
|
||||
} finally {
|
||||
changePasswordLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 处理修改密码取消
|
||||
/** handleChangePasswordCancel is a local helper used by this page script. */
|
||||
const handleChangePasswordCancel = () => {
|
||||
changePasswordModalVisible.value = false
|
||||
changePasswordForm.verificationCode = ''
|
||||
changePasswordForm.password = ''
|
||||
changePasswordForm.confirmPassword = ''
|
||||
}
|
||||
|
||||
// 处理注销账号
|
||||
/** handleDeactivateAccount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleDeactivateAccount = async () => {
|
||||
Modal.confirm({
|
||||
title: '确认注销账号',
|
||||
content: '注销账号后,您的所有数据将被删除且无法恢复。确定要注销账号吗?',
|
||||
okText: '确认注销',
|
||||
okType: 'danger',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
await runWithGlobalLoading(async () => {
|
||||
try {
|
||||
await userApi.deactivateAccount()
|
||||
message.success('账号注销成功')
|
||||
} catch (error) {
|
||||
console.error('注销账号失败:', error)
|
||||
message.error('注销账号失败')
|
||||
} finally {
|
||||
// 无论成功或失败,都清除本地存储的用户信息
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
localStorage.removeItem('userInfo')
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
localStorage.removeItem('needSetPassword')
|
||||
localStorage.removeItem('userPermissions')
|
||||
sessionStorage.removeItem('accessToken')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
// 跳转到登录页
|
||||
router.push('/')
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 生命周期
|
||||
onMounted(() => {
|
||||
fetchUserInfo()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mobile-container {
|
||||
min-height: 100vh;
|
||||
background: var(--theme-page-bg);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px 15px;
|
||||
background: var(--theme-card-bg);
|
||||
border-bottom: 1px solid var(--theme-border);
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.back-btn,
|
||||
.empty {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.account-settings {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.status-tips {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.settings-card {
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.settings-card :deep(.ant-card-body) {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.setting-item {
|
||||
padding: 16px;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s;
|
||||
border-bottom: 1px solid var(--theme-border);
|
||||
}
|
||||
|
||||
.setting-item:hover {
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.setting-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.setting-item :deep(.ant-list-item-action) {
|
||||
margin-left: 8px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.setting-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.setting-item :deep(.ant-list-item-meta-title) {
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.setting-item :deep(.ant-list-item-meta-description) {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.password-tip {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
margin-top: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,141 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { LeftOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { afterSaleApi, orderApi } from '../api/order'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const order = ref<any | null>(null)
|
||||
|
||||
const orderId = computed(() => String(route.query.orderId || ''))
|
||||
const items = computed(() => Array.isArray(order.value?.items) ? order.value.items : [])
|
||||
const form = reactive({
|
||||
orderItemId: undefined as IdType | undefined,
|
||||
type: 'REFUND',
|
||||
reason: '',
|
||||
refundAmount: undefined as number | undefined
|
||||
})
|
||||
|
||||
const formatMoney = (value?: number | string) => {
|
||||
const amount = Number(value)
|
||||
return Number.isFinite(amount) ? `¥${amount.toFixed(2)}` : '¥0.00'
|
||||
}
|
||||
|
||||
const loadOrder = async () => {
|
||||
if (!orderId.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
order.value = await orderApi.getOrderDetail(orderId.value)
|
||||
const preferredItemId = String(route.query.orderItemId || '')
|
||||
const firstItem = items.value.find((item: any) => String(item.id) === preferredItemId) || items.value[0]
|
||||
form.orderItemId = firstItem?.id
|
||||
form.refundAmount = Number(order.value?.actualAmount || order.value?.totalAmount || 0)
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '订单信息加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (!orderId.value) {
|
||||
message.warning('缺少订单信息')
|
||||
return
|
||||
}
|
||||
if (!form.reason.trim()) {
|
||||
message.warning('请填写售后原因')
|
||||
return
|
||||
}
|
||||
submitting.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(() => afterSaleApi.apply({
|
||||
orderId: orderId.value,
|
||||
orderItemId: form.orderItemId,
|
||||
type: form.type,
|
||||
reason: form.reason.trim(),
|
||||
refundAmount: form.refundAmount
|
||||
}))
|
||||
message.success('售后申请已提交')
|
||||
router.replace({ path: '/after-sales', query: { orderId: orderId.value } })
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '售后申请提交失败')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadOrder)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="apply-page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>申请售后</h1>
|
||||
<a-button type="link" @click="router.push('/after-sales')">记录</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<section class="hero-card">
|
||||
<span>售后申请</span>
|
||||
<h2>{{ order?.orderNo || (orderId ? `订单 ${orderId}` : '选择订单') }}</h2>
|
||||
<p>{{ order ? `可申请金额 ${formatMoney(order.actualAmount || order.totalAmount)}` : '从订单详情或订单中心进入可自动带入订单信息' }}</p>
|
||||
</section>
|
||||
|
||||
<a-spin :spinning="loading">
|
||||
<a-empty v-if="!orderId" description="缺少订单参数">
|
||||
<a-button type="primary" @click="router.push('/orders')">选择订单</a-button>
|
||||
</a-empty>
|
||||
|
||||
<section v-else class="form-card">
|
||||
<a-form layout="vertical">
|
||||
<a-form-item label="订单项目">
|
||||
<a-select v-model:value="form.orderItemId" allow-clear placeholder="默认整单">
|
||||
<a-select-option v-for="item in items" :key="item.id" :value="item.id">
|
||||
{{ item.productTitle || `项目 ${item.id}` }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="售后类型" required>
|
||||
<a-select v-model:value="form.type">
|
||||
<a-select-option value="REFUND">退款</a-select-option>
|
||||
<a-select-option value="AFTER_SALE">售后服务</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="退款金额">
|
||||
<a-input-number v-model:value="form.refundAmount" :min="0" :step="0.01" style="width: 100%" />
|
||||
</a-form-item>
|
||||
<a-form-item label="原因说明" required>
|
||||
<a-textarea v-model:value="form.reason" :rows="5" :maxlength="300" placeholder="请说明退款或售后原因" />
|
||||
</a-form-item>
|
||||
<a-button type="primary" block :loading="submitting" @click="submit">提交申请</a-button>
|
||||
</a-form>
|
||||
</section>
|
||||
</a-spin>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.apply-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
|
||||
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
|
||||
.header h1 { margin: 0; font-size: 18px; }
|
||||
.content { padding: 16px 14px 32px; }
|
||||
.hero-card, .form-card { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
|
||||
.hero-card { padding: 22px; margin-bottom: 14px; background: var(--theme-gradient-soft); }
|
||||
.hero-card span { color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
|
||||
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
|
||||
.hero-card p { margin: 0; color: var(--text-secondary); line-height: 1.6; }
|
||||
.form-card { padding: 16px; }
|
||||
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
||||
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
||||
:deep(.ant-input:focus), :deep(.ant-input-focused), :deep(.ant-select-focused .ant-select-selector) { border-color: var(--theme-primary) !important; box-shadow: var(--theme-focus-shadow) !important; }
|
||||
</style>
|
||||
@@ -0,0 +1,122 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { LeftOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { afterSaleApi, type AfterSaleVO } from '../api/order'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const records = ref<AfterSaleVO[]>([])
|
||||
|
||||
const focusOrderId = computed(() => String(route.query.orderId || ''))
|
||||
const focusedRecords = computed(() => {
|
||||
if (!focusOrderId.value) return records.value
|
||||
return records.value.filter(item => String(item.orderId) === focusOrderId.value)
|
||||
})
|
||||
|
||||
const statusText = (status?: string) => {
|
||||
if (status === 'PENDING') return '审核中'
|
||||
if (status === 'APPROVED') return '已通过'
|
||||
if (status === 'REJECTED') return '已拒绝'
|
||||
return status || '处理中'
|
||||
}
|
||||
|
||||
const typeText = (type?: string) => type === 'REFUND' ? '退款' : (type || '售后')
|
||||
const formatMoney = (value?: number) => value === undefined || value === null ? '--' : `¥${Number(value).toFixed(2)}`
|
||||
const formatTime = (value?: string) => value ? String(value).replace('T', ' ').slice(0, 16) : '--'
|
||||
|
||||
const loadRecords = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const page = await afterSaleApi.listMy({ page: 1, size: 50 })
|
||||
records.value = page?.list || []
|
||||
} catch (error: any) {
|
||||
records.value = []
|
||||
message.error(error?.message || '售后记录加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadRecords)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="after-sales-page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>售后记录</h1>
|
||||
<a-button type="link" @click="loadRecords">刷新</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<section class="hero-card">
|
||||
<span>售后服务</span>
|
||||
<h2>{{ focusedRecords.length }} 条记录</h2>
|
||||
<p>{{ focusOrderId ? `订单 ${focusOrderId} 的售后进度` : '查看退款、售后审核与处理说明' }}</p>
|
||||
</section>
|
||||
|
||||
<a-spin :spinning="loading">
|
||||
<a-empty v-if="!focusedRecords.length" description="暂无售后记录">
|
||||
<a-button type="primary" @click="router.push('/orders')">查看订单</a-button>
|
||||
</a-empty>
|
||||
|
||||
<article v-for="item in focusedRecords" :key="item.id" class="record-card">
|
||||
<div class="record-head">
|
||||
<div>
|
||||
<span class="record-label">{{ typeText(item.type) }}</span>
|
||||
<h3>{{ item.afterSaleNo || `售后 ${item.id}` }}</h3>
|
||||
</div>
|
||||
<strong>{{ statusText(item.status) }}</strong>
|
||||
</div>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>订单</dt>
|
||||
<dd>{{ item.orderId }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>金额</dt>
|
||||
<dd>{{ formatMoney(item.refundAmount) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>提交时间</dt>
|
||||
<dd>{{ formatTime(item.createTime) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p v-if="item.reason">原因:{{ item.reason }}</p>
|
||||
<p v-if="item.auditReason">处理说明:{{ item.auditReason }}</p>
|
||||
<div class="actions">
|
||||
<a-button size="small" @click="router.push(`/orders/${item.orderId}`)">订单详情</a-button>
|
||||
<a-button size="small" @click="router.push({ path: '/service-progress', query: { orderId: String(item.orderId) } })">服务进度</a-button>
|
||||
</div>
|
||||
</article>
|
||||
</a-spin>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.after-sales-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
|
||||
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
|
||||
.header h1 { margin: 0; font-size: 18px; }
|
||||
.content { padding: 16px 14px 32px; }
|
||||
.hero-card, .record-card { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
|
||||
.hero-card { padding: 22px; margin-bottom: 14px; background: var(--theme-gradient-soft); }
|
||||
.hero-card span, .record-label { color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
|
||||
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
|
||||
.hero-card p, .record-card p { margin: 0; color: var(--text-secondary); line-height: 1.6; }
|
||||
.record-card { padding: 16px; margin-top: 14px; }
|
||||
.record-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.record-head h3 { margin: 6px 0 0; font-size: 17px; }
|
||||
.record-head strong { flex: 0 0 auto; padding: 6px 12px; border-radius: 999px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 12px; }
|
||||
dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 14px 0; }
|
||||
dt { color: var(--text-secondary); font-size: 12px; }
|
||||
dd { margin: 4px 0 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 700; }
|
||||
.actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
|
||||
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
||||
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
||||
</style>
|
||||
@@ -0,0 +1,288 @@
|
||||
<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'
|
||||
/**
|
||||
* Purpose: ArtistCalendarAppointment supports ArtistCalendarView.vue by holding or executing the artist calendar appointment page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { orderApi, type ArtistCalendarAppointment } from '@/api/order'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
|
||||
/**
|
||||
* Purpose: router supports ArtistCalendarView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
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)
|
||||
/**
|
||||
* Purpose: appointments supports ArtistCalendarView.vue by holding or executing the appointments page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const appointments = ref<ArtistCalendarAppointment[]>([])
|
||||
/**
|
||||
* Purpose: selected supports ArtistCalendarView.vue by holding or executing the selected page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const selected = ref<ArtistCalendarAppointment | null>(null)
|
||||
/** detailOpen is a reactive state variable used by the template and event handlers. */
|
||||
const detailOpen = ref(false)
|
||||
|
||||
/**
|
||||
* Purpose: todayKey supports ArtistCalendarView.vue by holding or executing the today key page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const 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) : ''
|
||||
/**
|
||||
* Purpose: localDateKey supports ArtistCalendarView.vue by holding or executing the local date key page or API role.
|
||||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
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: var(--theme-page-bg); color: var(--text-primary); }
|
||||
.calendar-header { position: sticky; top: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; background: color-mix(in srgb, var(--theme-card-bg) 94%, transparent); border-bottom: 1px solid var(--theme-border); 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: var(--text-secondary); }
|
||||
.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: var(--theme-border); }
|
||||
.summary-strip div { padding: 16px; background: var(--theme-card-bg); }
|
||||
.summary-strip span { display: block; color: var(--text-secondary); 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: var(--text-secondary); font-style: normal; font-size: 12px; }
|
||||
.day-line { position: relative; display: grid; gap: 10px; padding-left: 18px; border-left: 2px solid var(--theme-border); }
|
||||
.appointment-block { width: 100%; display: grid; gap: 5px; padding: 14px 16px; border: 1px solid var(--theme-border); border-radius: 8px; background: var(--theme-card-bg); text-align: left; color: var(--text-primary); box-shadow: 0 10px 22px color-mix(in srgb, var(--theme-primary) 8%, transparent); cursor: pointer; transition: transform .18s ease, border-color .18s ease; }
|
||||
.appointment-block:hover { transform: translateY(-2px); border-color: var(--theme-primary); }
|
||||
.appointment-block.is-completed { background: #f5fff7; border-color: #c8ead1; }
|
||||
.appointment-block .time { color: var(--theme-primary); font-weight: 700; }
|
||||
.appointment-block small { color: var(--text-secondary); }
|
||||
.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: var(--text-secondary); font-size: 12px; }
|
||||
dd { margin: -6px 0 4px; color: var(--text-primary); 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>
|
||||
@@ -0,0 +1,340 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, shallowRef, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
CalendarOutlined,
|
||||
LeftOutlined,
|
||||
RightOutlined,
|
||||
StarFilled,
|
||||
UserOutlined
|
||||
} from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { nailArtistApi, type NailArtistListItemVO } from '@/api/nail-artist'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const artists = ref<NailArtistListItemVO[]>([])
|
||||
const loading = shallowRef(false)
|
||||
const loadError = shallowRef('')
|
||||
|
||||
const shopId = computed(() => String(route.params.shopId || ''))
|
||||
const pageTitle = computed(() => String(route.query.shopName || '美甲师'))
|
||||
|
||||
const formatRating = (value?: number | string) => {
|
||||
const rating = Number(value || 0)
|
||||
return rating > 0 ? rating.toFixed(1) : '暂无'
|
||||
}
|
||||
|
||||
const parseSkillTags = (skills?: string) => {
|
||||
return String(skills || '')
|
||||
.split(/[,;,;、\s]+/)
|
||||
.map(tag => tag.trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 4)
|
||||
}
|
||||
|
||||
const formatWorkTime = (artist: NailArtistListItemVO) => {
|
||||
const start = String(artist.workStartTime || '').slice(0, 5)
|
||||
const end = String(artist.workEndTime || '').slice(0, 5)
|
||||
return start && end ? `${start}-${end}` : '到店确认'
|
||||
}
|
||||
|
||||
const displayName = (artist: NailArtistListItemVO) => artist.nickname || artist.identity || '美甲师'
|
||||
|
||||
const openArtist = (artist: NailArtistListItemVO) => {
|
||||
const artistId = artist.userId
|
||||
if (!artistId) {
|
||||
message.info('美甲师信息暂未完善')
|
||||
return
|
||||
}
|
||||
router.push(`/artist/${artistId}`)
|
||||
}
|
||||
|
||||
const loadArtists = async () => {
|
||||
if (!shopId.value) {
|
||||
loadError.value = '缺少店铺信息'
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
artists.value = await nailArtistApi.listByShopId(shopId.value)
|
||||
} catch (error) {
|
||||
loadError.value = error instanceof Error ? error.message : '美甲师列表加载失败'
|
||||
message.error(loadError.value)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(shopId, loadArtists, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="artist-list-page">
|
||||
<header class="artist-list-topbar">
|
||||
<a-button class="nav-button" type="text" aria-label="返回" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>{{ pageTitle }}</h1>
|
||||
<span class="topbar-count">{{ artists.length }} 位</span>
|
||||
</header>
|
||||
|
||||
<main class="artist-list-body">
|
||||
<a-spin :spinning="loading">
|
||||
<a-result v-if="loadError" status="warning" title="暂时无法查看美甲师" :sub-title="loadError">
|
||||
<template #extra>
|
||||
<a-button type="primary" @click="loadArtists">重试</a-button>
|
||||
</template>
|
||||
</a-result>
|
||||
|
||||
<template v-else>
|
||||
<section class="list-summary">
|
||||
<span>Artists</span>
|
||||
<h2>本店美甲师</h2>
|
||||
<p>选择熟悉的美甲师进入主页,查看作品、评价和近期可预约时间。</p>
|
||||
</section>
|
||||
|
||||
<div v-if="artists.length" class="artist-cards">
|
||||
<button
|
||||
v-for="artist in artists"
|
||||
:key="artist.userId || artist.id"
|
||||
class="artist-card"
|
||||
type="button"
|
||||
@click="openArtist(artist)"
|
||||
>
|
||||
<a-avatar :size="56" class="artist-avatar">
|
||||
<UserOutlined />
|
||||
</a-avatar>
|
||||
<div class="artist-copy">
|
||||
<div class="artist-heading">
|
||||
<strong>{{ displayName(artist) }}</strong>
|
||||
<span :class="['status-chip', artist.status === 1 ? 'status-chip--active' : '']">
|
||||
{{ artist.status === 1 ? '可预约' : '休息中' }}
|
||||
</span>
|
||||
</div>
|
||||
<p>{{ artist.signature || artist.identity || '专注细节与稳定出品' }}</p>
|
||||
<div class="artist-meta">
|
||||
<span><StarFilled /> {{ formatRating(artist.rating) }}</span>
|
||||
<span><CalendarOutlined /> {{ formatWorkTime(artist) }}</span>
|
||||
</div>
|
||||
<div v-if="parseSkillTags(artist.skills).length" class="tag-row">
|
||||
<span v-for="tag in parseSkillTags(artist.skills)" :key="tag">{{ tag }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<RightOutlined class="card-arrow" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<a-empty v-else class="empty-state" description="本店暂未配置可展示的美甲师" />
|
||||
</template>
|
||||
</a-spin>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.artist-list-page {
|
||||
min-height: 100vh;
|
||||
background:
|
||||
radial-gradient(circle at 18% 0%, rgba(232, 180, 184, 0.28), transparent 34%),
|
||||
var(--theme-page-bg);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.artist-list-topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
display: grid;
|
||||
grid-template-columns: 44px minmax(0, 1fr) 52px;
|
||||
align-items: center;
|
||||
height: 58px;
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 0 14px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
|
||||
border-bottom: 1px solid var(--theme-border);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.nav-button {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.artist-list-topbar h1 {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.topbar-count {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.artist-list-body {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 18px 14px 36px;
|
||||
}
|
||||
|
||||
.list-summary {
|
||||
padding: 20px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--theme-border) 78%, transparent);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 16px 40px rgba(124, 83, 87, 0.08);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.list-summary span {
|
||||
color: var(--theme-primary);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.list-summary h2 {
|
||||
margin: 8px 0;
|
||||
font-size: 22px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.list-summary p {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.artist-cards {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.artist-card {
|
||||
display: grid;
|
||||
grid-template-columns: 56px minmax(0, 1fr) 18px;
|
||||
gap: 14px;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
padding: 16px;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--theme-border) 82%, transparent);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 12px 28px rgba(124, 83, 87, 0.06);
|
||||
}
|
||||
|
||||
.artist-avatar {
|
||||
color: var(--theme-primary);
|
||||
background: var(--theme-primary-soft);
|
||||
border: 2px solid #fff;
|
||||
}
|
||||
|
||||
.artist-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.artist-heading {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.artist-heading strong {
|
||||
overflow: hidden;
|
||||
font-size: 17px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.status-chip {
|
||||
flex: 0 0 auto;
|
||||
padding: 4px 8px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-primary-soft));
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.status-chip--active {
|
||||
color: var(--theme-primary);
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.artist-copy p {
|
||||
display: -webkit-box;
|
||||
margin: 6px 0 10px;
|
||||
overflow: hidden;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
}
|
||||
|
||||
.artist-meta,
|
||||
.tag-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.artist-meta span {
|
||||
display: inline-flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.artist-meta svg {
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.tag-row {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.tag-row span {
|
||||
padding: 4px 8px;
|
||||
color: var(--theme-primary);
|
||||
font-size: 12px;
|
||||
background: var(--theme-primary-soft);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.card-arrow {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
margin-top: 48px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.artist-list-body {
|
||||
padding: 14px 12px 30px;
|
||||
}
|
||||
|
||||
.artist-card {
|
||||
grid-template-columns: 52px minmax(0, 1fr) 16px;
|
||||
gap: 12px;
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,748 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined :style="{ fontSize: '20px' }" />
|
||||
</a-button>
|
||||
<h1>美甲师订单</h1>
|
||||
<a-button v-if="showCalendarEntry" type="link" @click="router.push('/artist-calendar')">日历</a-button>
|
||||
<div v-else class="placeholder" />
|
||||
</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="SHOP">本店美甲师订单</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="0">确认价格中</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="jayu-cloud-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 filteredOrders"
|
||||
:key="order.id"
|
||||
:ref="(el: any) => setOrderRef(order.id, el)"
|
||||
class="order-card"
|
||||
:class="{ 'is-target': isTargetOrder(order.id) }"
|
||||
>
|
||||
<div class="order-head">
|
||||
<div class="order-title">
|
||||
<span>订单号:{{ order.orderNo }}</span>
|
||||
<span v-if="order.artistOrderSourceText" class="source-tag" :class="sourceClass(order.artistOrderSource)">
|
||||
{{ order.artistOrderSourceText }}
|
||||
</span>
|
||||
<span v-if="isQuoteOrder(order)" class="quote-tag">询价预约</span>
|
||||
</div>
|
||||
<span class="status" :class="statusClass(order.status)">{{ orderStatusText(order) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="customer-meta">
|
||||
<span>预约用户:{{ order.customerNickname || '用户' }}</span>
|
||||
<span v-if="order.customerPhoneMasked">联系电话:{{ order.customerPhoneMasked }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="isQuoteOrder(order)" class="quote-summary">
|
||||
<div class="quote-summary__head">
|
||||
<strong>{{ quoteStatusText(order) }}</strong>
|
||||
<span v-if="order.quoteExpireTime">过期时间:{{ order.quoteExpireTime }}</span>
|
||||
</div>
|
||||
<p v-if="order.customerRemark">客户备注:{{ order.customerRemark }}</p>
|
||||
<div class="quote-summary__flags">
|
||||
<span>客户{{ confirmationText(order.quoteUserConfirmed) }}</span>
|
||||
<span>门店{{ confirmationText(order.quoteShopConfirmed) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-for="item in order.items" :key="item.id" class="item">
|
||||
<div class="thumb">
|
||||
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" />
|
||||
<span v-else>{{ item.productTitle[0] }}</span>
|
||||
</div>
|
||||
<div class="main">
|
||||
<div class="title">{{ item.productTitle }}</div>
|
||||
<div class="line">{{ formatMoney(item.price) }} x {{ item.quantity }}</div>
|
||||
<div v-if="hasItemQuoteInfo(item)" class="line quote-line">
|
||||
参考 {{ formatMoney(item.referencePrice ?? item.price) }} · 报价 {{ formatMoney(item.quotedPrice) }} · 最终 {{ formatMoney(item.confirmedPrice) }}
|
||||
</div>
|
||||
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
|
||||
<div v-if="pendingArtistChangeForItem(order, item)" class="change-status">
|
||||
改派申请处理中:{{ pendingArtistChangeForItem(order, item)?.requestedArtistName || '新美甲师' }}
|
||||
</div>
|
||||
<div v-else-if="canRequestArtistChange(order, item)" class="change-action">
|
||||
<span>需要更换服务美甲师</span>
|
||||
<a-button size="small" @click="openArtistChangeModal(order, item)">申请改派</a-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<span>当前项目合计:{{ formatMoney(order.actualAmount) }}</span>
|
||||
<div class="footer-actions">
|
||||
<a-button v-if="canQuoteOrder(order)" size="small" type="primary" @click="openQuoteModal(order)">
|
||||
报价/确认价格
|
||||
</a-button>
|
||||
<a-button v-if="canComplete(order)" size="small" type="primary" @click="completeOrder(order.id)">
|
||||
完成服务
|
||||
</a-button>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
</main>
|
||||
|
||||
<a-modal
|
||||
v-model:open="artistChangeModalOpen"
|
||||
title="申请改派"
|
||||
:confirm-loading="artistChangeSubmitting"
|
||||
@ok="submitArtistChangeRequest"
|
||||
@cancel="closeArtistChangeModal"
|
||||
>
|
||||
<a-form layout="vertical">
|
||||
<a-form-item label="当前美甲师">
|
||||
<span>{{ artistChangeOptions?.currentArtistName || activeArtistChangeItem?.artistName || '未分配' }}</span>
|
||||
</a-form-item>
|
||||
<a-form-item label="新美甲师" required>
|
||||
<a-select
|
||||
v-model:value="artistChangeForm.requestedArtistId"
|
||||
:loading="artistChangeOptionsLoading"
|
||||
placeholder="请选择新的美甲师"
|
||||
>
|
||||
<a-select-option
|
||||
v-for="artist in selectableArtistOptions"
|
||||
:key="String(artist.artistId)"
|
||||
:value="artist.artistId"
|
||||
>
|
||||
{{ artist.artistName }}
|
||||
</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item label="改派原因" required>
|
||||
<a-textarea v-model:value="artistChangeForm.reason" :rows="4" :maxlength="300" placeholder="请说明申请改派的原因" />
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
|
||||
<a-modal
|
||||
v-model:open="quoteModalOpen"
|
||||
title="门店报价"
|
||||
:footer="null"
|
||||
@cancel="closeQuoteModal"
|
||||
>
|
||||
<a-form layout="vertical" class="quote-form">
|
||||
<div class="quote-form__items">
|
||||
<div v-for="item in activeQuoteOrder?.items || []" :key="item.id" class="quote-form__item">
|
||||
<div class="quote-form__meta">
|
||||
<strong>{{ item.productTitle || `订单项 ${item.id}` }}</strong>
|
||||
<span>参考价 {{ formatMoney(item.referencePrice ?? item.price) }}</span>
|
||||
</div>
|
||||
<a-input-number
|
||||
:value="quoteInputValue(item)"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
placeholder="报价"
|
||||
class="quote-form__input"
|
||||
@change="value => setQuoteInputValue(item, value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<a-form-item label="报价备注">
|
||||
<a-textarea v-model:value="quoteForm.remark" :rows="3" :maxlength="300" placeholder="填写给客户的报价说明" />
|
||||
</a-form-item>
|
||||
<div class="quote-form__actions">
|
||||
<a-button type="primary" :loading="quoteSubmitting" @click="submitQuote">提交报价</a-button>
|
||||
<a-button :loading="quoteConfirming" @click="confirmQuote">确认当前价格</a-button>
|
||||
</div>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 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 { userApi } from '@/api/user'
|
||||
import { orderApi } from '../api/order'
|
||||
import type { OrderArtistChangeOptionsVO, OrderArtistChangeRequestVO } from '../api/order'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { extractLegacyFileId, getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache'
|
||||
|
||||
/**
|
||||
* Purpose: router supports ArtistOrderView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
/**
|
||||
* Purpose: route supports ArtistOrderView.vue by holding or executing the route page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const route = useRoute()
|
||||
/**
|
||||
* Purpose: orders supports ArtistOrderView.vue by holding or executing the orders page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const orders = ref<any[]>([])
|
||||
/**
|
||||
* Purpose: orderRefs supports ArtistOrderView.vue by holding or executing the order refs page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const orderRefs = ref<Record<string, any>>({})
|
||||
/**
|
||||
* Purpose: showCalendarEntry supports ArtistOrderView.vue by holding or executing the show calendar entry page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const showCalendarEntry = ref(false)
|
||||
/**
|
||||
* Purpose: currentUserId supports ArtistOrderView.vue by holding or executing the current user id page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const currentUserId = ref<IdType>()
|
||||
const currentUserType = ref<number>()
|
||||
/**
|
||||
* Purpose: artistChangeModalOpen supports ArtistOrderView.vue by holding or executing the artist change modal open page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistChangeModalOpen = ref(false)
|
||||
const quoteModalOpen = ref(false)
|
||||
const quoteSubmitting = ref(false)
|
||||
const quoteConfirming = ref(false)
|
||||
/**
|
||||
* Purpose: artistChangeSubmitting supports ArtistOrderView.vue by holding or executing the artist change submitting page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistChangeSubmitting = ref(false)
|
||||
/**
|
||||
* Purpose: artistChangeOptionsLoading supports ArtistOrderView.vue by holding or executing the artist change options loading page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistChangeOptionsLoading = ref(false)
|
||||
/**
|
||||
* Purpose: artistChangeOptions supports ArtistOrderView.vue by holding or executing the artist change options page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistChangeOptions = ref<OrderArtistChangeOptionsVO | null>(null)
|
||||
/**
|
||||
* Purpose: activeArtistChangeOrder supports ArtistOrderView.vue by holding or executing the active artist change order page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const activeArtistChangeOrder = ref<any | null>(null)
|
||||
/**
|
||||
* Purpose: activeArtistChangeItem supports ArtistOrderView.vue by holding or executing the active artist change item page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const activeArtistChangeItem = ref<any | null>(null)
|
||||
const activeQuoteOrder = ref<any | null>(null)
|
||||
/**
|
||||
* Purpose: filters supports ArtistOrderView.vue by holding or executing the filters page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const filters = reactive({
|
||||
keyword: '',
|
||||
source: 'all',
|
||||
status: 'all' as 'all' | number,
|
||||
date: null as any,
|
||||
minAmount: undefined as number | undefined,
|
||||
maxAmount: undefined as number | undefined
|
||||
})
|
||||
/**
|
||||
* Purpose: artistChangeForm supports ArtistOrderView.vue by holding or executing the artist change form page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const artistChangeForm = reactive({
|
||||
requestedArtistId: undefined as IdType | undefined,
|
||||
reason: ''
|
||||
})
|
||||
const quoteForm = reactive({
|
||||
remark: '',
|
||||
items: {} as Record<string, 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.quoteStatusText,
|
||||
order.customerRemark,
|
||||
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' })
|
||||
}
|
||||
|
||||
const isQuoteOrder = (order: any) => Number(order?.status) === 0
|
||||
|
||||
const orderStatusText = (order: any) => order?.statusText || (isQuoteOrder(order) ? '确认价格中' : '--')
|
||||
|
||||
const quoteStatusText = (order: any) => order?.quoteStatusText || (isQuoteOrder(order) ? '确认价格中' : '--')
|
||||
|
||||
const confirmationText = (confirmed?: boolean) => confirmed ? '已确认' : '待确认'
|
||||
|
||||
const formatMoney = (value?: unknown) => {
|
||||
if (value === undefined || value === null || value === '') return '--'
|
||||
const amount = Number(value)
|
||||
return Number.isFinite(amount) ? `¥${amount.toFixed(2)}` : '--'
|
||||
}
|
||||
|
||||
const hasItemQuoteInfo = (item: any) => {
|
||||
return item?.referencePrice !== undefined || item?.quotedPrice !== undefined || item?.confirmedPrice !== undefined
|
||||
}
|
||||
|
||||
/** statusClass is a local helper used by this page script. */
|
||||
const statusClass = (status: number) => {
|
||||
const normalized = Number(status)
|
||||
if (normalized === 0) return 'quoting'
|
||||
if (normalized === 1) return 'pending'
|
||||
if (normalized === 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'
|
||||
if (source === 'SHOP') return 'source-shop'
|
||||
return 'source-service'
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: sameId supports ArtistOrderView.vue by holding or executing the same id page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const sameId = (left: unknown, right: unknown) => {
|
||||
return left !== undefined && left !== null && right !== undefined && right !== null && String(left) === String(right)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: pendingArtistChangeForItem supports ArtistOrderView.vue by holding or executing the pending artist change for item page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const pendingArtistChangeForItem = (order: any, item: any): OrderArtistChangeRequestVO | undefined => {
|
||||
const itemValue = item?.pendingArtistChangeRequest as OrderArtistChangeRequestVO | undefined
|
||||
if (itemValue) return itemValue
|
||||
const orderValue = order?.pendingArtistChangeRequest as OrderArtistChangeRequestVO | undefined
|
||||
if (!orderValue) return undefined
|
||||
return sameId(orderValue.orderItemId, item.id) || (order.items || []).length === 1 ? orderValue : undefined
|
||||
}
|
||||
|
||||
/** canComplete is a local helper used by this page script. */
|
||||
const canComplete = (order: any) => {
|
||||
return !isQuoteOrder(order) && Number(order.status) === 1 && order.artistOrderSource !== 'SELF' && order.artistOrderSource !== 'SHOP'
|
||||
}
|
||||
|
||||
const canQuoteOrder = (order: any) => {
|
||||
return currentUserType.value === 2 && isQuoteOrder(order) && order.artistOrderSource === 'SHOP'
|
||||
}
|
||||
|
||||
const resetQuoteForm = (order: any) => {
|
||||
quoteForm.remark = ''
|
||||
Object.keys(quoteForm.items).forEach(key => {
|
||||
delete quoteForm.items[key]
|
||||
})
|
||||
for (const item of order?.items || []) {
|
||||
if (item?.id === undefined || item?.id === null) continue
|
||||
quoteForm.items[String(item.id)] = Number(item.quotedPrice ?? item.confirmedPrice ?? item.referencePrice ?? item.price ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
const openQuoteModal = (order: any) => {
|
||||
if (!canQuoteOrder(order)) return
|
||||
activeQuoteOrder.value = order
|
||||
resetQuoteForm(order)
|
||||
quoteModalOpen.value = true
|
||||
}
|
||||
|
||||
const closeQuoteModal = () => {
|
||||
quoteModalOpen.value = false
|
||||
activeQuoteOrder.value = null
|
||||
resetQuoteForm(null)
|
||||
}
|
||||
|
||||
const quoteInputValue = (item: any) => {
|
||||
if (item?.id === undefined || item?.id === null) return undefined
|
||||
return quoteForm.items[String(item.id)]
|
||||
}
|
||||
|
||||
const setQuoteInputValue = (item: any, value: unknown) => {
|
||||
if (item?.id === undefined || item?.id === null) return
|
||||
const key = String(item.id)
|
||||
if (value === undefined || value === null || value === '') {
|
||||
quoteForm.items[key] = undefined
|
||||
return
|
||||
}
|
||||
quoteForm.items[key] = Number(value)
|
||||
}
|
||||
|
||||
const collectQuoteItems = (order: any) => {
|
||||
const orderItems = order?.items || []
|
||||
if (!orderItems.length) return null
|
||||
const items: Array<{ orderItemId: IdType; quotedPrice: number }> = []
|
||||
for (const item of orderItems) {
|
||||
if (item?.id === undefined || item?.id === null) return null
|
||||
const price = Number(quoteForm.items[String(item.id)])
|
||||
if (!Number.isFinite(price) || price <= 0) return null
|
||||
items.push({ orderItemId: item.id, quotedPrice: price })
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
const syncActiveQuoteOrder = (orderId: IdType, fallback?: any) => {
|
||||
if (!sameId(activeQuoteOrder.value?.id, orderId)) return
|
||||
activeQuoteOrder.value = orders.value.find(order => sameId(order.id, orderId)) || fallback || activeQuoteOrder.value
|
||||
resetQuoteForm(activeQuoteOrder.value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: canRequestArtistChange supports ArtistOrderView.vue by holding or executing the can request artist change page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const canRequestArtistChange = (order: any, item: any) => {
|
||||
const assignedToCurrentUser = !currentUserId.value || !item.artistId || sameId(item.artistId, currentUserId.value)
|
||||
return !isQuoteOrder(order) && Number(order.status) === 1 && item.id && assignedToCurrentUser && !pendingArtistChangeForItem(order, item)
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: selectableArtistOptions supports ArtistOrderView.vue by holding or executing the selectable artist options page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const selectableArtistOptions = computed(() => {
|
||||
const options = artistChangeOptions.value?.artists || []
|
||||
return options.filter(artist => !sameId(artist.artistId, artistChangeOptions.value?.currentArtistId))
|
||||
})
|
||||
|
||||
/** 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[]) || []
|
||||
for (const order of orders.value) {
|
||||
for (const item of order.items || []) {
|
||||
const imageId = extractLegacyFileId(item.productImage)
|
||||
if (!imageId) continue
|
||||
const cachedUrl = getCachedSignedImageUrlSync(imageId)
|
||||
if (cachedUrl) item.productImage = cachedUrl
|
||||
item.productImage = await getCachedSignedImageUrl(imageId)
|
||||
}
|
||||
}
|
||||
await scrollToTargetOrder()
|
||||
} catch {
|
||||
message.error('获取订单列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
/** loadCalendarAccess is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const loadCalendarAccess = async () => {
|
||||
showCalendarEntry.value = false
|
||||
try {
|
||||
const currentUser = await userApi.getUserInfo()
|
||||
currentUserId.value = currentUser.id
|
||||
currentUserType.value = currentUser.type
|
||||
if (currentUser.type === 3) {
|
||||
showCalendarEntry.value = true
|
||||
return
|
||||
}
|
||||
if (currentUser.type === 2) {
|
||||
const artistInfo = await userApi.getNailArtistInfo(currentUser.id).catch(() => null)
|
||||
showCalendarEntry.value = Number(artistInfo?.participateProduction) === 1
|
||||
}
|
||||
} catch {
|
||||
currentUserId.value = undefined
|
||||
currentUserType.value = undefined
|
||||
showCalendarEntry.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** handleRefreshClick is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||
const handleRefreshClick = async () => {
|
||||
await runWithGlobalLoading(() => loadOrders())
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: openArtistChangeModal supports ArtistOrderView.vue by holding or executing the open artist change modal page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const openArtistChangeModal = async (order: any, item: any) => {
|
||||
if (!canRequestArtistChange(order, item)) return
|
||||
activeArtistChangeOrder.value = order
|
||||
activeArtistChangeItem.value = item
|
||||
artistChangeOptions.value = null
|
||||
artistChangeForm.requestedArtistId = undefined
|
||||
artistChangeForm.reason = ''
|
||||
artistChangeModalOpen.value = true
|
||||
artistChangeOptionsLoading.value = true
|
||||
try {
|
||||
artistChangeOptions.value = await orderApi.getArtistChangeOptions(order.id, item.id)
|
||||
if (!selectableArtistOptions.value.length) {
|
||||
message.warning('暂无可改派的美甲师')
|
||||
}
|
||||
} catch {
|
||||
message.error('获取可改派美甲师失败')
|
||||
closeArtistChangeModal()
|
||||
} finally {
|
||||
artistChangeOptionsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: closeArtistChangeModal supports ArtistOrderView.vue by holding or executing the close artist change modal page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const closeArtistChangeModal = () => {
|
||||
artistChangeModalOpen.value = false
|
||||
activeArtistChangeOrder.value = null
|
||||
activeArtistChangeItem.value = null
|
||||
artistChangeOptions.value = null
|
||||
artistChangeForm.requestedArtistId = undefined
|
||||
artistChangeForm.reason = ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: submitArtistChangeRequest supports ArtistOrderView.vue by holding or executing the submit artist change request page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const submitArtistChangeRequest = async () => {
|
||||
if (!activeArtistChangeOrder.value || !activeArtistChangeItem.value) return
|
||||
if (!artistChangeForm.requestedArtistId) {
|
||||
message.warning('请选择新的美甲师')
|
||||
return
|
||||
}
|
||||
const reason = artistChangeForm.reason.trim()
|
||||
if (!reason) {
|
||||
message.warning('请填写改派原因')
|
||||
return
|
||||
}
|
||||
if (sameId(artistChangeForm.requestedArtistId, artistChangeOptions.value?.currentArtistId)) {
|
||||
message.warning('新美甲师不能与当前美甲师相同')
|
||||
return
|
||||
}
|
||||
artistChangeSubmitting.value = true
|
||||
try {
|
||||
await orderApi.requestArtistChange({
|
||||
orderId: activeArtistChangeOrder.value.id,
|
||||
orderItemId: activeArtistChangeItem.value.id,
|
||||
requestedArtistId: artistChangeForm.requestedArtistId,
|
||||
reason
|
||||
})
|
||||
message.success('改派申请已提交')
|
||||
closeArtistChangeModal()
|
||||
await loadOrders()
|
||||
} catch {
|
||||
message.error('提交改派申请失败')
|
||||
} finally {
|
||||
artistChangeSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const submitQuote = async () => {
|
||||
const order = activeQuoteOrder.value
|
||||
if (!order || !canQuoteOrder(order)) return
|
||||
const items = collectQuoteItems(order)
|
||||
if (!items) {
|
||||
message.warning('请填写每个项目的有效报价')
|
||||
return
|
||||
}
|
||||
quoteSubmitting.value = true
|
||||
try {
|
||||
let updatedOrder: any
|
||||
await runWithGlobalLoading(async () => {
|
||||
updatedOrder = await orderApi.submitShopQuote(order.id, {
|
||||
remark: quoteForm.remark.trim() || undefined,
|
||||
items
|
||||
})
|
||||
await loadOrders()
|
||||
})
|
||||
syncActiveQuoteOrder(order.id, updatedOrder)
|
||||
message.success('报价已提交')
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '提交报价失败')
|
||||
} finally {
|
||||
quoteSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const confirmQuote = async () => {
|
||||
const order = activeQuoteOrder.value
|
||||
if (!order || !canQuoteOrder(order)) return
|
||||
quoteConfirming.value = true
|
||||
try {
|
||||
let updatedOrder: any
|
||||
await runWithGlobalLoading(async () => {
|
||||
updatedOrder = await orderApi.confirmShopQuote(order.id)
|
||||
await loadOrders()
|
||||
})
|
||||
syncActiveQuoteOrder(order.id, updatedOrder)
|
||||
message.success('当前价格已确认')
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '确认当前价格失败')
|
||||
} finally {
|
||||
quoteConfirming.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** completeOrder is a local helper used by this page script. */
|
||||
const completeOrder = (orderId: IdType) => {
|
||||
Modal.confirm({
|
||||
title: '确认完成服务',
|
||||
content: '确定要完成这个订单吗?',
|
||||
onOk: async () => {
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await orderApi.completeArtistOrder(orderId)
|
||||
await loadOrders()
|
||||
})
|
||||
message.success('订单已完成')
|
||||
} catch (error: any) {
|
||||
message.error('完成订单失败')
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadCalendarAccess(), loadOrders()])
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page { min-height: 100vh; padding-top: 60px; background: linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)), var(--theme-background-image), var(--theme-page-bg); background-size: cover, cover, auto; background-position: center top; color: var(--text-primary); }
|
||||
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 10px 15px; background: rgba(255, 255, 255, 0.92); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
|
||||
.header h1 { margin: 0; font-size: 18px; color: var(--text-primary); }
|
||||
.placeholder { width: 40px; height: 40px; }
|
||||
.content { padding: 15px; }
|
||||
.filter-panel { display: grid; gap: 10px; margin-bottom: 12px; padding: 12px; border-radius: 14px; background: var(--theme-card-bg); border: 1px solid var(--theme-border); box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08); }
|
||||
.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: var(--text-secondary); font-size: 12px; }
|
||||
.order-card { margin-bottom: 12px; border-radius: 14px; border: 1px solid var(--theme-border); background: var(--theme-card-bg); box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08); }
|
||||
.order-card.is-target { border-color: var(--theme-primary); box-shadow: 0 0 0 2px rgba(198, 89, 125, .16); }
|
||||
.order-head, .footer { display: flex; align-items: center; justify-content: space-between; }
|
||||
.footer { gap: 10px; }
|
||||
.footer-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.order-head { margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid var(--theme-border); }
|
||||
.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: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.source-shop { background: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.source-self { background: var(--theme-primary-soft); color: var(--theme-accent); }
|
||||
.source-both { background: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.quote-tag { padding: 3px 8px; border-radius: 999px; background: rgba(22, 119, 255, .1); color: #1677ff; font-size: 12px; font-weight: 600; }
|
||||
.customer-meta { display: flex; flex-wrap: wrap; gap: 8px 16px; margin-bottom: 12px; color: var(--text-secondary); font-size: 13px; }
|
||||
.quote-summary { display: grid; gap: 8px; margin-bottom: 12px; padding: 10px; border-radius: 8px; background: rgba(22, 119, 255, .08); color: var(--text-secondary); font-size: 13px; }
|
||||
.quote-summary__head, .quote-summary__flags { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.quote-summary__head strong { color: #1677ff; }
|
||||
.quote-summary p { margin: 0; }
|
||||
.status { padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
|
||||
.quoting { background: rgba(22, 119, 255, .1); color: #1677ff; }
|
||||
.pending { background: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.completed { background: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.cancelled { background: var(--theme-primary-soft); color: var(--theme-accent); }
|
||||
.item { display: flex; gap: 12px; margin-bottom: 12px; }
|
||||
.thumb { width: 60px; height: 60px; border-radius: 10px; overflow: hidden; display: flex; align-items: center; justify-content: center; background: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.thumb img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.main { flex: 1; }
|
||||
.title { font-weight: 600; color: var(--text-primary); }
|
||||
.line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; }
|
||||
.quote-line { color: #1677ff; }
|
||||
.appointment { color: var(--theme-primary); }
|
||||
.change-status { margin-top: 8px; padding: 8px 10px; border-radius: 8px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 13px; }
|
||||
.change-action { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 8px; padding: 8px 10px; border-radius: 8px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 13px; }
|
||||
.quote-form { display: grid; gap: 12px; }
|
||||
.quote-form__items { display: grid; gap: 10px; }
|
||||
.quote-form__item { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px; border: 1px solid var(--theme-border); border-radius: 8px; background: var(--theme-primary-soft); }
|
||||
.quote-form__meta { display: grid; gap: 3px; min-width: 0; }
|
||||
.quote-form__meta strong { color: var(--text-primary); }
|
||||
.quote-form__meta span { color: var(--text-secondary); font-size: 12px; }
|
||||
.quote-form__input { width: 140px; flex: 0 0 auto; }
|
||||
.quote-form__actions { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
|
||||
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
||||
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.content {
|
||||
max-width: 980px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,951 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, shallowRef } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
CalendarOutlined,
|
||||
HeartOutlined,
|
||||
LeftOutlined,
|
||||
MessageOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
ShareAltOutlined,
|
||||
ShopOutlined,
|
||||
StarFilled,
|
||||
UserOutlined
|
||||
} from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
|
||||
import {
|
||||
getPublicImageFileIds,
|
||||
refreshPublicImageUrl,
|
||||
resolvePublicImageUrl,
|
||||
resolvePublicImageUrlsSync
|
||||
} from '@/utils/public-image-assets'
|
||||
import {
|
||||
nailArtistApi,
|
||||
type NailArtistAvailabilityVO,
|
||||
type NailArtistProfileVO,
|
||||
type NailArtistReviewVO,
|
||||
type NailArtistWorkVO
|
||||
} from '@/api/nail-artist'
|
||||
import { productApi, type ProductVO } from '@/api/product'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const profile = shallowRef<NailArtistProfileVO | null>(null)
|
||||
const workImageUrls = ref<Record<string, string>>({})
|
||||
const reviews = ref<NailArtistReviewVO[]>([])
|
||||
const availability = ref<NailArtistAvailabilityVO[]>([])
|
||||
const loading = shallowRef(false)
|
||||
const loadError = shallowRef('')
|
||||
const selectedDate = shallowRef('')
|
||||
const workFilter = shallowRef('全部')
|
||||
|
||||
const artistId = computed(() => String(route.params.id || ''))
|
||||
const artistName = computed(() => profile.value?.artistName || '美甲师')
|
||||
const ratingValue = computed(() => Number(profile.value?.rating || 0))
|
||||
const ratingText = computed(() => ratingValue.value > 0 ? ratingValue.value.toFixed(1) : '暂无')
|
||||
const serviceCountText = computed(() => formatCompactNumber(Number(profile.value?.serviceCount || 0)))
|
||||
const goodRateText = computed(() => ratingValue.value > 0 ? `${Math.min(99, Math.round((ratingValue.value / 5) * 100))}%` : '暂无')
|
||||
const works = computed<NailArtistWorkVO[]>(() => profile.value?.works || [])
|
||||
const styleTags = computed(() => profile.value?.styleTags?.filter(Boolean) || [])
|
||||
const firstWorkImage = computed(() => {
|
||||
const firstWork = works.value.find(work => getWorkImage(work) !== DEFAULT_PRODUCT_IMAGE)
|
||||
return firstWork ? getWorkImage(firstWork) : DEFAULT_PRODUCT_IMAGE
|
||||
})
|
||||
const workTimeText = computed(() => {
|
||||
const start = profile.value?.workStartTime?.slice(0, 5)
|
||||
const end = profile.value?.workEndTime?.slice(0, 5)
|
||||
return start && end ? `${start}-${end}` : '到店确认'
|
||||
})
|
||||
|
||||
const availabilityGroups = computed(() => {
|
||||
const groupMap = new Map<string, NailArtistAvailabilityVO[]>()
|
||||
availability.value
|
||||
.filter(slot => slot.available !== false)
|
||||
.forEach(slot => {
|
||||
const date = slot.dateText || String(slot.startTime || '').slice(0, 10)
|
||||
if (!date) return
|
||||
const slots = groupMap.get(date) || []
|
||||
slots.push(slot)
|
||||
groupMap.set(date, slots)
|
||||
})
|
||||
|
||||
return Array.from(groupMap.entries()).map(([date, slots]) => ({
|
||||
date,
|
||||
label: formatDateLabel(date),
|
||||
week: formatWeekLabel(date),
|
||||
slots
|
||||
}))
|
||||
})
|
||||
|
||||
const selectedDateSlots = computed(() => {
|
||||
return availabilityGroups.value.find(group => group.date === selectedDate.value)?.slots || []
|
||||
})
|
||||
|
||||
const workFilterOptions = computed(() => {
|
||||
const tags = new Set<string>()
|
||||
works.value.forEach(work => work.tags?.filter(Boolean).forEach(tag => tags.add(tag)))
|
||||
return ['全部', ...Array.from(tags).slice(0, 5)]
|
||||
})
|
||||
|
||||
const filteredWorks = computed(() => {
|
||||
if (workFilter.value === '全部') {
|
||||
return works.value
|
||||
}
|
||||
return works.value.filter(work => work.tags?.includes(workFilter.value))
|
||||
})
|
||||
|
||||
const PROFILE_WORK_LIMIT = 20
|
||||
|
||||
const certificationText = computed(() => {
|
||||
const identity = profile.value?.identity || '认证美甲师'
|
||||
const experience = Number(profile.value?.experience || 0)
|
||||
return experience > 0 ? `${identity} · ${experience} 年经验` : identity
|
||||
})
|
||||
|
||||
function formatCompactNumber(value: number) {
|
||||
if (value >= 1000) {
|
||||
return `${(value / 1000).toFixed(1)}k+`
|
||||
}
|
||||
return String(value || 0)
|
||||
}
|
||||
|
||||
function formatDateLabel(dateText: string) {
|
||||
const date = new Date(`${dateText}T00:00:00`)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return dateText
|
||||
}
|
||||
return `${date.getMonth() + 1}.${date.getDate()}`
|
||||
}
|
||||
|
||||
function formatWeekLabel(dateText: string) {
|
||||
const date = new Date(`${dateText}T00:00:00`)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return '可约'
|
||||
}
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const diffDays = Math.round((date.getTime() - today.getTime()) / 86400000)
|
||||
if (diffDays === 0) return '今天'
|
||||
if (diffDays === 1) return '明天'
|
||||
return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
|
||||
}
|
||||
|
||||
const formatDateTime = (value?: string) => {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
return value.replace('T', ' ').slice(0, 16)
|
||||
}
|
||||
|
||||
const roundedRating = (value?: number | string) => Math.round(Number(value || 0))
|
||||
|
||||
const openProduct = (work: NailArtistWorkVO) => {
|
||||
if (!work.id) {
|
||||
return
|
||||
}
|
||||
router.push(`/product/${work.id}`)
|
||||
}
|
||||
|
||||
const getWorkImage = (work: NailArtistWorkVO) => workImageUrls.value[String(work.id)] || work.coverImageUrl || DEFAULT_PRODUCT_IMAGE
|
||||
|
||||
const isArtistBookableForProduct = (product: ProductVO) => {
|
||||
const ids = String(product.bookableArtists || '')
|
||||
.split(',')
|
||||
.map(id => id.trim())
|
||||
.filter(Boolean)
|
||||
return ids.includes(artistId.value)
|
||||
}
|
||||
|
||||
const mapProductToWork = (product: ProductVO): NailArtistWorkVO & { imageFileIds?: string } => ({
|
||||
id: product.id,
|
||||
title: product.title || product.name,
|
||||
description: product.description,
|
||||
price: product.price,
|
||||
imageUrls: product.imageUrls,
|
||||
imageFileIds: product.imageFileIds,
|
||||
tags: product.tagList || product.tags?.split(/[;,,、]/).map(tag => tag.trim()).filter(Boolean),
|
||||
likeCount: product.likeCount,
|
||||
collectCount: product.collectCount
|
||||
})
|
||||
|
||||
const loadSupplementWorks = async (existingWorks: NailArtistWorkVO[]): Promise<NailArtistWorkVO[]> => {
|
||||
if (existingWorks.length >= PROFILE_WORK_LIMIT) {
|
||||
return existingWorks.slice(0, PROFILE_WORK_LIMIT)
|
||||
}
|
||||
|
||||
const existingIds = new Set(existingWorks.map(work => String(work.id)))
|
||||
const products = await productApi.getAllProducts().catch(() => [])
|
||||
const supplementWorks = products
|
||||
.filter(product => !existingIds.has(String(product.id)))
|
||||
.filter(product => !profile.value?.shopId || String(product.shopId || '') === String(profile.value.shopId))
|
||||
.filter(isArtistBookableForProduct)
|
||||
.slice(0, PROFILE_WORK_LIMIT - existingWorks.length)
|
||||
.map(mapProductToWork)
|
||||
|
||||
return [...existingWorks, ...supplementWorks]
|
||||
}
|
||||
|
||||
const loadWorkImages = async (nextWorks: NailArtistWorkVO[]) => {
|
||||
const entries = await Promise.all(nextWorks.map(async work => {
|
||||
const cachedUrls = resolvePublicImageUrlsSync(work as NailArtistWorkVO & Record<string, unknown>, '')
|
||||
const imageUrl = cachedUrls[0] || await resolvePublicImageUrl(work as NailArtistWorkVO & Record<string, unknown>, DEFAULT_PRODUCT_IMAGE)
|
||||
return [String(work.id), imageUrl] as const
|
||||
}))
|
||||
workImageUrls.value = Object.fromEntries(entries)
|
||||
}
|
||||
|
||||
const handleWorkImageError = async (work: NailArtistWorkVO) => {
|
||||
const fileId = getPublicImageFileIds(work as NailArtistWorkVO & Record<string, unknown>)[0]
|
||||
const imageUrl = fileId ? await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE
|
||||
workImageUrls.value = { ...workImageUrls.value, [String(work.id)]: imageUrl }
|
||||
}
|
||||
|
||||
const openShop = () => {
|
||||
if (!profile.value?.shopId) {
|
||||
message.info('门店信息暂未完善')
|
||||
return
|
||||
}
|
||||
router.push(`/shop/${profile.value.shopId}`)
|
||||
}
|
||||
|
||||
const handleBookNow = () => {
|
||||
const firstWork = works.value[0]
|
||||
if (firstWork?.id) {
|
||||
openProduct(firstWork)
|
||||
return
|
||||
}
|
||||
openShop()
|
||||
}
|
||||
|
||||
const handleConsult = () => {
|
||||
if (profile.value?.shopId) {
|
||||
router.push(`/shop/${profile.value.shopId}`)
|
||||
return
|
||||
}
|
||||
message.info('请先选择作品后联系门店')
|
||||
}
|
||||
|
||||
const handleShare = async () => {
|
||||
const shareTitle = `${artistName.value}的美甲师主页`
|
||||
const shareUrl = window.location.href
|
||||
try {
|
||||
if (navigator.share) {
|
||||
await navigator.share({ title: shareTitle, url: shareUrl })
|
||||
return
|
||||
}
|
||||
await navigator.clipboard.writeText(shareUrl)
|
||||
message.success('主页链接已复制')
|
||||
} catch {
|
||||
message.info('分享已取消')
|
||||
}
|
||||
}
|
||||
|
||||
const loadProfile = async () => {
|
||||
if (!artistId.value) {
|
||||
loadError.value = '缺少美甲师信息'
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
const [profileData, availabilityData, reviewData] = await Promise.all([
|
||||
nailArtistApi.getPublicProfile(artistId.value),
|
||||
nailArtistApi.getAvailability(artistId.value),
|
||||
nailArtistApi.listReviews(artistId.value)
|
||||
])
|
||||
profile.value = profileData
|
||||
availability.value = availabilityData || profileData.availability || []
|
||||
reviews.value = reviewData || profileData.reviews || []
|
||||
const nextWorks = await loadSupplementWorks(profileData.works || [])
|
||||
profile.value = { ...profileData, works: nextWorks }
|
||||
await loadWorkImages(nextWorks)
|
||||
selectedDate.value = availability.value[0]?.dateText || String(availability.value[0]?.startTime || '').slice(0, 10)
|
||||
} catch (error) {
|
||||
loadError.value = error instanceof Error ? error.message : '美甲师个人页加载失败'
|
||||
message.error(loadError.value)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadProfile)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="artist-profile">
|
||||
<header class="artist-topbar">
|
||||
<a-button type="text" class="icon-btn" aria-label="返回" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>美甲师</h1>
|
||||
<a-button type="text" class="icon-btn" aria-label="分享" @click="handleShare">
|
||||
<ShareAltOutlined />
|
||||
</a-button>
|
||||
</header>
|
||||
|
||||
<main class="artist-body">
|
||||
<a-spin :spinning="loading">
|
||||
<a-result v-if="loadError" status="warning" title="暂时无法查看个人页" :sub-title="loadError">
|
||||
<template #extra>
|
||||
<a-button type="primary" @click="loadProfile">重试</a-button>
|
||||
</template>
|
||||
</a-result>
|
||||
|
||||
<template v-else-if="profile">
|
||||
<section class="profile-card">
|
||||
<img class="profile-glow-image" :src="firstWorkImage" alt="" aria-hidden="true" />
|
||||
<div class="avatar-wrap">
|
||||
<a-avatar :size="112" :src="profile.avatar">
|
||||
<UserOutlined />
|
||||
</a-avatar>
|
||||
<span class="top-badge">TOP 1%</span>
|
||||
</div>
|
||||
<h2>{{ artistName }}</h2>
|
||||
<div class="rating-line">
|
||||
<span class="star-row">
|
||||
<StarFilled v-for="star in 5" :key="star" :class="{ active: star <= roundedRating(profile.rating) }" />
|
||||
</span>
|
||||
<strong>{{ ratingText }}</strong>
|
||||
<span>{{ reviews.length }} 条评价</span>
|
||||
</div>
|
||||
<p>{{ profile.signature || profile.identity || '专注细节与稳定出品,让每一次指尖细节都更贴合你的风格。' }}</p>
|
||||
<button type="button" class="shop-link" @click="openShop">
|
||||
<ShopOutlined />
|
||||
<span>{{ profile.shopName || '门店待确认' }}</span>
|
||||
</button>
|
||||
<div class="style-tags">
|
||||
<span v-for="tag in styleTags" :key="tag">{{ tag }}</span>
|
||||
<span v-if="!styleTags.length">风格待补充</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="stats-section">
|
||||
<div class="stat-card">
|
||||
<strong>{{ serviceCountText }}</strong>
|
||||
<span>累计服务</span>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<strong>{{ goodRateText }}</strong>
|
||||
<span>好评率</span>
|
||||
</div>
|
||||
<div class="cert-card">
|
||||
<SafetyCertificateOutlined />
|
||||
<div>
|
||||
<span>认证资质</span>
|
||||
<strong>{{ certificationText }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="content-section">
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<span>Schedule</span>
|
||||
<h3>可预约时间</h3>
|
||||
</div>
|
||||
<small>{{ workTimeText }}</small>
|
||||
</div>
|
||||
<div v-if="availabilityGroups.length" class="date-strip">
|
||||
<button
|
||||
v-for="group in availabilityGroups"
|
||||
:key="group.date"
|
||||
type="button"
|
||||
:class="['date-card', { active: selectedDate === group.date }]"
|
||||
@click="selectedDate = group.date"
|
||||
>
|
||||
<span>{{ group.week }}</span>
|
||||
<strong>{{ group.label }}</strong>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="selectedDateSlots.length" class="time-grid">
|
||||
<button v-for="slot in selectedDateSlots" :key="slot.startTime" type="button" class="time-chip">
|
||||
{{ slot.timeText }}
|
||||
</button>
|
||||
</div>
|
||||
<a-empty v-else description="近期暂未放出可预约时间" />
|
||||
</section>
|
||||
|
||||
<section class="content-section">
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<span>Portfolio</span>
|
||||
<h3>作品集</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="workFilterOptions.length > 1" class="filter-row">
|
||||
<button
|
||||
v-for="option in workFilterOptions"
|
||||
:key="option"
|
||||
type="button"
|
||||
:class="['filter-chip', { active: workFilter === option }]"
|
||||
@click="workFilter = option"
|
||||
>
|
||||
{{ option }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="filteredWorks.length" class="work-grid">
|
||||
<button v-for="work in filteredWorks" :key="work.id" type="button" class="work-card" @click="openProduct(work)">
|
||||
<img :src="getWorkImage(work)" :alt="work.title || '作品'" loading="lazy" decoding="async" @error="handleWorkImageError(work)" />
|
||||
<span>{{ work.title || '美甲作品' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<a-empty v-else description="作品正在整理中" />
|
||||
</section>
|
||||
|
||||
<section class="content-section review-section">
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<span>Reviews</span>
|
||||
<h3>用户评价</h3>
|
||||
</div>
|
||||
<small>{{ reviews.length }} 条</small>
|
||||
</div>
|
||||
<div v-if="reviews.length" class="review-list">
|
||||
<article v-for="review in reviews" :key="review.id" class="review-item">
|
||||
<div class="review-top">
|
||||
<a-avatar :size="44" :src="review.customerAvatar">
|
||||
<UserOutlined />
|
||||
</a-avatar>
|
||||
<div class="review-author">
|
||||
<strong>{{ review.customerName || '匿名用户' }}</strong>
|
||||
<span class="star-row">
|
||||
<StarFilled v-for="star in 5" :key="star" :class="{ active: star <= roundedRating(review.rating) }" />
|
||||
</span>
|
||||
</div>
|
||||
<time>{{ formatDateTime(review.submittedAt) }}</time>
|
||||
</div>
|
||||
<p>{{ review.content || '这位用户没有填写文字评价' }}</p>
|
||||
<div v-if="review.imageUrls?.length" class="review-images">
|
||||
<img v-for="url in review.imageUrls" :key="url" :src="url" alt="评价图片" loading="lazy" decoding="async" />
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<a-empty v-else description="还没有公开评价" />
|
||||
</section>
|
||||
</template>
|
||||
</a-spin>
|
||||
</main>
|
||||
|
||||
<footer v-if="profile" class="booking-bar">
|
||||
<button type="button" class="bar-icon-btn" @click="handleConsult">
|
||||
<MessageOutlined />
|
||||
<span>咨询</span>
|
||||
</button>
|
||||
<button type="button" class="bar-icon-btn" @click="message.info('收藏功能即将开放')">
|
||||
<HeartOutlined />
|
||||
<span>收藏</span>
|
||||
</button>
|
||||
<button type="button" class="book-btn" @click="handleBookNow">
|
||||
<CalendarOutlined />
|
||||
<span>立即预约</span>
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.artist-profile {
|
||||
min-height: 100vh;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(232, 180, 184, 0.24), rgba(255, 248, 244, 0) 260px),
|
||||
var(--theme-page-bg);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.artist-topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 30;
|
||||
display: grid;
|
||||
grid-template-columns: 44px minmax(0, 1fr) 44px;
|
||||
align-items: center;
|
||||
height: 62px;
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 0 14px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--theme-border) 72%, transparent);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.artist-topbar h1 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.artist-body {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 22px 14px 116px;
|
||||
}
|
||||
|
||||
.profile-card,
|
||||
.content-section,
|
||||
.stat-card,
|
||||
.cert-card,
|
||||
.review-item {
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--theme-border) 72%, transparent);
|
||||
box-shadow: 0 18px 48px rgba(124, 83, 87, 0.08);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.profile-card {
|
||||
position: relative;
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
padding: 34px 20px 24px;
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
border-radius: 24px;
|
||||
}
|
||||
|
||||
.profile-glow-image {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 170px;
|
||||
object-fit: cover;
|
||||
opacity: 0.18;
|
||||
filter: blur(14px);
|
||||
transform: scale(1.08);
|
||||
}
|
||||
|
||||
.avatar-wrap {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.avatar-wrap :deep(.ant-avatar) {
|
||||
color: var(--theme-primary);
|
||||
background: var(--theme-primary-soft);
|
||||
border: 4px solid #fff;
|
||||
box-shadow: 0 16px 36px rgba(124, 83, 87, 0.18);
|
||||
}
|
||||
|
||||
.top-badge {
|
||||
position: absolute;
|
||||
right: -8px;
|
||||
bottom: 8px;
|
||||
padding: 5px 8px;
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
background: var(--theme-primary);
|
||||
border: 2px solid #fff;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.profile-card h2 {
|
||||
position: relative;
|
||||
margin: 18px 0 8px;
|
||||
font-size: 26px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.rating-line {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rating-line strong {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.star-row {
|
||||
display: inline-flex;
|
||||
gap: 2px;
|
||||
color: color-mix(in srgb, var(--theme-border) 70%, #fff);
|
||||
}
|
||||
|
||||
.star-row .active {
|
||||
color: #b88935;
|
||||
}
|
||||
|
||||
.profile-card p {
|
||||
position: relative;
|
||||
max-width: 640px;
|
||||
margin: 14px 0;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.shop-link {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
max-width: 100%;
|
||||
padding: 8px 12px;
|
||||
color: var(--theme-primary);
|
||||
cursor: pointer;
|
||||
background: var(--theme-primary-soft);
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.shop-link span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.style-tags {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.style-tags span,
|
||||
.filter-chip {
|
||||
padding: 7px 11px;
|
||||
color: var(--theme-primary);
|
||||
font-size: 12px;
|
||||
background: color-mix(in srgb, var(--theme-primary-soft) 86%, #fff);
|
||||
border: 1px solid color-mix(in srgb, var(--theme-primary) 18%, transparent);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.stats-section {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
min-height: 96px;
|
||||
padding: 18px;
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.stat-card strong {
|
||||
color: var(--theme-primary);
|
||||
font-size: 24px;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.stat-card span,
|
||||
.cert-card span {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.cert-card {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.cert-card svg {
|
||||
color: #b88935;
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.cert-card div {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cert-card strong {
|
||||
overflow: hidden;
|
||||
font-size: 15px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content-section {
|
||||
margin-top: 22px;
|
||||
padding: 18px;
|
||||
border-radius: 22px;
|
||||
}
|
||||
|
||||
.section-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.section-head span {
|
||||
color: var(--theme-primary);
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.section-head h3 {
|
||||
margin: 4px 0 0;
|
||||
font-size: 19px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.section-head small {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.date-strip {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.date-card {
|
||||
display: grid;
|
||||
flex: 0 0 80px;
|
||||
gap: 8px;
|
||||
place-items: center;
|
||||
min-height: 92px;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 72%, var(--theme-primary-soft));
|
||||
border: 1px solid color-mix(in srgb, var(--theme-border) 72%, transparent);
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.date-card strong {
|
||||
color: var(--text-primary);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.date-card.active {
|
||||
color: #fff;
|
||||
background: var(--theme-primary);
|
||||
border-color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.date-card.active strong {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.time-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.time-chip {
|
||||
min-height: 44px;
|
||||
color: var(--theme-primary);
|
||||
font-weight: 700;
|
||||
cursor: default;
|
||||
background: var(--theme-primary-soft);
|
||||
border: 1px solid color-mix(in srgb, var(--theme-primary) 18%, transparent);
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.filter-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
overflow-x: auto;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.filter-chip {
|
||||
flex: 0 0 auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.filter-chip.active {
|
||||
color: #fff;
|
||||
background: var(--theme-primary);
|
||||
}
|
||||
|
||||
.work-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.work-card {
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
background: var(--theme-primary-soft);
|
||||
border: 0;
|
||||
border-radius: 22px;
|
||||
aspect-ratio: 3 / 4;
|
||||
}
|
||||
|
||||
.work-card img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.work-card::after {
|
||||
position: absolute;
|
||||
inset: auto 0 0;
|
||||
height: 46%;
|
||||
content: "";
|
||||
background: linear-gradient(180deg, transparent, rgba(31, 27, 23, 0.62));
|
||||
}
|
||||
|
||||
.work-card span {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
left: 12px;
|
||||
z-index: 1;
|
||||
overflow: hidden;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
text-align: left;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.review-list {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.review-item {
|
||||
padding: 14px;
|
||||
border-radius: 18px;
|
||||
}
|
||||
|
||||
.review-top {
|
||||
display: grid;
|
||||
grid-template-columns: 44px minmax(0, 1fr) auto;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.review-author {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.review-author strong {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.review-top time {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.review-item p {
|
||||
margin: 12px 0 0;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.7;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.review-images {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.review-images img {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
object-fit: cover;
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.booking-bar {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 40;
|
||||
display: grid;
|
||||
grid-template-columns: 64px 64px minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 12px 14px max(12px, env(safe-area-inset-bottom));
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
|
||||
border-top: 1px solid var(--theme-border);
|
||||
box-shadow: 0 -16px 40px rgba(124, 83, 87, 0.1);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.bar-icon-btn,
|
||||
.book-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 48px;
|
||||
cursor: pointer;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.bar-icon-btn {
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
color: var(--theme-primary);
|
||||
font-size: 11px;
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.book-btn {
|
||||
gap: 8px;
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
background: var(--theme-primary);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.artist-body {
|
||||
padding: 18px 12px 112px;
|
||||
}
|
||||
|
||||
.profile-card {
|
||||
padding: 30px 16px 22px;
|
||||
}
|
||||
|
||||
.profile-card h2 {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.content-section {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.time-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,446 @@
|
||||
<template>
|
||||
<div class="mobile-container">
|
||||
<header class="header">
|
||||
<a-button type="text" class="back-btn" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>我的优惠券</h1>
|
||||
<div class="placeholder"></div>
|
||||
</header>
|
||||
|
||||
<div class="coupon-section">
|
||||
<a-card :bordered="false" class="filter-card">
|
||||
<a-segmented
|
||||
v-model:value="activeFilter"
|
||||
:options="filterOptions"
|
||||
class="filter-segmented"
|
||||
/>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="loading" :bordered="false" class="content-card">
|
||||
<a-skeleton :paragraph="{ rows: 3 }" />
|
||||
</a-card>
|
||||
|
||||
<a-card v-else-if="coupons.length === 0" :bordered="false" class="content-card">
|
||||
<a-empty description="暂无优惠券">
|
||||
<a-button type="primary">去领取</a-button>
|
||||
</a-empty>
|
||||
</a-card>
|
||||
|
||||
<div v-else class="coupon-list">
|
||||
<a-card
|
||||
v-for="coupon in filteredCoupons"
|
||||
:key="coupon.id"
|
||||
class="coupon-card"
|
||||
:class="{ 'expired': coupon.status === 3 }"
|
||||
>
|
||||
<div class="coupon-content">
|
||||
<div class="coupon-value">
|
||||
{{ coupon.couponType === 1 ? `${coupon.discountValue}折` : `¥${coupon.reduceAmount}` }}
|
||||
</div>
|
||||
<div class="coupon-info">
|
||||
<div class="coupon-name">{{ coupon.couponName }}</div>
|
||||
<div class="coupon-condition" v-if="coupon.couponType === 2">
|
||||
满{{ coupon.minAmount }}元可用
|
||||
</div>
|
||||
<div class="coupon-time">
|
||||
{{ formatDate(coupon.startTime) }} 至 {{ formatDate(coupon.endTime) }}
|
||||
</div>
|
||||
<div :class="['coupon-status', getStatusClass(coupon.status)]">
|
||||
{{ coupon.statusName }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</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'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { couponApi } from '@/api/coupon'
|
||||
|
||||
/**
|
||||
* Purpose: router supports CouponView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
|
||||
/** loading is a reactive state variable used by the template and event handlers. */
|
||||
const loading = ref(false)
|
||||
/**
|
||||
* Purpose: coupons supports CouponView.vue by holding or executing the coupons page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const coupons = ref<any[]>([])
|
||||
/** activeFilter is a reactive state variable used by the template and event handlers. */
|
||||
const activeFilter = ref('all')
|
||||
|
||||
/**
|
||||
* Purpose: filterOptions supports CouponView.vue by holding or executing the filter options page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const filterOptions = [
|
||||
{ label: '全部', value: 'all' },
|
||||
{ label: '未使用', value: 'available' },
|
||||
{ label: '已使用', value: 'used' },
|
||||
{ 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
|
||||
} else if (activeFilter.value === 'available') {
|
||||
return coupons.value.filter(coupon => coupon.status === 1)
|
||||
} else if (activeFilter.value === 'used') {
|
||||
return coupons.value.filter(coupon => coupon.status === 2)
|
||||
} else if (activeFilter.value === 'expired') {
|
||||
return coupons.value.filter(coupon => coupon.status === 3)
|
||||
}
|
||||
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 {
|
||||
const response = await couponApi.listUserCoupons() as any
|
||||
coupons.value = response || []
|
||||
} catch (error) {
|
||||
console.error('获取优惠券列表失败:', error)
|
||||
message.error('获取优惠券列表失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** getStatusClass is a local helper used by this page script. */
|
||||
const getStatusClass = (status: number) => {
|
||||
switch (status) {
|
||||
case 1:
|
||||
return 'available'
|
||||
case 2:
|
||||
return 'used'
|
||||
case 3:
|
||||
return 'expired'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** formatDate is a local helper used by this page script. */
|
||||
const formatDate = (dateString: string) => {
|
||||
if (!dateString) return ''
|
||||
const date = new Date(dateString)
|
||||
return date.toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadCoupons()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mobile-container {
|
||||
padding-top: 60px;
|
||||
min-height: 100vh;
|
||||
background:
|
||||
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
|
||||
var(--theme-background-image),
|
||||
var(--theme-page-bg);
|
||||
background-size: cover, cover, auto;
|
||||
background-position: center top;
|
||||
}
|
||||
|
||||
.header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
height: 60px;
|
||||
padding: 10px 15px;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
border-bottom: 1px solid var(--theme-border);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.placeholder {
|
||||
width: 40px;
|
||||
}
|
||||
|
||||
.coupon-section {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.filter-card {
|
||||
border-radius: 14px;
|
||||
margin-bottom: 15px;
|
||||
background: var(--theme-card-bg);
|
||||
border: 1px solid var(--theme-border);
|
||||
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
|
||||
}
|
||||
|
||||
.filter-segmented {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.content-card {
|
||||
border-radius: 14px;
|
||||
background: var(--theme-card-bg);
|
||||
border: 1px solid var(--theme-border);
|
||||
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
.coupon-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.coupon-card {
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
background: var(--theme-gradient-soft);
|
||||
border: 1px solid var(--theme-border);
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
|
||||
}
|
||||
|
||||
.coupon-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 18px 44px rgba(122, 67, 88, 0.12);
|
||||
}
|
||||
|
||||
.coupon-card.expired {
|
||||
opacity: 0.66;
|
||||
background: var(--theme-card-bg);
|
||||
}
|
||||
|
||||
.coupon-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.coupon-value {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: var(--theme-primary);
|
||||
padding: 20px;
|
||||
background: var(--theme-primary-soft);
|
||||
border-radius: 8px;
|
||||
min-width: 100px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.coupon-card.expired .coupon-value {
|
||||
color: var(--text-secondary);
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.coupon-info {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.coupon-name {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.coupon-condition {
|
||||
font-size: 12px;
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.coupon-time {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.coupon-status {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
padding: 2px 8px;
|
||||
border-radius: 8px;
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.coupon-status.available {
|
||||
background: var(--theme-primary-soft);
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.coupon-status.used {
|
||||
background: var(--theme-primary-soft);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.coupon-status.expired {
|
||||
background: var(--theme-primary-soft);
|
||||
color: var(--theme-accent);
|
||||
}
|
||||
|
||||
:deep(.ant-segmented) {
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
:deep(.ant-segmented-item-selected) {
|
||||
background: var(--theme-primary);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
:deep(.ant-btn-primary) {
|
||||
background: var(--theme-primary);
|
||||
border-color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.mobile-container {
|
||||
padding-top: 68px;
|
||||
background:
|
||||
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 26%, transparent), transparent 32%),
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 78%, transparent), var(--theme-page-bg));
|
||||
}
|
||||
|
||||
.header {
|
||||
height: 64px;
|
||||
padding: 12px 18px 10px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 17px;
|
||||
font-weight: 820;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent);
|
||||
}
|
||||
|
||||
.coupon-section {
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.filter-card,
|
||||
.content-card {
|
||||
border-radius: 22px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
|
||||
box-shadow: 0 18px 40px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
|
||||
}
|
||||
|
||||
.coupon-list {
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.coupon-card {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 24px;
|
||||
background:
|
||||
linear-gradient(135deg, color-mix(in srgb, var(--theme-card-bg) 88%, transparent), color-mix(in srgb, var(--theme-primary) 20%, var(--theme-card-bg)));
|
||||
box-shadow: 0 20px 42px color-mix(in srgb, var(--theme-neutral) 9%, transparent);
|
||||
}
|
||||
|
||||
.coupon-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 112px;
|
||||
width: 1px;
|
||||
background: linear-gradient(var(--theme-border) 52%, transparent 0);
|
||||
background-size: 1px 12px;
|
||||
}
|
||||
|
||||
.coupon-content {
|
||||
gap: 18px;
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.coupon-value {
|
||||
min-width: 78px;
|
||||
padding: 16px 8px;
|
||||
border-radius: 18px;
|
||||
color: var(--theme-primary-action);
|
||||
background: color-mix(in srgb, var(--theme-primary) 24%, var(--theme-card-bg));
|
||||
font-family: Georgia, 'Times New Roman', serif;
|
||||
}
|
||||
|
||||
.coupon-name {
|
||||
font-weight: 820;
|
||||
}
|
||||
|
||||
.coupon-condition,
|
||||
.coupon-status.available {
|
||||
color: var(--theme-primary-action);
|
||||
}
|
||||
|
||||
:deep(.ant-segmented) {
|
||||
width: 100%;
|
||||
padding: 4px;
|
||||
border-radius: 16px;
|
||||
background: color-mix(in srgb, var(--theme-primary) 16%, var(--theme-card-bg));
|
||||
}
|
||||
|
||||
:deep(.ant-segmented-item) {
|
||||
border-radius: 13px;
|
||||
}
|
||||
|
||||
:deep(.ant-segmented-item-selected) {
|
||||
background: var(--theme-card-bg);
|
||||
color: var(--theme-primary-action);
|
||||
box-shadow: 0 10px 20px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
|
||||
}
|
||||
|
||||
:deep(.ant-btn-primary) {
|
||||
border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.coupon-section {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,96 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { LeftOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { userApi, type ContactInfoVO } from '@/api/user'
|
||||
import { BRAND_CONFIG } from '@/config/brand'
|
||||
|
||||
const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const contact = ref<ContactInfoVO | null>(null)
|
||||
|
||||
const loadContact = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
contact.value = await userApi.getPlatformContact()
|
||||
} catch (error: any) {
|
||||
contact.value = null
|
||||
message.warning(error?.message || '暂时无法加载客服信息')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadContact)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="help-page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>帮助与客服</h1>
|
||||
<a-button type="link" @click="loadContact">刷新</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<section class="hero-card">
|
||||
<span>{{ BRAND_CONFIG.appName }}客服</span>
|
||||
<h2>帮助与客服</h2>
|
||||
<p>订单、预约、售后和账号问题都可以从这里继续处理。</p>
|
||||
</section>
|
||||
|
||||
<a-spin :spinning="loading">
|
||||
<section class="section-card">
|
||||
<h3>平台联系信息</h3>
|
||||
<p v-if="contact?.contactName">{{ contact.contactName }} {{ contact.roleLabel || '' }}</p>
|
||||
<p v-if="contact?.phoneAvailable && contact.phone">电话:{{ contact.phone }}</p>
|
||||
<p v-if="contact?.wechatAvailable && contact.wechatId">微信:{{ contact.wechatId }}</p>
|
||||
<p v-if="contact?.platformContactText">{{ contact.platformContactText }}</p>
|
||||
<p v-if="!contact">暂无可展示的客服信息,请稍后重试或通过订单详情联系服务人员。</p>
|
||||
</section>
|
||||
|
||||
<section class="quick-grid">
|
||||
<button type="button" @click="router.push('/orders')">
|
||||
<strong>订单中心</strong>
|
||||
<span>查看预约、支付、评价</span>
|
||||
</button>
|
||||
<button type="button" @click="router.push('/after-sales')">
|
||||
<strong>售后记录</strong>
|
||||
<span>查看退款和处理进度</span>
|
||||
</button>
|
||||
<button type="button" @click="router.push('/notifications')">
|
||||
<strong>消息中心</strong>
|
||||
<span>查看系统通知</span>
|
||||
</button>
|
||||
<button type="button" @click="router.push('/settings')">
|
||||
<strong>账号设置</strong>
|
||||
<span>修改资料、手机号和密码</span>
|
||||
</button>
|
||||
</section>
|
||||
</a-spin>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.help-page { min-height: 100vh; padding-top: 66px; background: linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 76%, transparent), var(--theme-page-bg)); color: var(--text-primary); }
|
||||
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 64px; padding: 11px 18px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
|
||||
.header h1 { margin: 0; font-size: 17px; font-weight: 820; }
|
||||
.content { padding: 18px 18px 34px; }
|
||||
.hero-card, .section-card, .quick-grid button { border: 1px solid var(--theme-border); border-radius: 24px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px color-mix(in srgb, var(--theme-neutral) 8%, transparent); }
|
||||
.hero-card { padding: 24px; margin-bottom: 14px; background: linear-gradient(135deg, color-mix(in srgb, var(--theme-primary) 24%, var(--theme-card-bg)), color-mix(in srgb, var(--theme-secondary) 18%, var(--theme-card-bg))); }
|
||||
.hero-card span { color: var(--theme-primary-action); font-family: Georgia, 'Times New Roman', serif; font-size: 12px; font-weight: 800; }
|
||||
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; font-weight: 850; }
|
||||
.hero-card p, .section-card p, .quick-grid span { margin: 0; color: var(--text-secondary); line-height: 1.6; }
|
||||
.section-card { padding: 16px; }
|
||||
.section-card h3 { margin: 0 0 12px; font-size: 17px; }
|
||||
.section-card p + p { margin-top: 8px; }
|
||||
.quick-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 14px; }
|
||||
.quick-grid button { display: grid; gap: 6px; min-height: 112px; padding: 16px; border-color: var(--theme-border); text-align: left; color: var(--text-primary); cursor: pointer; }
|
||||
.quick-grid strong { font-size: 16px; }
|
||||
.quick-grid span { font-size: 13px; }
|
||||
:deep(.ant-btn-link) { color: var(--theme-primary-action); }
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,224 @@
|
||||
<template>
|
||||
<div class="not-found-container">
|
||||
<header class="not-found-topbar">
|
||||
<button class="not-found-back" type="button" aria-label="返回" @click="handleBackClick">
|
||||
<LeftOutlined />
|
||||
</button>
|
||||
<strong>{{ BRAND_CONFIG.appName }}</strong>
|
||||
<span class="not-found-topbar-spacer" aria-hidden="true"></span>
|
||||
</header>
|
||||
|
||||
<div class="not-found-content">
|
||||
<span class="not-found-kicker">{{ BRAND_CONFIG.appName }}</span>
|
||||
<div class="error-code">404</div>
|
||||
<h1>这页去做护理了</h1>
|
||||
<p>您访问的页面不存在或已被删除,我们带您回到首页继续浏览作品。</p>
|
||||
<p class="redirect-message">
|
||||
将在 <span class="countdown">{{ countdown }}</span> 秒后自动跳转到首页...
|
||||
</p>
|
||||
<a-button type="primary" @click="redirectToHome">立即前往首页</a-button>
|
||||
</div>
|
||||
</div>
|
||||
</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'
|
||||
import { LeftOutlined } from '@ant-design/icons-vue'
|
||||
import { BRAND_CONFIG } from '@/config/brand'
|
||||
|
||||
/**
|
||||
* Purpose: router supports NotFoundView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
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
|
||||
|
||||
const clearRedirectTimer = () => {
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
const handleBackClick = () => {
|
||||
clearRedirectTimer()
|
||||
if (window.history.length > 1) {
|
||||
router.back()
|
||||
return
|
||||
}
|
||||
router.push('/home')
|
||||
}
|
||||
|
||||
/** redirectToHome is a local helper used by this page script. */
|
||||
const redirectToHome = () => {
|
||||
clearRedirectTimer()
|
||||
router.push('/home')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
timer = window.setInterval(() => {
|
||||
if (countdown.value > 0) {
|
||||
countdown.value--
|
||||
} else {
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
redirectToHome()
|
||||
}
|
||||
}, 1000)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
clearRedirectTimer()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.not-found-container {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background:
|
||||
radial-gradient(circle at 82% 12%, color-mix(in srgb, var(--theme-primary) 30%, transparent), transparent 34%),
|
||||
linear-gradient(180deg, var(--theme-tertiary), color-mix(in srgb, var(--theme-secondary) 14%, var(--theme-tertiary)));
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.not-found-topbar {
|
||||
position: fixed;
|
||||
top: 12px;
|
||||
left: 50%;
|
||||
z-index: 20;
|
||||
display: grid;
|
||||
grid-template-columns: 40px minmax(0, 1fr) 40px;
|
||||
align-items: center;
|
||||
width: min(calc(100% - 32px), var(--app-mobile-max-width, 480px));
|
||||
height: 44px;
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.not-found-back {
|
||||
display: inline-grid;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
place-items: center;
|
||||
border: 1px solid color-mix(in srgb, var(--theme-border) 78%, transparent);
|
||||
border-radius: 999px;
|
||||
color: var(--theme-primary-action);
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
|
||||
box-shadow: 0 10px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.not-found-topbar strong {
|
||||
overflow: hidden;
|
||||
color: var(--text-primary);
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
text-align: center;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.not-found-topbar-spacer {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
|
||||
.not-found-content {
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
|
||||
border: 1px solid var(--theme-border);
|
||||
border-radius: 28px;
|
||||
padding: 48px 28px;
|
||||
text-align: center;
|
||||
box-shadow: 0 24px 54px color-mix(in srgb, var(--theme-neutral) 12%, transparent);
|
||||
max-width: 500px;
|
||||
width: 100%;
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
.not-found-kicker {
|
||||
color: var(--theme-secondary);
|
||||
font-family: Georgia, 'Times New Roman', serif;
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.error-code {
|
||||
font-size: 104px;
|
||||
font-weight: 900;
|
||||
color: var(--theme-primary-action);
|
||||
margin: 10px 0 14px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.not-found-content h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
margin: 0 0 16px 0;
|
||||
}
|
||||
|
||||
.not-found-content p {
|
||||
font-size: 16px;
|
||||
color: var(--text-secondary);
|
||||
margin: 0 0 24px 0;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.redirect-message {
|
||||
margin: 20px 0 30px 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.countdown {
|
||||
color: var(--theme-primary-action);
|
||||
font-weight: bold;
|
||||
font-size: 18px;
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
:deep(.ant-btn-primary) {
|
||||
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
|
||||
border: none;
|
||||
padding: 12px 32px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
border-radius: 25px;
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
:deep(.ant-btn-primary:hover) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: var(--theme-button-shadow);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.not-found-content {
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
.error-code {
|
||||
font-size: 80px;
|
||||
}
|
||||
|
||||
.not-found-content h1 {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.not-found-content p {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,331 @@
|
||||
<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="currentMessageContentHtml" class="message-content" v-html="currentMessageContentHtml"></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'
|
||||
/**
|
||||
* Purpose: SystemMessageVO supports NotificationsView.vue by holding or executing the system message vo page or API role.
|
||||
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
import { userApi, type SystemMessageVO } from '@/api/user'
|
||||
import { buildSystemMessageActionPath } from '@/utils/system-message-action'
|
||||
import { renderRichContent } from '@/utils/rich-content'
|
||||
|
||||
/**
|
||||
* Purpose: router supports NotificationsView.vue by holding or executing the router page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const router = useRouter()
|
||||
/** loading is a reactive state variable used by the template and event handlers. */
|
||||
const loading = ref(false)
|
||||
/**
|
||||
* Purpose: messages supports NotificationsView.vue by holding or executing the messages page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const messages = ref<SystemMessageVO[]>([])
|
||||
/** detailVisible is a reactive state variable used by the template and event handlers. */
|
||||
const detailVisible = ref(false)
|
||||
/**
|
||||
* Purpose: currentMessage supports NotificationsView.vue by holding or executing the current message page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const 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)
|
||||
const currentMessageContentHtml = computed(() => renderRichContent(currentMessage.value?.content || ''))
|
||||
|
||||
/**
|
||||
* Purpose: resolveSystemMessageActionPath supports NotificationsView.vue by holding or executing the resolve system message action path page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const resolveSystemMessageActionPath = (item: SystemMessageVO) => buildSystemMessageActionPath(item)
|
||||
|
||||
/**
|
||||
* Purpose: markMessageReadIfNeeded supports NotificationsView.vue by holding or executing the mark message read if needed page or API role.
|
||||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||||
*/
|
||||
const markMessageReadIfNeeded = async (item: SystemMessageVO) => {
|
||||
if (item.readStatus === 1) {
|
||||
return
|
||||
}
|
||||
await userApi.markMessageRead(item.id)
|
||||
item.readStatus = 1
|
||||
}
|
||||
|
||||
/** 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) => {
|
||||
try {
|
||||
await markMessageReadIfNeeded(item)
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '标记已读失败')
|
||||
return
|
||||
}
|
||||
|
||||
const actionPath = resolveSystemMessageActionPath(item)
|
||||
if (actionPath) {
|
||||
await router.push(actionPath)
|
||||
return
|
||||
}
|
||||
|
||||
currentMessage.value = item
|
||||
detailVisible.value = true
|
||||
}
|
||||
|
||||
onMounted(loadMessages)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.notifications-page {
|
||||
min-height: 100vh;
|
||||
background: var(--theme-page-bg);
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
align-items: center;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
margin: 4px 0 0;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 0;
|
||||
border-radius: 20px;
|
||||
background: var(--theme-card-bg);
|
||||
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: var(--theme-card-bg);
|
||||
border: 1px solid var(--theme-border);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.message-item .dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--theme-border);
|
||||
}
|
||||
|
||||
.message-item.unread .dot {
|
||||
background: var(--theme-primary);
|
||||
}
|
||||
|
||||
.message-main {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.message-main em {
|
||||
width: fit-content;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--theme-primary-soft);
|
||||
color: var(--theme-primary);
|
||||
font-size: 12px;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
.message-main small,
|
||||
.message-meta {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.message-content {
|
||||
line-height: 1.8;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.message-content :deep(*) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.message-content :deep(p),
|
||||
.message-content :deep(ul),
|
||||
.message-content :deep(ol),
|
||||
.message-content :deep(blockquote),
|
||||
.message-content :deep(pre),
|
||||
.message-content :deep(table) {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.message-content :deep(p:last-child),
|
||||
.message-content :deep(ul:last-child),
|
||||
.message-content :deep(ol:last-child),
|
||||
.message-content :deep(blockquote:last-child),
|
||||
.message-content :deep(pre:last-child),
|
||||
.message-content :deep(table:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.message-content :deep(ul),
|
||||
.message-content :deep(ol) {
|
||||
padding-left: 1.25em;
|
||||
}
|
||||
|
||||
.message-content :deep(a) {
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.message-content :deep(img) {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.message-content :deep(pre) {
|
||||
overflow-x: auto;
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.message-image {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-height: 420px;
|
||||
margin-top: 14px;
|
||||
object-fit: contain;
|
||||
border-radius: 8px;
|
||||
background: var(--theme-primary-soft);
|
||||
}
|
||||
|
||||
.notifications-page {
|
||||
padding: 18px 18px 34px;
|
||||
background:
|
||||
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 28%, transparent), transparent 30%),
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 74%, transparent), var(--theme-page-bg));
|
||||
}
|
||||
|
||||
.page-header {
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
font-size: 21px;
|
||||
font-weight: 860;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
color: var(--theme-secondary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
color: var(--theme-primary-action);
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 82%, transparent);
|
||||
box-shadow: 0 12px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
|
||||
}
|
||||
|
||||
.message-list {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.message-item {
|
||||
align-items: flex-start;
|
||||
padding: 17px;
|
||||
border-radius: 22px;
|
||||
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
|
||||
box-shadow: 0 18px 38px color-mix(in srgb, var(--theme-neutral) 7%, transparent);
|
||||
}
|
||||
|
||||
.message-item.unread {
|
||||
border-color: color-mix(in srgb, var(--theme-primary) 36%, var(--theme-border));
|
||||
}
|
||||
|
||||
.message-item.unread .dot {
|
||||
background: var(--theme-primary-action);
|
||||
}
|
||||
|
||||
.message-main strong {
|
||||
color: var(--text-primary);
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.message-main em {
|
||||
color: var(--theme-primary-action);
|
||||
background: color-mix(in srgb, var(--theme-primary) 18%, var(--theme-card-bg));
|
||||
}
|
||||
|
||||
.message-content :deep(a) {
|
||||
color: var(--theme-primary-action);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,429 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { LeftOutlined } from '@ant-design/icons-vue'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import { afterSaleApi, orderApi, paymentApi } from '../api/order'
|
||||
import type { AfterSaleVO, OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
|
||||
import { userApi, type ContactInfoVO } from '@/api/user'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { extractLegacyFileId, getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const loading = ref(false)
|
||||
const order = ref<any | null>(null)
|
||||
const reviews = ref<OrderArtistReviewVO[]>([])
|
||||
const changeRequests = ref<OrderArtistChangeRequestVO[]>([])
|
||||
const afterSales = ref<AfterSaleVO[]>([])
|
||||
const contact = ref<ContactInfoVO | null>(null)
|
||||
const quoteReply = ref('')
|
||||
const quoteSubmitting = ref(false)
|
||||
const quoteConfirming = ref(false)
|
||||
|
||||
const orderId = computed(() => String(route.params.id || route.query.orderId || ''))
|
||||
const items = computed(() => Array.isArray(order.value?.items) ? order.value.items : [])
|
||||
|
||||
const formatMoney = (value?: number | string) => {
|
||||
const amount = Number(value)
|
||||
return Number.isFinite(amount) ? `¥${amount.toFixed(2)}` : '¥0.00'
|
||||
}
|
||||
|
||||
const formatDateTime = (value?: string) => value ? String(value).replace('T', ' ').slice(0, 16) : '--'
|
||||
const isQuoteStatus = (status?: unknown) => Number(status) === 0
|
||||
const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status))
|
||||
const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending'
|
||||
const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID'
|
||||
const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value))
|
||||
const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING')
|
||||
const canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value)))
|
||||
|
||||
const timeline = computed(() => {
|
||||
const current = order.value || {}
|
||||
const firstAppointment = items.value.map((item: any) => item.appointmentTime).find(Boolean)
|
||||
const status = Number(current.status)
|
||||
if (status === 0) {
|
||||
return [
|
||||
{ key: 'created', title: '已创建', text: formatDateTime(current.createTime), done: true, active: false },
|
||||
{ key: 'quote', title: '确认价格', text: current.quoteStatusText || '等待双方确认', done: Boolean(current.quoteUserConfirmed && current.quoteShopConfirmed), active: true },
|
||||
{ key: 'appointment', title: '预约时间', text: firstAppointment ? formatDateTime(firstAppointment) : '价格确认后安排', done: Boolean(firstAppointment), active: false },
|
||||
{ key: 'service', title: '服务完成', text: '待服务', done: false, active: false },
|
||||
{ key: 'review', title: '评价', text: '完成后可评价', done: false, active: false }
|
||||
]
|
||||
}
|
||||
return [
|
||||
{ key: 'created', title: '已创建', text: formatDateTime(current.createTime), done: true, active: false },
|
||||
{ key: 'appointment', title: '预约时间', text: formatDateTime(firstAppointment), done: Boolean(firstAppointment), active: status === 1 },
|
||||
{ key: 'service', title: status === 3 ? '已取消' : '服务完成', text: formatDateTime(current.completeTime || current.cancelTime || current.updateTime), done: status === 2 || status === 3, active: status === 2 || status === 3 },
|
||||
{ key: 'review', title: '评价', text: reviews.value.length ? `${reviews.value.length} 条记录` : '完成后可评价', done: reviews.value.some(item => Number(item.status) === 1 || item.rating), active: reviews.value.some(item => Number(item.status) !== 1 && !item.rating) },
|
||||
{ key: 'after-sale', title: '售后', text: afterSales.value.length ? `${afterSales.value.length} 条记录` : '暂无售后', done: afterSales.value.length > 0, active: afterSales.value.some(item => item.status === 'PENDING') }
|
||||
]
|
||||
})
|
||||
|
||||
const hasAmount = (value: unknown) => value !== undefined && value !== null && value !== '' && Number.isFinite(Number(value))
|
||||
|
||||
const formatQuoteAmount = (value: unknown, fallback = '--') => hasAmount(value) ? formatMoney(value as number | string) : fallback
|
||||
|
||||
const quoteReferencePrice = (item: any) => item?.referencePrice ?? item?.price
|
||||
|
||||
const quoteMessages = computed(() => Array.isArray(order.value?.quoteMessages) ? order.value.quoteMessages : [])
|
||||
|
||||
const quoteStatusText = computed(() => order.value?.quoteStatusText || order.value?.statusText || '确认价格中')
|
||||
|
||||
const quoteExpireText = computed(() => {
|
||||
const expireTime = formatDateTime(order.value?.quoteExpireTime)
|
||||
return expireTime !== '--' ? `有效期至 ${expireTime}` : '等待门店报价'
|
||||
})
|
||||
|
||||
const quoteMessageItems = (quoteMessage: any) => Array.isArray(quoteMessage?.items) ? quoteMessage.items : []
|
||||
|
||||
const quoteActorText = (quoteMessage: any) => {
|
||||
if (quoteMessage?.actorTypeText) return quoteMessage.actorTypeText
|
||||
if (String(quoteMessage?.actorType || '').toUpperCase() === 'USER') return '用户'
|
||||
if (String(quoteMessage?.actorType || '').toUpperCase() === 'SHOP') return '门店'
|
||||
return '系统'
|
||||
}
|
||||
|
||||
const quoteActionText = (quoteMessage: any) => quoteMessage?.actionText || quoteMessage?.action || '报价更新'
|
||||
|
||||
const quoteMessageKey = (quoteMessage: any, index: string | number) => {
|
||||
return String(quoteMessage?.id ?? `${quoteMessage?.createTime || 'quote'}-${quoteMessage?.action || index}`)
|
||||
}
|
||||
|
||||
const quoteMessageItemKey = (quoteItem: any) => {
|
||||
return String(quoteItem?.orderItemId ?? quoteItem?.productId ?? quoteItem?.id ?? JSON.stringify(quoteItem))
|
||||
}
|
||||
|
||||
const quoteMessageItemText = (quoteItem: any) => {
|
||||
const sourceItem = items.value.find((item: any) => String(item.id) === String(quoteItem?.orderItemId) || String(item.productId) === String(quoteItem?.productId))
|
||||
const title = quoteItem?.productTitle || sourceItem?.productTitle || '预约项目'
|
||||
const amount = quoteItem?.confirmedPrice ?? quoteItem?.quotedPrice ?? quoteItem?.price
|
||||
return hasAmount(amount) ? `${title}:${formatMoney(amount)}` : title
|
||||
}
|
||||
|
||||
const orderHasCurrentQuote = computed(() => {
|
||||
return items.value.some((item: any) => hasAmount(item?.quotedPrice ?? item?.confirmedPrice))
|
||||
})
|
||||
|
||||
const resolveOrderImages = async () => {
|
||||
for (const item of items.value) {
|
||||
const imageId = extractLegacyFileId(item.productImage)
|
||||
if (!imageId) continue
|
||||
const cachedUrl = getCachedSignedImageUrlSync(imageId)
|
||||
if (cachedUrl) item.productImage = cachedUrl
|
||||
item.productImage = await getCachedSignedImageUrl(imageId)
|
||||
}
|
||||
}
|
||||
|
||||
const loadRelated = async () => {
|
||||
if (!orderId.value) return
|
||||
const [reviewList, changeList, afterSalePage, contactInfo] = await Promise.all([
|
||||
orderApi.getOrderReviews(orderId.value).catch(() => []),
|
||||
orderApi.getOrderArtistChangeRequests(orderId.value).catch(() => []),
|
||||
afterSaleApi.listMy({ page: 1, size: 50 }).catch(() => ({ list: [] })),
|
||||
userApi.getOrderArtistContact(orderId.value).catch(() => null)
|
||||
])
|
||||
reviews.value = reviewList || []
|
||||
changeRequests.value = changeList || []
|
||||
afterSales.value = ((afterSalePage as any)?.list || []).filter((item: AfterSaleVO) => String(item.orderId) === orderId.value)
|
||||
contact.value = contactInfo
|
||||
}
|
||||
|
||||
const loadOrder = async () => {
|
||||
if (!orderId.value) {
|
||||
order.value = null
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
order.value = await orderApi.getOrderDetail(orderId.value)
|
||||
await resolveOrderImages()
|
||||
await loadRelated()
|
||||
} catch (error: any) {
|
||||
order.value = null
|
||||
message.error(error?.message || '订单详情加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const submitQuoteReply = async () => {
|
||||
if (!order.value?.id) return
|
||||
const remark = quoteReply.value.trim()
|
||||
if (!remark) {
|
||||
message.warning('请先填写回复内容')
|
||||
return
|
||||
}
|
||||
quoteSubmitting.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await orderApi.replyQuote(order.value.id, { remark })
|
||||
await loadOrder()
|
||||
})
|
||||
quoteReply.value = ''
|
||||
message.success('报价回复已发送')
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '发送报价回复失败')
|
||||
} finally {
|
||||
quoteSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const confirmQuote = () => {
|
||||
if (!order.value?.id) return
|
||||
if (!orderHasCurrentQuote.value) {
|
||||
message.warning('当前暂无可确认报价')
|
||||
return
|
||||
}
|
||||
Modal.confirm({
|
||||
title: '确认当前报价',
|
||||
content: '确认后门店会继续处理预约,请确认当前报价无误。',
|
||||
onOk: async () => {
|
||||
quoteConfirming.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await orderApi.confirmUserQuote(order.value.id)
|
||||
await loadOrder()
|
||||
})
|
||||
message.success('已确认当前报价')
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '确认报价失败')
|
||||
} finally {
|
||||
quoteConfirming.value = false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const preparePayment = async () => {
|
||||
if (!order.value?.id) return
|
||||
await runWithGlobalLoading(async () => {
|
||||
await paymentApi.prepareOrderPayment(order.value.id)
|
||||
await loadOrder()
|
||||
})
|
||||
message.success('支付单已准备')
|
||||
}
|
||||
|
||||
const mockPay = async () => {
|
||||
if (!order.value?.id) return
|
||||
await runWithGlobalLoading(async () => {
|
||||
await paymentApi.mockSuccess(order.value.id)
|
||||
await loadOrder()
|
||||
})
|
||||
message.success('模拟支付成功')
|
||||
}
|
||||
|
||||
const cancelOrder = () => {
|
||||
if (!order.value?.id) return
|
||||
Modal.confirm({
|
||||
title: '取消订单',
|
||||
content: '确认取消这笔订单吗?',
|
||||
onOk: async () => {
|
||||
await runWithGlobalLoading(() => orderApi.cancelOrder(order.value.id as IdType))
|
||||
message.success('订单已取消')
|
||||
await loadOrder()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(loadOrder)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="detail-page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined />
|
||||
</a-button>
|
||||
<h1>订单详情</h1>
|
||||
<a-button type="link" @click="router.push('/orders')">列表</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<a-spin :spinning="loading">
|
||||
<a-empty v-if="!order" description="未找到订单">
|
||||
<a-button type="primary" @click="router.push('/orders')">查看订单中心</a-button>
|
||||
</a-empty>
|
||||
|
||||
<template v-else>
|
||||
<section class="hero-card">
|
||||
<span class="eyebrow">{{ isQuoteConfirming ? '询价预约' : '预约订单' }}</span>
|
||||
<h2>{{ order.orderNo || `订单 ${order.id}` }}</h2>
|
||||
<p>{{ order.shopName || '当前门店' }}</p>
|
||||
<div class="hero-meta">
|
||||
<strong>{{ formatMoney(order.actualAmount || order.totalAmount) }}</strong>
|
||||
<span :class="['status-pill', statusClass(order.status)]">{{ isQuoteConfirming ? quoteStatusText : (order.statusText || '处理中') }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="timeline-card">
|
||||
<article v-for="node in timeline" :key="node.key" :class="{ done: node.done, active: node.active }">
|
||||
<strong>{{ node.title }}</strong>
|
||||
<span>{{ node.text }}</span>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section v-if="isQuoteConfirming" class="section-card quote-detail-panel">
|
||||
<div class="section-head">
|
||||
<div>
|
||||
<h3>报价确认</h3>
|
||||
<p>{{ quoteStatusText }} · {{ quoteExpireText }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p>客户备注:{{ order.customerRemark || '暂无备注' }}</p>
|
||||
<div class="quote-flags">
|
||||
<span :class="{ active: order.quoteUserConfirmed }">用户{{ order.quoteUserConfirmed ? '已确认' : '待确认' }}</span>
|
||||
<span :class="{ active: order.quoteShopConfirmed }">门店{{ order.quoteShopConfirmed ? '已确认' : '待确认' }}</span>
|
||||
</div>
|
||||
<div class="quote-items">
|
||||
<article v-for="item in items" :key="item.id || item.productId" class="quote-item">
|
||||
<strong>{{ item.productTitle || '预约项目' }}</strong>
|
||||
<span>参考价 {{ formatQuoteAmount(quoteReferencePrice(item), '待确认') }}</span>
|
||||
<span>当前报价 {{ formatQuoteAmount(item.quotedPrice, '待报价') }}</span>
|
||||
<span>最终价 {{ formatQuoteAmount(item.confirmedPrice, '待确认') }}</span>
|
||||
</article>
|
||||
</div>
|
||||
<div class="quote-history">
|
||||
<strong>报价历史</strong>
|
||||
<div v-if="quoteMessages.length" class="quote-history__list">
|
||||
<article v-for="(quoteMessage, index) in quoteMessages" :key="quoteMessageKey(quoteMessage, index)" class="quote-history__item">
|
||||
<div>
|
||||
<span>{{ quoteActorText(quoteMessage) }}</span>
|
||||
<em>{{ quoteActionText(quoteMessage) }}</em>
|
||||
<small>{{ formatDateTime(quoteMessage.createTime) }}</small>
|
||||
</div>
|
||||
<p v-if="quoteMessage.remark">{{ quoteMessage.remark }}</p>
|
||||
<div v-if="quoteMessageItems(quoteMessage).length" class="quote-history__prices">
|
||||
<span v-for="quoteItem in quoteMessageItems(quoteMessage)" :key="quoteMessageItemKey(quoteItem)">
|
||||
{{ quoteMessageItemText(quoteItem) }}
|
||||
</span>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else>暂无报价历史</p>
|
||||
</div>
|
||||
<div class="quote-reply">
|
||||
<a-textarea v-model:value="quoteReply" :rows="3" :maxlength="300" placeholder="给门店补充说明或回复当前报价" />
|
||||
<div class="quote-reply__actions">
|
||||
<a-button :loading="quoteSubmitting" @click="submitQuoteReply">发送回复</a-button>
|
||||
<a-button
|
||||
v-if="!order.quoteUserConfirmed"
|
||||
type="primary"
|
||||
:loading="quoteConfirming"
|
||||
:disabled="!orderHasCurrentQuote"
|
||||
@click="confirmQuote"
|
||||
>
|
||||
确认当前报价
|
||||
</a-button>
|
||||
<span v-else class="quote-confirmed">你已确认当前报价</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section-card">
|
||||
<div class="section-head">
|
||||
<h3>预约项目</h3>
|
||||
<a-button type="link" @click="router.push({ path: '/service-progress', query: { orderId } })">服务进度</a-button>
|
||||
</div>
|
||||
<article v-for="item in items" :key="item.id" class="item-row">
|
||||
<div class="thumb">
|
||||
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" />
|
||||
<span v-else>{{ String(item.productTitle || '项').slice(0, 1) }}</span>
|
||||
</div>
|
||||
<div class="item-main">
|
||||
<strong>{{ item.productTitle || '预约项目' }}</strong>
|
||||
<span>{{ isQuoteConfirming ? '参考价 ' : '' }}{{ formatMoney(item.price) }} x {{ item.quantity || 1 }}</span>
|
||||
<span v-if="item.artistName">美甲师:{{ item.artistName }}</span>
|
||||
<span v-if="item.appointmentTime">预约:{{ formatDateTime(item.appointmentTime) }}</span>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section v-if="contact" class="section-card">
|
||||
<h3>联系信息</h3>
|
||||
<p>{{ contact.contactName || contact.roleLabel || '服务联系人' }}</p>
|
||||
<p v-if="contact.phoneAvailable && contact.phone">电话:{{ contact.phone }}</p>
|
||||
<p v-if="contact.wechatAvailable && contact.wechatId">微信:{{ contact.wechatId }}</p>
|
||||
<p v-if="contact.platformContactText">{{ contact.platformContactText }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="afterSales.length || changeRequests.length || reviews.length" class="section-card">
|
||||
<h3>关联记录</h3>
|
||||
<p v-for="item in afterSales" :key="`as-${item.id}`">售后 {{ item.afterSaleNo || item.id }}:{{ item.status || '-' }}</p>
|
||||
<p v-for="item in changeRequests" :key="`change-${item.id}`">改派:{{ item.statusText || item.status || '-' }}</p>
|
||||
<p v-for="item in reviews" :key="`review-${item.id}`">评价:{{ item.statusText || item.rating || '待评价' }}</p>
|
||||
</section>
|
||||
|
||||
<section class="action-bar">
|
||||
<a-button v-if="canPreparePayment" @click="preparePayment">准备支付</a-button>
|
||||
<a-button v-if="canMockPay" type="primary" @click="mockPay">模拟支付</a-button>
|
||||
<a-button v-if="canApplyAfterSale" @click="router.push({ path: '/after-sale/apply', query: { orderId } })">申请售后</a-button>
|
||||
<a-button v-if="order.status === 1" danger @click="cancelOrder">取消订单</a-button>
|
||||
</section>
|
||||
</template>
|
||||
</a-spin>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.detail-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
|
||||
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
|
||||
.header h1 { margin: 0; font-size: 18px; }
|
||||
.content { padding: 16px 14px 28px; }
|
||||
.hero-card, .section-card, .timeline-card { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
|
||||
.hero-card { padding: 22px; background: var(--theme-gradient-soft); }
|
||||
.eyebrow { display: block; color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
|
||||
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
|
||||
.hero-card p { margin: 0; color: var(--text-secondary); }
|
||||
.hero-meta { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 18px; }
|
||||
.hero-meta strong { font-size: 20px; }
|
||||
.status-pill { padding: 6px 12px; border-radius: 999px; font-size: 12px; font-weight: 700; background: var(--theme-primary-soft); color: var(--theme-primary); }
|
||||
.status-pill.quote { color: #6b4600; background: #fff2cc; }
|
||||
.status-pill.cancelled { color: var(--theme-accent); }
|
||||
.timeline-card { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 1px; overflow: hidden; margin-top: 14px; background: var(--theme-border); }
|
||||
.timeline-card article { min-width: 0; padding: 12px 8px; background: var(--theme-card-bg); color: var(--text-secondary); }
|
||||
.timeline-card article.active { color: var(--theme-primary); }
|
||||
.timeline-card article.done strong { color: var(--theme-primary); }
|
||||
.timeline-card strong, .timeline-card span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.timeline-card strong { font-size: 12px; }
|
||||
.timeline-card span { margin-top: 4px; font-size: 11px; }
|
||||
.section-card { margin-top: 14px; padding: 16px; }
|
||||
.section-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.section-card h3 { margin: 0 0 12px; font-size: 17px; }
|
||||
.section-card p { margin: 8px 0 0; color: var(--text-secondary); line-height: 1.6; }
|
||||
.section-head p { margin: 4px 0 0; font-size: 13px; }
|
||||
.quote-detail-panel { display: grid; gap: 12px; }
|
||||
.quote-flags { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.quote-flags span { padding: 4px 9px; border-radius: 999px; color: var(--text-secondary); background: var(--theme-primary-soft); font-size: 12px; }
|
||||
.quote-flags span.active { color: var(--theme-primary); font-weight: 700; }
|
||||
.quote-items, .quote-history, .quote-history__list, .quote-reply { display: grid; gap: 8px; }
|
||||
.quote-item { display: grid; grid-template-columns: minmax(0, 1.35fr) repeat(3, minmax(82px, auto)); gap: 8px; align-items: center; min-width: 0; padding: 10px; border-radius: 12px; background: color-mix(in srgb, var(--theme-primary-soft) 48%, var(--theme-card-bg)); }
|
||||
.quote-item strong { min-width: 0; overflow-wrap: anywhere; color: var(--text-primary); font-size: 13px; }
|
||||
.quote-item span, .quote-history__item small, .quote-confirmed { color: var(--text-secondary); font-size: 12px; }
|
||||
.quote-history > strong { color: var(--text-primary); font-size: 13px; }
|
||||
.quote-history__item { display: grid; gap: 6px; padding: 10px; border-radius: 12px; background: color-mix(in srgb, var(--theme-primary-soft) 42%, var(--theme-card-bg)); }
|
||||
.quote-history__item div { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; }
|
||||
.quote-history__item span, .quote-history__item em { color: var(--theme-primary); font-size: 12px; font-style: normal; font-weight: 700; }
|
||||
.quote-history__item p { margin: 0; overflow-wrap: anywhere; font-size: 13px; }
|
||||
.quote-history__prices { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.quote-history__prices span { padding: 3px 7px; border-radius: 8px; color: var(--text-secondary); background: var(--theme-card-bg); font-size: 12px; }
|
||||
.quote-reply__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
|
||||
.quote-confirmed { display: inline-flex; align-items: center; min-height: 32px; color: var(--theme-primary); font-weight: 700; }
|
||||
.item-row { display: flex; gap: 12px; padding: 12px 0; border-top: 1px solid var(--theme-border); }
|
||||
.item-row:first-of-type { border-top: 0; padding-top: 0; }
|
||||
.thumb { width: 64px; height: 64px; flex: 0 0 auto; border-radius: 14px; overflow: hidden; display: grid; place-items: center; background: var(--theme-primary-soft); color: var(--theme-primary); font-weight: 700; }
|
||||
.thumb img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.item-main { display: grid; gap: 5px; min-width: 0; color: var(--text-secondary); font-size: 13px; }
|
||||
.item-main strong { color: var(--text-primary); font-size: 15px; }
|
||||
.action-bar { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; margin-top: 16px; }
|
||||
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
||||
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
||||
@media (max-width: 640px) {
|
||||
.quote-item { grid-template-columns: 1fr; }
|
||||
.quote-reply__actions { justify-content: stretch; }
|
||||
.quote-reply__actions :deep(.ant-btn) { flex: 1 1 140px; }
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user