购物车和订单中心以及优惠券相关功能初版

This commit is contained in:
xiaowang
2026-02-27 16:44:41 +08:00
parent 3529a73d84
commit 43f31eed53
36 changed files with 1785 additions and 24 deletions
+9 -6
View File
@@ -17,12 +17,15 @@ const adminApi = axios.create({
adminApi.interceptors.request.use(
config => {
let token = localStorage.getItem('adminAccessToken')
if (!token) {
token = sessionStorage.getItem('adminAccessToken')
}
if (token) {
config.headers.Authorization = `Bearer ${token}`
// 登录请求不需要携带Token
if (!config.url?.includes('/auth/login')) {
let token = localStorage.getItem('adminAccessToken')
if (!token) {
token = sessionStorage.getItem('adminAccessToken')
}
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
}
return config
},
+4
View File
@@ -44,6 +44,10 @@ export const authApi = {
return api.post<LoginResponse>('/user/login', data)
},
adminLogin: (data: LoginRequest) => {
return api.post<LoginResponse>('/admin/api/auth/login', data)
},
register: (data: RegisterRequest) => {
return api.post('/user/register', data)
},
+33
View File
@@ -0,0 +1,33 @@
import api from './index'
interface CartItem {
productId: number
quantity: number
}
export const cartApi = {
// 添加商品到购物车
addToCart: (item: CartItem) => {
return api.post('/cart/add', item)
},
// 从购物车移除商品
removeFromCart: (productId: number) => {
return api.delete(`/cart/remove/${productId}`)
},
// 更新购物车商品数量
updateCartQuantity: (item: CartItem) => {
return api.put('/cart/update', item)
},
// 获取购物车列表
getCartList: () => {
return api.get('/cart/list')
},
// 清空购物车
clearCart: () => {
return api.delete('/cart/clear')
}
}
+2 -1
View File
@@ -102,7 +102,8 @@ api.interceptors.response.use(
return url?.includes('/user/login') ||
url?.includes('/user/register') ||
url?.includes('/user/refresh-token') ||
url?.includes('/shop/list/simple')
url?.includes('/shop/list/simple') ||
url?.includes('/admin/login')
}
if (error.response?.status === 401) {
+39
View File
@@ -0,0 +1,39 @@
import api from './index'
interface CreateOrderRequest {
couponId?: number
}
export const orderApi = {
// 创建订单
createOrder: (data: CreateOrderRequest) => {
return api.post('/order/create', data)
},
// 获取订单列表
getOrderList: () => {
return api.get('/order/list')
},
// 获取订单详情
getOrderDetail: (orderId: number) => {
return api.get(`/order/detail/${orderId}`)
},
// 取消订单
cancelOrder: (orderId: number) => {
return api.put(`/order/cancel/${orderId}`)
},
// 后台获取所有订单
getAllOrders: () => {
return api.get('/order/admin/list')
},
// 后台处理订单
processOrder: (orderId: number, status: number) => {
return api.put(`/order/admin/process/${orderId}`, {}, {
params: { status }
})
}
}
+16 -10
View File
@@ -5,16 +5,16 @@ const router = createRouter({
routes: [
{
path: '/',
name: 'home',
component: () => import('../views/HomeView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/auth',
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: true, isAdmin: false }
},
{
path: '/products',
name: 'products',
@@ -123,6 +123,12 @@ const router = createRouter({
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'order:view' }
}
]
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFoundView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
}
]
})
@@ -226,11 +232,11 @@ router.beforeEach((to, _from, next) => {
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (requiresAuth && !token) {
next('/auth')
} else if (to.path === '/auth' && token) {
next('/')
} else if (to.path === '/' && !token) {
next('/auth')
} else if (to.path === '/' && token) {
next('/home')
} else if (to.path === '/home' && !token) {
next('/')
} else {
next()
}
+138
View File
@@ -0,0 +1,138 @@
<template>
<div class="not-found-container">
<div class="not-found-content">
<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">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const countdown = ref(5)
let timer: number | null = null
const redirectToHome = () => {
if (timer) {
clearInterval(timer)
}
router.push('/home')
}
onMounted(() => {
timer = window.setInterval(() => {
if (countdown.value > 0) {
countdown.value--
} else {
if (timer) {
clearInterval(timer)
}
redirectToHome()
}
}, 1000)
})
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
</script>
<style scoped>
.not-found-container {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.not-found-content {
background: white;
border-radius: 20px;
padding: 60px 40px;
text-align: center;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
max-width: 500px;
width: 100%;
}
.error-code {
font-size: 120px;
font-weight: bold;
color: #667eea;
margin: 0 0 20px 0;
line-height: 1;
}
.not-found-content h1 {
font-size: 28px;
font-weight: 700;
color: #333;
margin: 0 0 16px 0;
}
.not-found-content p {
font-size: 16px;
color: #666;
margin: 0 0 24px 0;
line-height: 1.6;
}
.redirect-message {
margin: 20px 0 30px 0;
color: #999;
font-size: 14px;
}
.countdown {
color: #667eea;
font-weight: bold;
font-size: 18px;
margin: 0 4px;
}
:deep(.ant-btn-primary) {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
padding: 12px 32px;
font-size: 16px;
font-weight: 600;
border-radius: 25px;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
transition: all 0.3s ease;
}
:deep(.ant-btn-primary:hover) {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
@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>
+333
View File
@@ -0,0 +1,333 @@
<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="placeholder"></div>
</header>
<!-- 订单列表 -->
<div class="order-section">
<a-empty v-if="orders.length === 0" description="暂无订单">
<a-button type="primary" @click="handleBrowseProducts">去购物</a-button>
</a-empty>
<div v-else class="order-list">
<a-card v-for="order in orders" :key="order.id" class="order-card">
<div class="order-header">
<span class="order-no">订单号: {{ order.orderNo }}</span>
<span :class="['order-status', order.status === 1 ? 'pending' : order.status === 2 ? 'completed' : 'cancelled']">
{{ order.statusText }}
</span>
</div>
<div class="order-items">
<div v-for="item in order.items" :key="item.id" class="order-item">
<div class="item-image" v-if="item.productImage">
<img :src="item.productImage" :alt="item.productTitle" />
</div>
<div class="item-image" v-else :style="{ backgroundColor: getRandomColor() }">
<span>{{ item.productTitle[0] }}</span>
</div>
<div class="item-info">
<div class="item-title">{{ item.productTitle }}</div>
<div class="item-price">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
</div>
</div>
</div>
<div class="order-footer">
<div class="order-total">
总计: <span class="total-price">¥{{ order.actualAmount.toFixed(2) }}</span>
</div>
<div class="order-actions">
<a-button v-if="order.status === 1" size="small" danger @click="handleCancelOrder(order.id)">
取消订单
</a-button>
</div>
</div>
</a-card>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { orderApi } from '../api/order'
import { fileApi } from '../api/index'
const router = useRouter()
// 订单相关状态
const orders = ref<any[]>([])
const loading = ref(false)
// 图片缓存
const imageIdCache = ref<Record<string, string>>({})
// 加载订单列表
const loadOrders = async () => {
loading.value = true
try {
const data = await orderApi.getOrderList()
orders.value = data
// 加载商品图片的临时加签链接
await loadProductImages(orders.value)
} catch (error) {
message.error('获取订单列表失败')
} finally {
loading.value = false
}
}
// 加载商品图片
const loadProductImages = async (orders: any[]) => {
for (const order of orders) {
if (order.items && order.items.length > 0) {
for (const item of order.items) {
if (item.productImage) {
// 过滤掉HTML标签
const cleanImageUrl = item.productImage.replace(/<[^>]*>/g, '')
// 从cleanImageUrl中提取图片ID
// 假设图片URL的格式为 '/api/file/get/123'
const match = cleanImageUrl.match(/\/api\/file\/get\/(\d+)/)
if (match && match[1]) {
const imageId = match[1]
try {
// 检查缓存
if (!imageIdCache.value[imageId]) {
const signedUrl = await fileApi.getSignedUrl(Number(imageId))
imageIdCache.value[imageId] = signedUrl
}
// 更新商品图片为临时加签链接
item.productImage = imageIdCache.value[imageId]
} catch (error) {
console.error('获取图片签名链接失败:', error)
// 如果获取签名链接失败,清除无效的图片URL
item.productImage = ''
}
} else {
// 如果不是有效的图片URL格式,清除无效的图片URL
item.productImage = ''
}
}
}
}
}
}
// 处理取消订单
const handleCancelOrder = async (orderId: number) => {
Modal.confirm({
title: '确认取消订单',
content: '确定要取消这个订单吗?',
onOk: async () => {
try {
await orderApi.cancelOrder(orderId)
message.success('订单已取消')
loadOrders()
} catch (error) {
message.error('取消订单失败')
}
}
})
}
// 处理返回按钮点击
const handleBackClick = () => {
router.back()
}
// 处理浏览商品
const handleBrowseProducts = () => {
router.push('/products')
}
// 生成随机颜色
const getRandomColor = () => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)]
}
// 页面加载时获取订单数据
onMounted(() => {
loadOrders()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.placeholder {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.order-section {
padding: 15px;
padding-bottom: 20px;
}
.order-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.order-card {
border-radius: 12px;
overflow: hidden;
}
.order-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid #f0f0f0;
}
.order-no {
font-size: 14px;
color: #666;
}
.order-status {
font-size: 14px;
font-weight: 600;
padding: 4px 12px;
border-radius: 12px;
}
.order-status.pending {
background: #fff7e6;
color: #fa8c16;
}
.order-status.completed {
background: #f6ffed;
color: #52c41a;
}
.order-status.cancelled {
background: #fff1f0;
color: #ff4d4f;
}
.order-items {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 15px;
}
.order-item {
display: flex;
gap: 12px;
align-items: center;
}
.item-image {
width: 60px;
height: 60px;
border-radius: 8px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
font-weight: bold;
color: rgba(0,0,0,0.1);
flex-shrink: 0;
overflow: hidden;
}
.item-image img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
}
.item-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 4px;
}
.item-title {
font-size: 14px;
font-weight: 600;
color: #1a1a2e;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.item-price {
font-size: 13px;
color: #666;
}
.order-footer {
display: flex;
justify-content: space-between;
align-items: center;
padding-top: 10px;
border-top: 1px solid #f0f0f0;
}
.order-total {
font-size: 14px;
color: #666;
}
.total-price {
font-size: 16px;
font-weight: 700;
color: #ff4d4f;
}
.order-actions {
display: flex;
gap: 8px;
}
</style>
+5 -2
View File
@@ -42,11 +42,11 @@
<a-card :bordered="false" class="stats-card">
<a-row :gutter="16">
<a-col :span="8">
<div class="stat-item">
<div class="stat-item" @click="router.push('/orders')" style="cursor: pointer;">
<div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
<ShoppingOutlined />
</div>
<a-statistic title="订单" :value="12" />
<a-statistic title="订单" :value="orderCount" />
</div>
</a-col>
<a-col :span="8">
@@ -251,6 +251,7 @@ const activeTab = ref('')
const orders = ref<any[]>([])
const coupons = ref<any[]>([])
const loading = ref(false)
const orderCount = ref(0)
const editForm = ref({
nickname: '',
@@ -396,6 +397,7 @@ const loadOrders = async () => {
try {
const data = await orderApi.getOrderList()
orders.value = data
orderCount.value = data.length
} catch (error) {
message.error('获取订单列表失败')
} finally {
@@ -497,6 +499,7 @@ const getRandomColor = () => {
onMounted(() => {
fetchUserInfo()
loadOrders()
})
</script>
+3 -2
View File
@@ -308,8 +308,9 @@ const fetchCoupons = async () => {
loading.value = true
try {
const res = await adminCouponApi.listAllCoupons()
couponList.value = res || []
pagination.total = res.length || 0
// 处理后端返回的分页数据结构
couponList.value = res?.list || []
pagination.total = res?.total || 0
} catch (error) {
message.error('获取优惠券列表失败')
} finally {
+149
View File
@@ -0,0 +1,149 @@
<template>
<div class="orders-view">
<h1>订单管理</h1>
<div class="orders-table">
<table>
<thead>
<tr>
<th>订单编号</th>
<th>用户ID</th>
<th>总金额</th>
<th>实际金额</th>
<th>优惠券</th>
<th>状态</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="order in orders" :key="order.id">
<td>{{ order.orderNo }}</td>
<td>{{ order.userId }}</td>
<td>{{ order.totalAmount }}</td>
<td>{{ order.actualAmount }}</td>
<td>{{ order.couponName || '无' }}</td>
<td>{{ order.statusText }}</td>
<td>{{ order.createTime }}</td>
<td>
<div class="order-actions">
<button v-if="order.status === 1" @click="processOrder(order.id, 2)" class="btn btn-success">
确认完成
</button>
<button v-if="order.status === 1" @click="processOrder(order.id, 3)" class="btn btn-danger">
取消订单
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { orderApi } from '../../api/order'
import { message } from 'ant-design-vue'
interface Order {
id: number
orderNo: string
userId: number
totalAmount: number
actualAmount: number
couponId: number | null
couponName: string | null
status: number
statusText: string
createTime: string
items: any[]
}
const orders = ref<Order[]>([])
const loadOrders = async () => {
try {
const data = await orderApi.getAllOrders()
orders.value = data
} catch (error) {
message.error('获取订单列表失败')
}
}
const processOrder = async (orderId: number, status: number) => {
try {
await orderApi.processOrder(orderId, status)
message.success('操作成功')
loadOrders()
} catch (error) {
message.error('操作失败')
}
}
onMounted(() => {
loadOrders()
})
</script>
<style scoped>
.orders-view {
padding: 20px;
}
h1 {
margin-bottom: 20px;
font-size: 24px;
color: #333;
}
.orders-table {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #e8e8e8;
}
th {
background-color: #f5f5f5;
font-weight: 600;
}
.order-actions {
display: flex;
gap: 8px;
}
.btn {
padding: 6px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.btn-success {
background-color: #52c41a;
color: white;
}
.btn-danger {
background-color: #ff4d4f;
color: white;
}
.btn:hover {
opacity: 0.8;
}
</style>
+8 -1
View File
@@ -217,6 +217,7 @@
placeholder="请选择优惠券"
style="width: 100%"
:loading="loadingCoupons"
:disabled="!isShopOwner()"
>
<a-select-option
v-if="coupons.length === 0"
@@ -331,6 +332,11 @@ const getCurrentUserInfo = () => {
return null
}
const isShopOwner = () => {
const userInfo = getCurrentUserInfo()
return userInfo && userInfo.type === 2
}
const fetchShops = async () => {
loadingShops.value = true
try {
@@ -397,7 +403,8 @@ const fetchCoupons = async () => {
loadingCoupons.value = true
try {
const res = await adminCouponApi.listAllCoupons()
coupons.value = res || []
// 处理后端返回的分页数据结构
coupons.value = res?.list || []
} catch (error) {
console.error('获取优惠券列表失败', error)
message.error('获取优惠券列表失败')