修复一些问题,个人账号功能完善,注册功能完善,收藏,购物车功能完善,初版基本完成,投入测试

This commit is contained in:
xiaowang
2026-03-03 17:50:10 +08:00
parent b301e37468
commit b0470b8f86
23 changed files with 804 additions and 129 deletions
-2
View File
@@ -74,8 +74,6 @@ watch(() => route.path, async () => {
// 页面加载时获取购物车数量
loadCartCount()
// 每30秒自动更新一次购物车数量
setInterval(loadCartCount, 30000)
</script>
<style>
+6
View File
@@ -9,5 +9,11 @@ export const fileApi = {
'Content-Type': 'multipart/form-data'
}
})
},
getSignedUrl: (fileId: number, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
params: { expiryTimeInMinutes }
})
}
}
+3
View File
@@ -1,5 +1,6 @@
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { wishlistApi } from './wishlist'
import router from '../router'
import { message } from 'ant-design-vue'
@@ -221,4 +222,6 @@ export const fileApi = {
}
}
export { wishlistApi }
export default api
+18
View File
@@ -3,17 +3,35 @@ import api from './index'
export interface ProductVO {
id: number
shopId: number | null
shopName?: string
name: string
title?: string
description: string
image: string
imageFileIds?: string
imageUrls?: string[]
price: number
estimatedTime: number
approximateDuration?: string
category: string
tags?: string
tagList?: string[]
tagInfos?: TagInfo[]
status: number
likeCount?: number
collectCount?: number
createTime: string
updateTime: string
}
export interface TagInfo {
id: number
tagName: string
textColor?: string
bgColor?: string
borderColor?: string
}
export interface ListProductsParams {
page: number
size: number
+4
View File
@@ -22,6 +22,7 @@ export interface UpdateUserInfoRequest {
nickname?: string
avatar?: string
signature?: string
phone?: string
}
export interface ListUsersParams {
@@ -87,5 +88,8 @@ export const userApi = {
},
sendVerificationCode: (data: { phone: string }) => {
return api.post('/user/send-verification-code', data)
},
deactivateAccount: () => {
return api.delete('/user/deactivate')
}
}
+13
View File
@@ -271,6 +271,19 @@ router.beforeEach((to, _from, next) => {
} else if (to.path === '/home' && !token) {
next('/')
} else {
// 对于需要认证的页面,验证token的有效性
if (requiresAuth && token) {
// 检查userInfo是否存在
const userInfo = localStorage.getItem('userInfo')
if (!userInfo) {
console.log('Token存在但userInfo不存在,清除token并跳转到登录页')
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
sessionStorage.removeItem('accessToken')
next('/')
return
}
}
next()
}
}
+115 -36
View File
@@ -11,36 +11,8 @@
<!-- 账号设置内容 -->
<div class="account-settings">
<!-- 状态提示 -->
<div v-if="!hasPassword || !hasPhone" class="status-tips">
<a-alert
v-if="!hasPassword"
type="warning"
message="请设置密码"
description="为了账户安全,建议您设置一个安全的密码"
show-icon
:closable="false"
>
<template #action>
<a-button size="small" type="primary" @click="handleSetPassword">去设置</a-button>
</template>
</a-alert>
<a-alert
v-if="!hasPhone"
type="warning"
message="请绑定手机号"
description="绑定手机号可以提高账户安全性"
show-icon
:closable="false"
>
<template #action>
<a-button size="small" type="primary" @click="handleBindPhone">去绑定</a-button>
</template>
</a-alert>
</div>
<!-- 账号设置选项 -->
<a-card :bordered="false" class="settings-card" v-if="hasPassword && hasPhone">
<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)">
@@ -190,7 +162,7 @@
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, RightOutlined, LockOutlined, PhoneOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { message, Modal } from 'ant-design-vue'
import { userApi } from '@/api/user'
import type { UserVO } from '@/api/user'
@@ -253,9 +225,64 @@ const accountSettings = ref([
title: '修改密码',
icon: LockOutlined,
bgColor: '#f6ffed'
},
{
key: 'deactivateAccount',
title: '注销账号',
icon: LockOutlined,
bgColor: '#fff1f0'
}
])
// 根据用户状态动态更新账号设置选项
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
}
// 获取用户信息
const fetchUserInfo = async () => {
try {
@@ -265,6 +292,8 @@ const fetchUserInfo = async () => {
hasPhone.value = !!userInfo.value.phone
// 检查是否设置密码(通过localStorage中的标识)
hasPassword.value = localStorage.getItem('needSetPassword') !== 'true'
// 更新账号设置选项
updateAccountSettings()
} catch (error) {
console.error('获取用户信息失败:', error)
message.error('获取用户信息失败')
@@ -279,12 +308,21 @@ const handleBackClick = () => {
// 处理设置项点击
const handleSettingClick = (key: string) => {
switch (key) {
case 'bindPhone':
bindPhoneModalVisible.value = true
break
case 'changePhone':
changePhoneModalVisible.value = true
break
case 'setPassword':
handleSetPassword()
break
case 'changePassword':
changePasswordModalVisible.value = true
break
case 'deactivateAccount':
handleDeactivateAccount()
break
default:
break
}
@@ -295,12 +333,7 @@ const handleSetPassword = () => {
router.push('/settings/password')
}
// 处理绑定手机号
const handleBindPhone = () => {
bindPhoneModalVisible.value = true
}
// 发送验证码
// 发送绑定手机号验证码
const handleSendVerificationCode = async () => {
if (!bindPhoneForm.phone) {
message.error('请输入手机号')
@@ -461,6 +494,52 @@ const handleChangePasswordCancel = () => {
changePasswordForm.confirmPassword = ''
}
// 处理注销账号
const handleDeactivateAccount = async () => {
Modal.confirm({
title: '确认注销账号',
content: '注销账号后,您的所有数据将被删除且无法恢复。确定要注销账号吗?',
okText: '确认注销',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
try {
// 在删除前先重命名账号和手机号,添加删除时间戳
const timestamp = new Date().getTime()
const newAccount = `${userInfo.value.account}_deleted_${timestamp}`
const newPhone = `${userInfo.value.phone}_deleted_${timestamp}`
try {
await userApi.updateUserInfo({ account: newAccount, phone: newPhone })
} catch (renameError) {
console.error('重命名账号和手机号失败:', renameError)
// 重命名失败也继续删除流程
}
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()
+171 -8
View File
@@ -49,6 +49,51 @@
</a-input>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="account" label="账号">
<a-input
v-model:value="formData.account"
placeholder="请输入账号"
size="large"
>
<template #prefix>
<UserOutlined style="color: #999" />
</template>
</a-input>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="phone" label="手机号">
<a-input
v-model:value="formData.phone"
placeholder="请输入手机号"
size="large"
>
<template #prefix>
<UserOutlined style="color: #999" />
</template>
</a-input>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="verificationCode" label="验证码">
<a-input
v-model:value="formData.verificationCode"
placeholder="请输入验证码"
size="large"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !formData.phone"
@click="handleSendVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item name="account" label="账号" v-if="activeTab === 'login' && loginType === 'password'">
<a-input
v-model:value="formData.account"
@@ -62,7 +107,7 @@
</a-input>
<div v-if="accountStatus" class="account-status">
<span v-if="accountStatus.exists" class="status-success">
账号存在,昵称:{{ accountStatus.nickname }}
账号存在,昵称:{{ accountStatus.nickname }} {{ accountStatus.hasShop ? ',已绑定店铺' : ',请选择店铺' }}
</span>
<span v-else class="status-error">
账号不存在
@@ -75,11 +120,24 @@
v-model:value="formData.phone"
placeholder="请输入手机号"
size="large"
@blur="handlePhoneBlur"
>
<template #prefix>
<UserOutlined style="color: #999" />
</template>
</a-input>
<div class="phone-login-tip">
<InfoCircleOutlined style="color: #1890ff; margin-right: 4px;" />
<span>新用户将自动注册</span>
</div>
<div v-if="phoneUserStatus" class="account-status">
<span v-if="phoneUserStatus.exists" class="status-success">
{{ phoneUserStatus.hasShop ? '账号已存在,已绑定店铺' : '账号已存在,请选择店铺' }}
</span>
<span v-else class="status-error">
新用户,请选择店铺
</span>
</div>
</a-form-item>
<a-form-item name="verificationCode" label="验证码" v-if="activeTab === 'login' && loginType === 'phone'">
@@ -103,6 +161,34 @@
</a-input>
</a-form-item>
<a-form-item
v-if="activeTab === 'login' && loginType === 'phone' && (phoneUserStatus && !phoneUserStatus.hasShop)"
name="shopId"
label="选择店铺"
>
<a-select
v-model:value="formData.shopId"
placeholder="请选择店铺"
size="large"
:loading="loadingShops"
>
<a-select-option
v-if="shops.length === 0"
disabled
value=""
>
暂无店铺数据
</a-select-option>
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item name="password" label="密码" v-if="activeTab === 'login' && loginType === 'password' || activeTab === 'register'">
<a-input-password
v-model:value="formData.password"
@@ -115,6 +201,34 @@
</a-input-password>
</a-form-item>
<a-form-item
v-if="activeTab === 'login' && loginType === 'password' && (accountStatus && accountStatus.exists && !accountStatus.hasShop)"
name="shopId"
label="选择店铺"
>
<a-select
v-model:value="formData.shopId"
placeholder="请选择店铺"
size="large"
:loading="loadingShops"
>
<a-select-option
v-if="shops.length === 0"
disabled
value=""
>
暂无店铺数据
</a-select-option>
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="activeTab === 'register'" name="confirmPassword" label="确认密码">
<a-input-password
v-model:value="formData.confirmPassword"
@@ -195,7 +309,7 @@
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined, WechatOutlined, QqOutlined } from '@ant-design/icons-vue'
import { UserOutlined, LockOutlined, WechatOutlined, QqOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { authApi } from '@/api/auth'
import { shopApi } from '@/api/shop'
@@ -209,6 +323,7 @@ const loading = ref(false)
const loadingShops = ref(false)
const shops = ref<any[]>([])
const accountStatus = ref<any>(null)
const phoneUserStatus = ref<any>(null)
const countdown = ref(0)
const formData = reactive({
@@ -291,15 +406,27 @@ const handleSubmit = async () => {
let response
if (loginType.value === 'phone') {
if (phoneUserStatus.value && !phoneUserStatus.value.hasShop && !formData.shopId) {
message.error('请选择店铺')
loading.value = false
return
}
response = await authApi.phoneLogin({
phone: formData.phone,
verificationCode: formData.verificationCode
verificationCode: formData.verificationCode,
shopId: formData.shopId
})
} else {
if (accountStatus.value && accountStatus.value.exists && !accountStatus.value.hasShop && !formData.shopId) {
message.error('请选择店铺')
loading.value = false
return
}
response = await authApi.login({
account: formData.account,
password: formData.password,
rememberMe: formData.rememberMe
rememberMe: formData.rememberMe,
shopId: formData.shopId
})
}
@@ -312,7 +439,6 @@ const handleSubmit = async () => {
localStorage.setItem('accessToken', loginData.accessToken)
localStorage.setItem('refreshToken', loginData.refreshToken)
localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo))
// 存储是否需要设置密码的标识
if (loginData.needSetPassword) {
localStorage.setItem('needSetPassword', 'true')
} else {
@@ -336,6 +462,8 @@ const handleSubmit = async () => {
account: formData.account,
password: formData.password,
nickname: formData.nickname,
phone: formData.phone,
verificationCode: formData.verificationCode,
shopId: formData.shopId!
})
@@ -369,16 +497,43 @@ const handleAccountBlur = async () => {
if (res) {
accountStatus.value = {
exists: true,
nickname: res.nickname
nickname: res.nickname,
hasShop: res.shopId && res.shopId > 0
}
} else {
accountStatus.value = {
exists: false
exists: false,
hasShop: false
}
}
} catch (error) {
accountStatus.value = {
exists: false
exists: false,
hasShop: false
}
}
}
}
const handlePhoneBlur = async () => {
if (activeTab.value === 'login' && loginType.value === 'phone' && formData.phone) {
try {
const res = await userApi.getUserByAccount(formData.phone)
if (res) {
phoneUserStatus.value = {
exists: true,
hasShop: res.shopId && res.shopId > 0
}
} else {
phoneUserStatus.value = {
exists: false,
hasShop: false
}
}
} catch (error) {
phoneUserStatus.value = {
exists: false,
hasShop: false
}
}
}
@@ -588,4 +743,12 @@ onMounted(() => {
.status-error {
color: #f5222d;
}
.phone-login-tip {
margin-top: 8px;
font-size: 12px;
color: #1890ff;
display: flex;
align-items: center;
}
</style>
+51 -13
View File
@@ -24,23 +24,22 @@
class="cart-item"
:body-style="{ padding: '16px' }"
hoverable
@click="handleProductClick(item)"
>
<div class="item-content">
<!-- 复选框 -->
<a-checkbox v-model:checked="item.selected" @change="handleSelectChange" />
<!-- 商品图片 -->
<div class="item-image" v-if="item.productImage">
<div class="item-image" v-if="item.productImage" @click="handleProductClick(item)" style="cursor: pointer;">
<img :src="item.productImage" :alt="item.productTitle" />
</div>
<div class="item-image" v-else :style="{ backgroundColor: getRandomColor() }">
<div class="item-image" v-else :style="{ backgroundColor: getRandomColor(), cursor: 'pointer' }" @click="handleProductClick(item)">
<span>{{ item.productTitle[0] }}</span>
</div>
<!-- 商品详情 -->
<div class="item-details">
<h3 class="item-name">{{ item.productTitle }}</h3>
<h3 class="item-name" @click="handleProductClick(item)" style="cursor: pointer;">{{ item.productTitle }}</h3>
<p class="item-price">¥{{ item.price.toFixed(2) }}</p>
<!-- 数量控制和删除按钮 -->
@@ -744,36 +743,66 @@ onMounted(() => {
.coupon-card {
border-radius: 12px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
border: 1px solid #f0f0f0;
transition: all 0.3s ease;
}
.coupon-card:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
transform: translateY(-2px);
}
.coupon-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
padding: 18px 20px;
cursor: pointer;
background: linear-gradient(135deg, #f6f9ff 0%, #ffffff 100%);
border-bottom: 1px solid #e6f7ff;
}
.coupon-header:hover {
background-color: #f5f5f5;
background: linear-gradient(135deg, #e6f7ff 0%, #f6f9ff 100%);
}
.coupon-title {
font-size: 15px;
font-size: 16px;
font-weight: 600;
color: #333;
display: flex;
align-items: center;
gap: 8px;
}
.coupon-title::before {
content: "🎁";
font-size: 18px;
}
.coupon-value {
font-size: 14px;
font-size: 13px;
font-weight: 500;
color: #1890ff;
display: flex;
align-items: center;
gap: 4px;
gap: 6px;
padding: 6px 12px;
background: rgba(24, 144, 255, 0.1);
border-radius: 20px;
transition: all 0.3s ease;
box-shadow: 0 1px 3px rgba(24, 144, 255, 0.2);
}
.coupon-value:hover {
background: rgba(24, 144, 255, 0.2);
transform: scale(1.05);
box-shadow: 0 2px 6px rgba(24, 144, 255, 0.3);
}
.coupon-discount {
padding: 12px 16px;
padding: 14px 20px;
background-color: #f0f9ff;
border-top: 1px solid #e6f7ff;
display: flex;
@@ -783,13 +812,22 @@ onMounted(() => {
.discount-label {
font-size: 14px;
color: #333;
color: #666;
display: flex;
align-items: center;
gap: 6px;
}
.discount-label::before {
content: "💰";
font-size: 14px;
}
.discount-amount {
font-size: 16px;
font-weight: 600;
font-size: 18px;
font-weight: 700;
color: #1890ff;
text-shadow: 0 1px 2px rgba(24, 144, 255, 0.3);
}
.discount {
+7 -7
View File
@@ -82,6 +82,13 @@ const formState = reactive({
confirmPassword: ''
})
const validateConfirmPassword = (_, value: string) => {
if (value !== formState.password) {
return Promise.reject(new Error('两次输入的密码不一致'))
}
return Promise.resolve()
}
const formRules = {
password: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
@@ -94,13 +101,6 @@ const formRules = {
]
}
const validateConfirmPassword = (_, value: string) => {
if (value !== formState.password) {
return Promise.reject(new Error('两次输入的密码不一致'))
}
return Promise.resolve()
}
const handleSubmit = async () => {
if (!formRef.value) return
+94 -12
View File
@@ -69,7 +69,27 @@
</div>
</div>
<div class="tags">
<el-tag size="small" effect="light" style="margin-right: 8px; margin-bottom: 8px">
<el-tag
v-for="tag in product.tagInfos"
:key="tag.id"
size="small"
effect="light"
:style="{
marginRight: '8px',
marginBottom: '8px',
color: tag.textColor || '#409eff',
backgroundColor: tag.bgColor || '#ecf5ff',
borderColor: tag.borderColor || '#409eff'
}"
>
{{ tag.tagName }}
</el-tag>
<el-tag
v-if="!product.tagInfos || product.tagInfos.length === 0"
size="small"
effect="light"
style="margin-right: 8px; margin-bottom: 8px"
>
{{ product.category }}
</el-tag>
</div>
@@ -96,8 +116,9 @@ import { ArrowLeft, Star, Clock, Collection, ShoppingCart, Right } from '@elemen
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productApi, type ProductVO } from '@/api/product'
import { cartApi } from '@/api/cart'
import { wishlistApi } from '@/api/wishlist'
import { fileApi } from '@/api/file'
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
@@ -122,6 +143,8 @@ const product = ref<ProductVO>({
const isFavorite = ref(false)
const currentImageIndex = ref(0)
const productImages = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
// 从后端获取商品详情
const fetchProductDetail = async () => {
@@ -133,18 +156,59 @@ const fetchProductDetail = async () => {
product.value = response || {}
await loadProductImages()
await checkWishlistStatus()
} catch (error) {
console.error('获取商品详情失败:', error)
ElMessage.error('未登录,请先登录')
}
}
// 检查商品是否在收藏列表中
const checkWishlistStatus = async () => {
if (product.value.id) {
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (!token) {
isFavorite.value = false
return
}
try {
const status = await wishlistApi.checkWishlist(product.value.id)
isFavorite.value = status
} catch (error) {
console.error('检查收藏状态失败:', error)
isFavorite.value = false
}
}
}
// 加载商品图片
const loadProductImages = async () => {
// 由于ProductVO类型中没有imageFileIds属性,这里简化处理
if (product.value.image) {
productImages.value = [product.value.image]
currentImageIndex.value = 0
if (product.value.imageFileIds) {
const ids = product.value.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
if (!imageIdCache.value[id]) {
const response = await fileApi.getSignedUrl(Number(id)) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id])
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
}
if (urls.length > 0) {
productImages.value = urls
currentImageIndex.value = 0
}
} else {
productImages.value = [DEFAULT_PRODUCT_IMAGE]
}
}
@@ -158,10 +222,23 @@ const handleBackClick = () => {
router.back()
}
const handleFavoriteClick = () => {
isFavorite.value = !isFavorite.value
console.log('收藏状态:', isFavorite.value)
ElMessage.success(isFavorite.value ? '已收藏' : '已取消收藏')
const handleFavoriteClick = async () => {
if (!product.value.id) return
try {
if (isFavorite.value) {
await wishlistApi.removeFromWishlist(product.value.id)
ElMessage.success('已取消收藏')
} else {
await wishlistApi.addToWishlist(product.value.id)
ElMessage.success('已收藏')
}
isFavorite.value = !isFavorite.value
console.log('收藏状态:', isFavorite.value)
} catch (error) {
console.error('操作收藏失败:', error)
ElMessage.error('操作失败,请重试')
}
}
const handleAddToCart = async () => {
@@ -174,7 +251,7 @@ const handleAddToCart = async () => {
console.log('调用cartApi.addToCart成功')
// 实时更新购物车角标数字
await updateCartCount()
ElMessage.success(`已将 ${product.value.name} 添加到购物车`)
ElMessage.success(`已将 ${product.value.title || product.value.name || '商品'} 添加到购物车`)
} catch (error) {
console.error('添加到购物车失败:', error)
ElMessage.error('添加到购物车失败,请重试')
@@ -247,7 +324,12 @@ onMounted(() => {
}
.actions .active {
color: #ff4d4f;
color: #FFD700;
fill: #FFD700;
}
.actions .active svg {
fill: #FFD700;
}
.product-image-container {
+67 -10
View File
@@ -42,13 +42,13 @@
<!-- 商品图片 -->
<div class="product-img">
<img
v-if="item.image"
:src="item.image"
:alt="item.name"
v-if="getProductImages(item) && getProductImages(item).length > 0"
:src="getProductImages(item)[0]"
:alt="item.title || item.name"
class="product-image"
/>
<div v-else class="product-img-placeholder">
<span>{{ item.name ? item.name[0] : '商' }}</span>
<span>{{ (item.title || item.name) ? (item.title || item.name)[0] : '商' }}</span>
</div>
<a-badge
v-if="item.category"
@@ -59,7 +59,7 @@
</div>
<!-- 商品信息 -->
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p class="name">{{ item.title || item.name }}</p>
<div class="product-meta">
<span class="duration">{{ item.estimatedTime }} 分钟</span>
<div class="stats">
@@ -69,7 +69,28 @@
</div>
<!-- 标签展示 -->
<div class="product-tags">
<template v-if="item.category">
<template v-if="item.tagInfos && item.tagInfos.length > 0">
<a-tag
v-for="tag in item.tagInfos"
:key="tag.id"
size="small"
:style="{
marginRight: '4px',
marginBottom: '4px',
fontSize: '9px',
padding: '1px 6px',
color: tag.textColor || '#333333',
backgroundColor: tag.bgColor || '#F0F0F0',
borderColor: tag.borderColor || '#F0F0F0',
borderWidth: '1px',
borderStyle: 'solid',
borderRadius: '8px'
}"
>
{{ tag.tagName }}
</a-tag>
</template>
<template v-else-if="item.category">
<a-tag
size="small"
:style="{
@@ -136,8 +157,8 @@ import {
import { message } from 'ant-design-vue'
import { productApi, type ProductVO } from '@/api/product'
import { tagApi, type TagVO } from '@/api/tag'
import { cartApi } from '@/api/cart'
import { fileApi } from '@/api/file'
const router = useRouter()
@@ -159,7 +180,10 @@ const hasMore = ref(true)
// 加载状态
const loading = ref(false)
// 图片ID缓存
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<number, string[]>>({})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
// 从后端获取标签列表
const fetchTags = async () => {
@@ -172,7 +196,38 @@ const fetchTags = async () => {
}
}
// 加载商品图片
const loadImageUrls = async (productList: ProductVO[]) => {
for (const product of productList) {
if (product.imageFileIds) {
const ids = product.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
if (!imageIdCache.value[id]) {
const response = await fileApi.getSignedUrl(Number(id)) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id])
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
}
imageUrls.value[product.id] = urls
} else {
imageUrls.value[product.id] = [DEFAULT_PRODUCT_IMAGE]
}
}
}
const getProductImages = (product: ProductVO): string[] => {
return imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
}
// 从后端获取商品数据
const fetchProducts = async () => {
@@ -191,6 +246,8 @@ const fetchProducts = async () => {
console.log('Products response:', response)
products.value = response || []
await loadImageUrls(products.value)
console.log('Processed products:', products.value)
hasMore.value = false
@@ -226,10 +283,10 @@ const handleProductClick = (item: any) => {
// 处理添加到购物车
const handleAddToCart = async (item: any) => {
console.log('添加到购物车:', item.name)
console.log('添加到购物车:', item.title || item.name)
try {
await cartApi.addToCart({ productId: item.id, quantity: 1 })
message.success(`已将 ${item.name} 添加到购物车`)
message.success(`已将 ${item.title || item.name || '商品'} 添加到购物车`)
} catch (error) {
console.error('添加到购物车失败:', error)
message.error('添加到购物车失败,请重试')
+15 -1
View File
@@ -68,7 +68,7 @@
<div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
<HeartOutlined />
</div>
<a-statistic title="收藏" :value="5" />
<a-statistic title="收藏" :value="wishlistCount" />
</div>
</a-col>
<a-col :span="8">
@@ -215,6 +215,7 @@ import { userApi, type UserVO } from '@/api/user'
import { fileApi } from '@/api/file'
import { orderApi } from '@/api/order'
import { couponApi } from '@/api/coupon'
import { wishlistApi } from '@/api/wishlist'
import { DEFAULT_AVATAR } from '@/constants'
const router = useRouter()
@@ -243,6 +244,7 @@ const orders = ref<any[]>([])
const loading = ref(false)
const orderCount = ref(0)
const couponCount = ref(0)
const wishlistCount = ref(0)
const editForm = ref({
nickname: '',
@@ -495,6 +497,8 @@ onMounted(() => {
loadOrders()
// 异步加载优惠券数量
loadCouponCount()
// 异步加载收藏数量
loadWishlistCount()
})
// 加载优惠券数量
@@ -506,6 +510,16 @@ const loadCouponCount = async () => {
console.error('获取优惠券数量失败:', error)
}
}
// 加载收藏数量
const loadWishlistCount = async () => {
try {
const response = await wishlistApi.getWishlist() as any
wishlistCount.value = response.length
} catch (error) {
console.error('获取收藏数量失败:', error)
}
}
</script>
<style scoped>
+112 -24
View File
@@ -6,24 +6,29 @@
<div class="back-btn" @click="handleBackClick">
<el-icon><ArrowLeft /></el-icon>
</div>
<h1>Wishlist</h1>
<h1>我的收藏</h1>
<div class="empty"></div>
</header>
<!-- Wishlist Items -->
<div class="wishlist-items">
<div v-for="item in wishlistItems" :key="item.id" class="wishlist-item">
<div class="item-image" :style="{ backgroundColor: item.bgColor }">
<span>{{ item.name[0] }}</span>
<div class="item-image" @click="handleProductClick(item.product.id)">
<img v-if="getProductImages(item.product) && getProductImages(item.product).length > 0"
:src="getProductImages(item.product)[0]"
:alt="item.product.title" />
<div v-else class="image-placeholder" :style="{ backgroundColor: getRandomColor() }">
<span>{{ item.product.title ? item.product.title[0] : '商' }}</span>
</div>
</div>
<div class="item-details">
<h3 class="item-name">{{ item.name }}</h3>
<p class="item-price">${{ item.price }}</p>
<h3 class="item-name" @click="handleProductClick(item.product.id)">{{ item.product.title }}</h3>
<p class="item-price">¥{{ item.product.price }}</p>
<div class="item-actions">
<el-button size="small" type="primary" @click="handleAddToCart(item)">
Add to Cart
<el-button size="small" type="primary" @click="handleAddToCart(item.product.id)">
添加到购物车
</el-button>
<el-icon class="delete-icon" @click="handleRemoveItem(item)"><Delete /></el-icon>
<el-icon class="delete-icon" @click="handleRemoveItem(item.product.id)"><Delete /></el-icon>
</div>
</div>
</div>
@@ -32,42 +37,96 @@
<!-- Empty Wishlist Message -->
<div v-if="wishlistItems.length === 0" class="empty-wishlist">
<el-icon :size="60"><Star /></el-icon>
<p>Your wishlist is empty</p>
<p>收藏列表为空</p>
<el-button type="primary" @click="handleBrowseProducts">
Browse Products
浏览商品
</el-button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ref, onMounted } from 'vue'
import { ArrowLeft, Delete, Star } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { wishlistApi, type WishlistItem } from '@/api/wishlist'
import { cartApi } from '@/api/cart'
import { fileApi } from '@/api/file'
const router = useRouter()
const wishlistItems = ref([
{ id: 1, name: 'Watch', price: 40, bgColor: '#ffe4d6' },
{ id: 2, name: 'LG TV', price: 330, bgColor: '#f0d6ff' },
{ id: 3, name: 'Jacket', price: 50, bgColor: '#ffd6e2' },
{ id: 4, name: 'Nike Shoes', price: 430, bgColor: '#d6eaff' }
])
const wishlistItems = ref<WishlistItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<number, string[]>>({})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
const handleBackClick = () => {
console.log('返回按钮被点击')
router.back()
}
const handleAddToCart = (item: any) => {
console.log('添加到购物车:', item.name)
const fetchWishlist = async () => {
try {
const response = await wishlistApi.getWishlist()
wishlistItems.value = response
await loadImageUrls(response)
} catch (error) {
console.error('获取收藏列表失败:', error)
ElMessage.error('获取收藏列表失败')
}
}
const handleRemoveItem = (item: any) => {
console.log('从收藏夹移除:', item.name)
const index = wishlistItems.value.findIndex(i => i.id === item.id)
if (index > -1) {
wishlistItems.value.splice(index, 1)
const loadImageUrls = async (items: WishlistItem[]) => {
for (const item of items) {
if (item.product.imageFileIds) {
const ids = item.product.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
if (!imageIdCache.value[id]) {
const response = await fileApi.getSignedUrl(Number(id)) as any
imageIdCache.value[id] = response
}
urls.push(imageIdCache.value[id])
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
}
imageUrls.value[item.product.id] = urls
} else {
imageUrls.value[item.product.id] = [DEFAULT_PRODUCT_IMAGE]
}
}
}
const getProductImages = (product: any): string[] => {
return imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
}
const handleAddToCart = async (productId: number) => {
try {
await cartApi.addToCart({ productId, quantity: 1 })
ElMessage.success('已添加到购物车')
} catch (error) {
console.error('添加到购物车失败:', error)
ElMessage.error('添加到购物车失败')
}
}
const handleRemoveItem = async (productId: number) => {
try {
await wishlistApi.removeFromWishlist(productId)
wishlistItems.value = wishlistItems.value.filter(item => item.productId !== productId)
ElMessage.success('已从收藏中移除')
} catch (error) {
console.error('移除收藏失败:', error)
ElMessage.error('移除收藏失败')
}
}
@@ -75,6 +134,19 @@ const handleBrowseProducts = () => {
console.log('浏览商品')
router.push('/products')
}
const handleProductClick = (productId: number) => {
router.push(`/product/${productId}`)
}
const getRandomColor = () => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)]
}
onMounted(() => {
fetchWishlist()
})
</script>
<style scoped>
@@ -121,6 +193,22 @@ const handleBrowseProducts = () => {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
cursor: pointer;
}
.item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
font-weight: bold;
color: rgba(0,0,0,0.1);
+3 -3
View File
@@ -330,10 +330,10 @@
>
<a-select-option
v-for="artist in artists"
:key="artist.id"
:value="artist.id.toString()"
:key="artist?.id"
:value="artist?.id?.toString()"
>
{{ artist.nickname }}
{{ artist?.nickname || '' }}
</a-select-option>
</a-select>
</a-form-item>
+4 -3
View File
@@ -534,14 +534,15 @@ const handleDelete = async (record: UserVO) => {
return
}
// 在删除前先重命名账号,添加删除时间戳
// 在删除前先重命名账号和手机号,添加删除时间戳
const timestamp = new Date().getTime()
const newAccount = `${record.account}_deleted_${timestamp}`
const newPhone = `${record.phone}_deleted_${timestamp}`
try {
await userApi.updateUser(record.id, { account: newAccount })
await userApi.updateUser(record.id, { account: newAccount, phone: newPhone })
} catch (renameError) {
console.error('重命名账号失败:', renameError)
console.error('重命名账号和手机号失败:', renameError)
// 重命名失败也继续删除流程
}
@@ -78,12 +78,11 @@ public class TagController {
}
/**
* 查询所有标签
* 查询所有标签(公开接口,不需要权限)
*
* @return 标签VO列表
*/
@GetMapping("/list/all")
@RequirePermission("tag:view")
public Result<List<TagVO>> listAllTags() {
List<TagVO> tagVOs = tagService.listAllTags();
return Result.success(tagVOs);
@@ -10,6 +10,8 @@ import com.xiaowang.yuminailcore.dto.RegisterRequestDTO;
import com.xiaowang.yuminailcore.dto.SendVerificationCodeRequestDTO;
import com.xiaowang.yuminailcore.dto.UpdatePhoneRequestDTO;
import com.xiaowang.yuminailcore.dto.UserDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.UserVO;
import com.xiaowang.yuminailcore.service.MinioService;
@@ -39,6 +41,7 @@ public class UserController {
private final UserService userService;
private final MinioService minioService;
private final VerificationCodeService verificationCodeService;
private final UserMapper userMapper;
/**
* 创建用户
@@ -326,6 +329,46 @@ public class UserController {
return Result.success(success);
}
/**
* 注销账号
*
* @param request 请求对象
* @return 是否注销成功
*/
@DeleteMapping("/deactivate")
public Result<Boolean> deactivateAccount(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
// 获取用户信息
UserDO userDO = userMapper.selectById(userId);
if (userDO == null) {
return Result.error("用户不存在");
}
// 管理员账号无法注销
if (userDO.getType() == 4) {
return Result.error("管理员账号无法注销");
}
// 在删除前先重命名账号和手机号,添加删除时间戳
String timestamp = String.valueOf(System.currentTimeMillis());
String newAccount = userDO.getAccount() + "_deleted_" + timestamp;
String newPhone = userDO.getPhone() + "_deleted_" + timestamp;
try {
UserDTO updateDTO = new UserDTO();
updateDTO.setAccount(newAccount);
updateDTO.setPhone(newPhone);
userService.updateUser(userId, updateDTO);
} catch (Exception e) {
System.out.println("重命名账号和手机号失败: " + e.getMessage());
// 重命名失败也继续删除流程
}
boolean success = userService.deleteUser(userId);
return Result.success(success);
}
@Data
public static class PasswordDTO {
private String password;
@@ -16,4 +16,6 @@ public class LoginRequestDTO {
private String password;
private Boolean rememberMe;
private Long shopId;
}
@@ -20,4 +20,6 @@ public class PhoneLoginRequestDTO {
@NotBlank(message = "验证码不能为空")
@Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字")
private String verificationCode;
private Long shopId;
}
@@ -162,6 +162,20 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
"tag:view", "tag:create", "tag:edit", "tag:assign",
"coupon:view", "coupon:assign", "order:view", "order:process")
);
} else if (userType == 0) { // 普通用户
// 分配普通用户默认权限
// 首页的查看权限
// 仪表盘的查看权限
// 商品查看权限
// 标签查看权限
// 店铺查看权限
// 订单查看权限
permissions = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getIsDelete, 0)
.in(PermissionDO::getPermissionCode, "home:view", "dashboard:view",
"product:view", "tag:view", "shop:view", "order:view")
);
}
if (permissions != null && !permissions.isEmpty()) {
@@ -379,6 +393,16 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("密码错误");
}
// 检查是否需要设置店铺
if (userDO.getShopId() == null || userDO.getShopId() == 0) {
if (loginRequestDTO.getShopId() == null || loginRequestDTO.getShopId() == 0) {
throw new RuntimeException("请选择店铺");
}
userDO.setShopId(loginRequestDTO.getShopId());
userDO.setUpdateTime(LocalDateTime.now());
userMapper.updateById(userDO);
}
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
@@ -411,7 +435,19 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
);
if (userDO == null) {
userDO = registerByPhone(phoneLoginRequestDTO.getPhone());
if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) {
throw new RuntimeException("首次登录需要选择店铺");
}
userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId());
} else {
if (userDO.getShopId() == null || userDO.getShopId() == 0) {
if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) {
throw new RuntimeException("请选择店铺");
}
userDO.setShopId(phoneLoginRequestDTO.getShopId());
userDO.setUpdateTime(LocalDateTime.now());
userMapper.updateById(userDO);
}
}
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
@@ -430,7 +466,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userInfo.setCreateTime(userDO.getCreateTime());
responseVO.setUserInfo(userInfo);
// 设置是否需要设置密码
responseVO.setNeedSetPassword(ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
return responseVO;
@@ -440,7 +475,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private static final String UNSET_PASSWORD_MARKER = "__UNSET_PASSWORD__";
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识
private UserDO registerByPhone(String phone) {
private UserDO registerByPhone(String phone, Long shopId) {
UserDO userDO = new UserDO();
userDO.setAccount(phone);
userDO.setPhone(phone);
@@ -448,12 +483,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userDO.setNickname("用户" + phone.substring(7));
userDO.setType(0);
userDO.setLevel("普通");
userDO.setShopId(0L);
userDO.setShopId(shopId);
userDO.setIsDelete(0);
userDO.setStatus(1);
userDO.setCreateTime(LocalDateTime.now());
userDO.setUpdateTime(LocalDateTime.now());
// 设置未设置密码的特殊标识
userDO.setPassword(ENCODED_UNSET_PASSWORD);
userMapper.insert(userDO);
@@ -511,7 +545,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
);
if (existingUser != null) {
throw new RuntimeException("账号已存在");
if (existingUser.getIsDelete() == 0) {
throw new RuntimeException("账号已存在");
} else {
throw new RuntimeException("该账号已被注销,请使用手机号验证码登录");
}
}
UserDO existingPhoneUser = userMapper.selectOne(
@@ -235,7 +235,7 @@ create table t_user
shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)',
nickname varchar(50) not null comment '用户昵称',
account varchar(50) not null comment '用户账号(登录用)',
phone varchar(20) null comment '手机号',
phone varchar(50) null comment '手机号',
email varchar(100) null comment '邮箱',
phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证',
email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证',
@@ -576,4 +576,25 @@ create table t_order_item
) comment '订单商品表';
create index idx_order_id
on t_order_item (order_id) comment '按订单查询商品的索引';
on t_order_item (order_id) comment '按订单查询商品的索引';
-- 商品收藏表
create table t_wishlist
(
id bigint unsigned auto_increment comment '收藏记录唯一主键ID'
primary key comment '商品收藏主键索引',
user_id bigint unsigned not null comment '关联用户表主键',
product_id bigint unsigned not null comment '关联商品表主键',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除',
constraint uk_user_product
unique (user_id, product_id) comment '用户-商品唯一索引'
) comment '商品收藏表';
create index idx_user_id
on t_wishlist (user_id) comment '按用户查询收藏的索引';
create index idx_product_id
on t_wishlist (product_id) comment '按商品查询收藏的索引';
@@ -69,6 +69,12 @@ spring:
- Path=/api/order/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: wishlist-route
uri: lb://yumi-nail-core
predicates:
- Path=/api/wishlist/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
# 后台管理API路由
- id: admin-route
uri: lb://yumi-nail-core