功能:完善评论测试与优惠券最优选择

This commit is contained in:
xiaowang
2026-05-16 14:28:42 +08:00
parent 1f05e0ab44
commit 4563dd2538
31 changed files with 1130 additions and 581 deletions
+24
View File
@@ -0,0 +1,24 @@
const request = require('../utils/request')
module.exports = {
listByProduct(productId) {
return request({
url: `/comment/list/product/${productId}`
})
},
create(data) {
return request({
url: '/comment/create',
method: 'POST',
data
})
},
delete(id) {
return request({
url: `/comment/delete/${id}`,
method: 'DELETE'
})
}
}
+3 -4
View File
@@ -242,11 +242,10 @@ Page({
}
if (selectedCouponKey === NO_COUPON_KEY) {
const vipCoupons = list
.filter(item => item.sourceType === 'SYSTEM_VIP')
const bestCoupons = list
.sort((left, right) => calculateCouponDiscount(right, subtotalAmount) - calculateCouponDiscount(left, subtotalAmount))
if (vipCoupons.length) {
selectedCouponKey = vipCoupons[0].key
if (bestCoupons.length) {
selectedCouponKey = bestCoupons[0].key
}
}
+64 -1
View File
@@ -1,6 +1,7 @@
const cartApi = require('../../api/cart')
const productApi = require('../../api/product')
const productLikeApi = require('../../api/product-like')
const commentApi = require('../../api/comment')
const shopApi = require('../../api/shop')
const wishlistApi = require('../../api/wishlist')
const actionGuard = require('../../utils/action-guard')
@@ -65,6 +66,9 @@ Page({
product: null,
productImages: [],
shopInfo: null,
comments: [],
commentText: '',
replyTarget: null,
isFavorite: false,
isLiked: false,
artistCountText: '门店安排',
@@ -122,8 +126,9 @@ Page({
earliestBookableText: estimateEarliestBookable(shopInfo && shopInfo.businessHours)
})
await this.loadComments()
if (auth.isLoggedIn()) {
this.loadInteractionStatus()
await this.loadInteractionStatus()
} else {
this.setData({
isFavorite: false,
@@ -159,6 +164,22 @@ Page({
} catch (error) {}
},
async loadComments() {
const product = this.data.product
if (!product || !product.id) {
this.setData({ comments: [] })
return
}
try {
const comments = await commentApi.listByProduct(product.id)
this.setData({
comments: Array.isArray(comments) ? comments : []
})
} catch (error) {
this.setData({ comments: [] })
}
},
handleBack() {
navigation.goBack('/pages/products/index')
},
@@ -323,4 +344,46 @@ Page({
})
}
}
,
handleCommentInput(event) {
this.setData({
commentText: event.detail.value
})
},
handleReply(event) {
const comment = event.currentTarget.dataset.comment
this.setData({
replyTarget: comment || null
})
},
async handleSubmitComment() {
const product = this.data.product
const content = String(this.data.commentText || '').trim()
if (!product || !product.id || !navigation.ensureLogin('发表评论')) {
return
}
if (!content) {
wx.showToast({ title: '请输入评论内容', icon: 'none' })
return
}
try {
await commentApi.create({
productId: product.id,
shopId: product.shopId,
parentCommentId: this.data.replyTarget ? this.data.replyTarget.id : null,
commentContent: content
})
this.setData({
commentText: '',
replyTarget: null
})
await this.loadComments()
wx.showToast({ title: '评论已发布', icon: 'none' })
} catch (error) {
wx.showToast({ title: error.message || '评论发布失败', icon: 'none' })
}
}
})
@@ -78,6 +78,35 @@
<view class="desc-text">{{product.descriptionText}}</view>
</view>
</view>
<view class="page-card comment-card">
<view class="comment-head">
<view class="section-title">作品评论</view>
<text class="comment-count">{{comments.length}} 条</text>
</view>
<view class="comment-editor">
<textarea class="comment-input" maxlength="300" auto-height placeholder="{{replyTarget ? '回复 ' + (replyTarget.userNickname || '用户') : '说说你的看法'}}" value="{{commentText}}" bindinput="handleCommentInput"></textarea>
<view class="comment-actions">
<view wx:if="{{replyTarget}}" class="comment-cancel" bindtap="handleReply">取消回复</view>
<view class="comment-submit" bindtap="handleSubmitComment">发布</view>
</view>
</view>
<view wx:if="{{!comments.length}}" class="comment-empty">还没有评论,来写第一条吧</view>
<view wx:for="{{comments}}" wx:key="id" class="comment-item">
<view class="comment-main">
<text class="comment-name">{{item.userNickname || '用户'}}</text>
<text class="comment-time">{{item.createTime}}</text>
</view>
<view class="comment-text">{{item.commentContent}}</view>
<view class="comment-reply-btn" data-comment="{{item}}" bindtap="handleReply">回复</view>
<view wx:if="{{item.replies && item.replies.length}}" class="reply-list">
<view wx:for="{{item.replies}}" wx:for-item="reply" wx:key="id" class="reply-item">
<text class="reply-name">{{reply.userNickname || '用户'}}:</text>
<text>{{reply.commentContent}}</text>
</view>
</view>
</view>
</view>
</view>
<view class="footer-bar">
@@ -157,6 +157,116 @@
color: #5d4b55;
}
.comment-card {
margin-top: 24rpx;
padding: 30rpx;
}
.comment-head,
.comment-main,
.comment-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
}
.comment-count,
.comment-time {
font-size: 22rpx;
color: #9b8d94;
}
.comment-editor {
margin-top: 20rpx;
padding: 20rpx;
border-radius: 20rpx;
background: #fff8fa;
}
.comment-input {
width: 100%;
min-height: 120rpx;
font-size: 26rpx;
line-height: 1.7;
color: #2d2430;
}
.comment-actions {
margin-top: 16rpx;
justify-content: flex-end;
}
.comment-cancel,
.comment-submit,
.comment-reply-btn {
font-size: 24rpx;
color: #c6597d;
font-weight: 700;
}
.comment-submit {
min-width: 116rpx;
height: 56rpx;
line-height: 56rpx;
text-align: center;
border-radius: 999rpx;
color: #ffffff;
background: #c6597d;
}
.comment-empty {
padding: 28rpx 0 8rpx;
font-size: 24rpx;
color: #9b8d94;
text-align: center;
}
.comment-item {
padding: 24rpx 0;
border-bottom: 1rpx solid #f2e7eb;
}
.comment-item:last-child {
border-bottom: 0;
}
.comment-name {
font-size: 26rpx;
font-weight: 700;
color: #2d2430;
}
.comment-text {
margin-top: 12rpx;
font-size: 26rpx;
line-height: 1.8;
color: #5d4b55;
}
.comment-reply-btn {
margin-top: 10rpx;
}
.reply-list {
margin-top: 14rpx;
padding: 16rpx;
border-radius: 18rpx;
background: #faf4f6;
}
.reply-item {
padding: 6rpx 0;
font-size: 24rpx;
line-height: 1.7;
color: #5d4b55;
}
.reply-name {
color: #2d2430;
font-weight: 700;
}
.footer-bar {
position: fixed;
left: 24rpx;
+1
View File
@@ -38,6 +38,7 @@ function isWhitelistedPath(url) {
'/user/reset-password-by-phone',
'/product/get/',
'/product/list/',
'/comment/list/product/',
'/shop/get/',
'/shop/list/public',
'/shop/list/simple',
+17
View File
@@ -0,0 +1,17 @@
const request = require('../utils/request')
module.exports = {
listComments(params) {
return request({
url: '/comment/list',
params
})
},
deleteComment(id) {
return request({
url: `/comment/delete/${id}`,
method: 'DELETE'
})
}
}
+5 -4
View File
@@ -10,6 +10,7 @@
"pages/user-form/index",
"pages/products/index",
"pages/product-form/index",
"pages/comments/index",
"pages/coupons/index",
"pages/coupon-form/index",
"pages/coupon-distribute/index",
@@ -38,25 +39,25 @@
"list": [
{
"pagePath": "pages/workbench/index",
"text": "工作台",
"text": "Workbench",
"iconPath": "assets/tabbar/workbench.png",
"selectedIconPath": "assets/tabbar/workbench-active.png"
},
{
"pagePath": "pages/orders/index",
"text": "订单",
"text": "Orders",
"iconPath": "assets/tabbar/orders.png",
"selectedIconPath": "assets/tabbar/orders-active.png"
},
{
"pagePath": "pages/manage/index",
"text": "经营",
"text": "Manage",
"iconPath": "assets/tabbar/manage.png",
"selectedIconPath": "assets/tabbar/manage-active.png"
},
{
"pagePath": "pages/profile/index",
"text": "我的",
"text": "Profile",
"iconPath": "assets/tabbar/profile.png",
"selectedIconPath": "assets/tabbar/profile-active.png"
}
@@ -0,0 +1,71 @@
const commentApi = require('../../api/comment')
Page({
data: {
loading: false,
keyword: '',
comments: []
},
onShow() {
this.loadComments()
},
async onPullDownRefresh() {
await this.loadComments()
wx.stopPullDownRefresh()
},
handleKeywordInput(event) {
this.setData({
keyword: event.detail.value
})
},
async loadComments() {
this.setData({ loading: true })
try {
const comments = await commentApi.listComments({
keyword: this.data.keyword || undefined
})
this.setData({
comments: Array.isArray(comments) ? comments : []
})
} catch (error) {
wx.showToast({
title: error.message || '评论加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
}
},
handleSearch() {
this.loadComments()
},
handleDelete(event) {
const id = event.currentTarget.dataset.id
if (!id) {
return
}
wx.showModal({
title: '删除评论',
content: '确认删除这条评论?',
confirmText: '删除',
success: async res => {
if (!res.confirm) {
return
}
try {
await commentApi.deleteComment(id)
wx.showToast({ title: '评论已删除', icon: 'none' })
this.loadComments()
} catch (error) {
wx.showToast({ title: error.message || '删除失败', icon: 'none' })
}
}
})
}
})
@@ -0,0 +1,21 @@
<navigation-bar title="评论管理" showBack="{{true}}" background="#081518" color="#ffffff"></navigation-bar>
<view class="page">
<view class="search-row">
<input class="search-input" placeholder="搜索评论内容" value="{{keyword}}" bindinput="handleKeywordInput" confirm-type="search" bindconfirm="handleSearch" />
<view class="search-btn" bindtap="handleSearch">搜索</view>
</view>
<view wx:if="{{!comments.length && !loading}}" class="empty">暂无评论</view>
<view wx:for="{{comments}}" wx:key="id" class="comment-card">
<view class="comment-head">
<text class="comment-user">{{item.userNickname || '用户'}}</text>
<text class="comment-time">{{item.createTime}}</text>
</view>
<view class="comment-content">{{item.commentContent}}</view>
<view wx:if="{{item.parentCommentContent}}" class="reply-content">回复:{{item.parentCommentContent}}</view>
<view class="comment-meta">{{item.productTitle || '作品'}} · {{item.shopName || '门店'}}</view>
<view class="delete-btn" data-id="{{item.id}}" bindtap="handleDelete">删除</view>
</view>
</view>
@@ -0,0 +1,94 @@
.page {
min-height: 100vh;
padding: 28rpx 24rpx 60rpx;
background: #0c181b;
}
.search-row {
display: flex;
gap: 16rpx;
margin-bottom: 24rpx;
}
.search-input {
flex: 1;
height: 76rpx;
padding: 0 24rpx;
border-radius: 18rpx;
background: #132529;
color: #ffffff;
font-size: 26rpx;
}
.search-btn {
width: 128rpx;
height: 76rpx;
line-height: 76rpx;
text-align: center;
border-radius: 18rpx;
background: #f07e57;
color: #ffffff;
font-weight: 700;
}
.empty {
padding: 80rpx 0;
text-align: center;
color: #7e8f8c;
}
.comment-card {
margin-bottom: 18rpx;
padding: 24rpx;
border-radius: 20rpx;
background: #132529;
color: #dce7e4;
}
.comment-head {
display: flex;
justify-content: space-between;
gap: 16rpx;
}
.comment-user {
font-size: 28rpx;
font-weight: 700;
color: #ffffff;
}
.comment-time,
.comment-meta {
font-size: 22rpx;
color: #7e8f8c;
}
.comment-content {
margin-top: 16rpx;
font-size: 26rpx;
line-height: 1.8;
}
.reply-content {
margin-top: 12rpx;
padding: 16rpx;
border-radius: 16rpx;
background: #0c181b;
color: #a9bbb6;
font-size: 24rpx;
}
.comment-meta {
margin-top: 14rpx;
}
.delete-btn {
margin-top: 18rpx;
width: 120rpx;
height: 56rpx;
line-height: 56rpx;
text-align: center;
border-radius: 999rpx;
color: #ffffff;
background: #d95f5f;
}
@@ -23,6 +23,14 @@ const MANAGE_MODULES = [
permissionCodes: ['coupon:view'],
requiresShopContext: true
},
{
key: 'comments',
title: '评论管理',
description: '查看作品评论与回复,删除不合规内容',
path: '/pages/comments/index',
permissionCodes: ['comment:view'],
requiresShopContext: true
},
{
key: 'tags',
title: '标签管理',
@@ -32,6 +32,8 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/user/reset-password-by-phone",
"/product/get/**",
"/product/list/**",
"/comment/list/product/**",
"/api/comment/list/product/**",
"/shop/get/**",
"/shop/list/public",
"/shop/list/simple",
@@ -0,0 +1,49 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.service.CommentService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping("/admin/comment")
@RequiredArgsConstructor
public class AdminCommentController {
private final CommentService commentService;
private final AdminScopeHelper adminScopeHelper;
@GetMapping("/list")
@RequirePermission("comment:view")
public Result<List<CommentVO>> listComments(
HttpServletRequest request,
@RequestParam(required = false) Long productId,
@RequestParam(required = false) Long userId,
@RequestParam(required = false) Long shopId,
@RequestParam(required = false) String keyword
) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
return Result.success(commentService.listAdminComments(productId, userId, scopedShopId, keyword));
}
@DeleteMapping("/delete/{id}")
@RequirePermission("comment:delete")
public Result<Boolean> deleteComment(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long managedShopId = adminScopeHelper.resolveShopScope(currentUser, null);
return Result.success(commentService.adminDeleteComment(id, managedShopId));
}
}
@@ -7,6 +7,7 @@ import com.xiaowang.yuminailcore.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@@ -30,8 +31,9 @@ public class CommentController {
* @return 评论ID
*/
@PostMapping("/create")
public Result<Long> createComment(@RequestBody CommentDTO commentDTO) {
Long id = commentService.createComment(commentDTO);
public Result<Long> createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) {
Long userId = (Long) request.getAttribute("userId");
Long id = commentService.createComment(userId, commentDTO);
return Result.success(id);
}
@@ -43,8 +45,9 @@ public class CommentController {
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateComment(@PathVariable Long id, @RequestBody CommentDTO commentDTO) {
boolean success = commentService.updateComment(id, commentDTO);
public Result<Boolean> updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) {
Long userId = (Long) request.getAttribute("userId");
boolean success = commentService.updateComment(id, userId, commentDTO);
return Result.success(success);
}
@@ -55,8 +58,9 @@ public class CommentController {
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteComment(@PathVariable Long id) {
boolean success = commentService.deleteComment(id);
public Result<Boolean> deleteComment(HttpServletRequest request, @PathVariable Long id) {
Long userId = (Long) request.getAttribute("userId");
boolean success = commentService.deleteComment(id, userId);
return Result.success(success);
}
@@ -24,6 +24,8 @@ public interface CommentService extends IService<CommentDO> {
*/
Long createComment(CommentDTO commentDTO);
Long createComment(Long currentUserId, CommentDTO commentDTO);
/**
* 更新评论
*
@@ -33,6 +35,8 @@ public interface CommentService extends IService<CommentDO> {
*/
boolean updateComment(Long id, CommentDTO commentDTO);
boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO);
/**
* 删除评论
*
@@ -41,6 +45,12 @@ public interface CommentService extends IService<CommentDO> {
*/
boolean deleteComment(Long id);
boolean deleteComment(Long id, Long currentUserId);
boolean adminDeleteComment(Long id, Long managedShopId);
List<CommentVO> listAdminComments(Long productId, Long userId, Long shopId, String keyword);
/**
* 根据ID查询评论
*
@@ -4,13 +4,25 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.dto.CommentDTO;
import com.xiaowang.yuminailcore.entity.CommentDO;
import com.xiaowang.yuminailcore.entity.ProductDO;
import com.xiaowang.yuminailcore.entity.ShopDO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.CommentMapper;
import com.xiaowang.yuminailcore.mapper.ProductMapper;
import com.xiaowang.yuminailcore.mapper.ShopMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.service.CommentService;
import com.xiaowang.yuminailcore.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@@ -25,15 +37,58 @@ import java.util.stream.Collectors;
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> implements CommentService {
private final CommentMapper commentMapper;
private final UserMapper userMapper;
private final ShopMapper shopMapper;
private final ProductMapper productMapper;
@Override
public Long createComment(CommentDTO commentDTO) {
if (commentDTO == null || commentDTO.getUserId() == null) {
throw new RuntimeException("请先登录后再评论");
}
return createComment(commentDTO.getUserId(), commentDTO);
}
@Override
public Long createComment(Long currentUserId, CommentDTO commentDTO) {
if (currentUserId == null) {
throw new RuntimeException("请先登录后再评论");
}
if (commentDTO == null) {
throw new RuntimeException("评论内容不能为空");
}
String content = sanitizeContent(commentDTO.getCommentContent());
Long productId = normalizeId(commentDTO.getProductId());
Long parentCommentId = normalizeId(commentDTO.getParentCommentId());
if (productId == null && parentCommentId == null) {
throw new RuntimeException("请选择要评论的作品");
}
CommentDO parentComment = null;
if (parentCommentId != null) {
parentComment = commentMapper.selectById(parentCommentId);
if (parentComment == null || Integer.valueOf(1).equals(parentComment.getIsDelete())) {
throw new RuntimeException("回复的评论不存在");
}
if (productId == null) {
productId = parentComment.getProductId();
} else if (parentComment.getProductId() != null && !productId.equals(parentComment.getProductId())) {
throw new RuntimeException("回复内容与作品不匹配");
}
}
Long shopId = normalizeId(commentDTO.getShopId());
if (shopId == null && productId != null) {
ProductDO product = productMapper.selectById(productId);
if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) {
shopId = product.getShopId();
}
}
CommentDO commentDO = new CommentDO();
commentDO.setUserId(commentDTO.getUserId());
commentDO.setShopId(commentDTO.getShopId());
commentDO.setProductId(commentDTO.getProductId());
commentDO.setCommentContent(commentDTO.getCommentContent());
commentDO.setParentCommentId(commentDTO.getParentCommentId());
commentDO.setUserId(currentUserId);
commentDO.setShopId(shopId);
commentDO.setProductId(productId);
commentDO.setCommentContent(content);
commentDO.setParentCommentId(parentCommentId);
commentDO.setLikeCount(0);
commentDO.setIsDelete(0);
commentMapper.insert(commentDO);
return commentDO.getId();
@@ -45,11 +100,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
if (commentDO == null) {
return false;
}
commentDO.setUserId(commentDTO.getUserId());
commentDO.setShopId(commentDTO.getShopId());
commentDO.setProductId(commentDTO.getProductId());
commentDO.setCommentContent(commentDTO.getCommentContent());
commentDO.setParentCommentId(commentDTO.getParentCommentId());
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@@ -63,10 +115,52 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
return commentMapper.updateById(commentDO) > 0;
}
@Override
public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return false;
}
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
throw new RuntimeException("只能修改自己的评论");
}
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
public boolean deleteComment(Long id, Long currentUserId) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return false;
}
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
throw new RuntimeException("只能删除自己的评论");
}
commentDO.setIsDelete(1);
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
public boolean adminDeleteComment(Long id, Long managedShopId) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return false;
}
if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) {
throw new RuntimeException("无权删除其他门店评论");
}
commentDO.setIsDelete(1);
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
public CommentVO getCommentById(Long id) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null) {
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return null;
}
return convertToVO(commentDO);
@@ -74,10 +168,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
@Override
public List<CommentVO> listAllComments() {
List<CommentDO> commentDOs = commentMapper.selectList(null);
return commentDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
return toCommentVOList(activeQuery().orderByDesc(CommentDO::getCreateTime));
}
@Override
@@ -85,6 +176,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getUserId, userId)
.eq(CommentDO::getIsDelete, 0)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
@@ -96,6 +189,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getShopId, shopId)
.eq(CommentDO::getIsDelete, 0)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
@@ -107,10 +202,10 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getProductId, productId)
.eq(CommentDO::getIsDelete, 0)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
return buildTree(commentDOs);
}
@Override
@@ -118,12 +213,28 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getParentCommentId, parentCommentId)
.eq(CommentDO::getIsDelete, 0)
.orderByAsc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
public List<CommentVO> listAdminComments(Long productId, Long userId, Long shopId, String keyword) {
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getIsDelete, 0)
.eq(productId != null && productId > 0, CommentDO::getProductId, productId)
.eq(userId != null && userId > 0, CommentDO::getUserId, userId)
.eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId)
.like(StringUtils.hasText(keyword), CommentDO::getCommentContent, keyword)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream().map(this::convertToVO).collect(Collectors.toList());
}
/**
* 将 DO 转换为 VO
*
@@ -141,6 +252,80 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
commentVO.setLikeCount(commentDO.getLikeCount());
commentVO.setCreateTime(commentDO.getCreateTime());
commentVO.setUpdateTime(commentDO.getUpdateTime());
fillDisplayFields(commentVO, commentDO);
return commentVO;
}
private List<CommentVO> toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> wrapper) {
return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList());
}
private List<CommentVO> buildTree(List<CommentDO> commentDOs) {
Map<Long, CommentVO> rootMap = new HashMap<>();
List<CommentVO> roots = new ArrayList<>();
List<CommentVO> replies = new ArrayList<>();
for (CommentDO commentDO : commentDOs) {
CommentVO vo = convertToVO(commentDO);
if (commentDO.getParentCommentId() == null || commentDO.getParentCommentId() <= 0) {
vo.setReplies(new ArrayList<>());
rootMap.put(commentDO.getId(), vo);
roots.add(vo);
} else {
replies.add(vo);
}
}
replies.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())));
for (CommentVO reply : replies) {
CommentVO root = rootMap.get(reply.getParentCommentId());
if (root != null) {
root.getReplies().add(reply);
}
}
roots.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed());
return roots;
}
private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) {
UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId());
if (user != null) {
commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount());
}
ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId());
if (shop != null) {
commentVO.setShopName(shop.getShopName());
}
ProductDO product = commentDO.getProductId() == null ? null : productMapper.selectById(commentDO.getProductId());
if (product != null) {
commentVO.setProductTitle(product.getTitle());
}
if (commentDO.getParentCommentId() != null && commentDO.getParentCommentId() > 0) {
CommentDO parent = commentMapper.selectById(commentDO.getParentCommentId());
if (parent != null && !Integer.valueOf(1).equals(parent.getIsDelete())) {
commentVO.setParentCommentContent(parent.getCommentContent());
}
}
}
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> activeQuery() {
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0);
}
private Long normalizeId(Long id) {
return id == null || id <= 0 ? null : id;
}
private String sanitizeContent(String content) {
if (!StringUtils.hasText(content)) {
throw new RuntimeException("评论内容不能为空");
}
String sanitized = content.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim();
sanitized = sanitized.replaceAll("<[^>]*>", "");
if (!StringUtils.hasText(sanitized)) {
throw new RuntimeException("评论内容不能为空");
}
if (sanitized.length() > 300) {
throw new RuntimeException("评论最多输入 300 个字");
}
return sanitized;
}
}
@@ -291,7 +291,7 @@ public class OrderServiceImpl implements OrderService {
CouponSelection couponSelection = resolveRequestedCoupon(orderDTO, availableCouponOptions);
if (couponSelection == null && !isExplicitNoCoupon(orderDTO)) {
couponSelection = selectBestSystemVipCoupon(availableCouponOptions, totalAmount);
couponSelection = selectBestAvailableCoupon(availableCouponOptions, totalAmount);
}
if (couponSelection != null) {
@@ -961,11 +961,15 @@ public class OrderServiceImpl implements OrderService {
);
}
private CouponSelection selectBestSystemVipCoupon(List<UserCouponVO> availableCoupons, BigDecimal totalAmount) {
private CouponSelection selectBestAvailableCoupon(List<UserCouponVO> availableCoupons, BigDecimal totalAmount) {
return availableCoupons.stream()
.filter(coupon -> COUPON_SOURCE_SYSTEM_VIP.equals(coupon.getSourceType()))
.filter(coupon -> coupon.getCouponId() != null)
.max(Comparator.comparing(coupon -> calculateCouponDiscountAmount(coupon, totalAmount)))
.map(coupon -> new CouponSelection(coupon.getSourceType(), coupon.getCouponId(), null))
.map(coupon -> new CouponSelection(
coupon.getSourceType(),
coupon.getCouponId(),
COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null
))
.orElse(null);
}
@@ -127,6 +127,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
seeds.put("coupon:edit", new PermissionSeed("编辑优惠券", "优惠券管理", "编辑优惠券模板"));
seeds.put("coupon:delete", new PermissionSeed("删除优惠券", "优惠券管理", "删除优惠券模板"));
seeds.put("coupon:assign", new PermissionSeed("发放优惠券", "优惠券管理", "向用户发放普通优惠券"));
seeds.put("comment:view", new PermissionSeed("查看评论", "评论管理", "查看作品评论与回复"));
seeds.put("comment:delete", new PermissionSeed("删除评论", "评论管理", "删除不合规作品评论"));
seeds.put("order:view", new PermissionSeed("查看订单", "订单管理", "查看订单列表与详情"));
seeds.put("order:process", new PermissionSeed("处理订单", "订单管理", "处理订单状态或由美甲师完结订单"));
seeds.put("order:edit", new PermissionSeed("编辑订单", "订单管理", "编辑订单信息的预留权限"));
@@ -19,6 +19,7 @@ public final class PermissionPolicy {
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"comment:view", "comment:delete",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit"
);
@@ -33,6 +34,7 @@ public final class PermissionPolicy {
"permission:view", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"comment:view", "comment:delete",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit"
);
@@ -45,6 +47,7 @@ public final class PermissionPolicy {
"shop:view",
"tag:view", "tag:create",
"coupon:view",
"comment:view",
"order:view", "order:process"
);
@@ -1127,6 +1127,8 @@ VALUES
('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0),
('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0),
('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0),
('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0),
('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0),
('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0),
('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0),
('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0),
@@ -1220,6 +1222,8 @@ INNER JOIN t_permission p
'coupon:edit',
'coupon:delete',
'coupon:assign',
'comment:view',
'comment:delete',
'order:view',
'order:process',
'order:edit',
@@ -1272,6 +1276,8 @@ INNER JOIN t_permission p
'coupon:edit',
'coupon:delete',
'coupon:assign',
'comment:view',
'comment:delete',
'order:view',
'order:process',
'order:edit',
@@ -1304,6 +1310,7 @@ INNER JOIN t_permission p
'tag:view',
'tag:create',
'coupon:view',
'comment:view',
'order:view',
'order:process'
)
+23
View File
@@ -360,6 +360,29 @@ export const adminCouponApi = {
}
}
export interface AdminCommentVO {
id: IdType
userId: IdType
userNickname?: string
shopId?: IdType
shopName?: string
productId?: IdType
productTitle?: string
commentContent: string
parentCommentId?: IdType
parentCommentContent?: string
createTime?: string
}
export const adminCommentApi = {
listComments: (params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string }) => {
return adminApi.get<AdminCommentVO[]>('/comment/list', { params }) as unknown as Promise<AdminCommentVO[]>
},
deleteComment: (id: IdType) => {
return adminApi.delete<boolean>(`/comment/delete/${id}`) as unknown as Promise<boolean>
}
}
export interface Product {
id: IdType
shopId: IdType
+31
View File
@@ -0,0 +1,31 @@
import api from './index'
import type { IdType } from '@/utils/id'
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
createTime?: string
updateTime?: string
replies?: CommentVO[]
}
export const commentApi = {
listByProduct: (productId: IdType) => {
return api.get<CommentVO[]>(`/comment/list/product/${productId}`) as unknown as Promise<CommentVO[]>
},
create: (data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }) => {
return api.post<IdType>('/comment/create', data) as unknown as Promise<IdType>
},
delete: (id: IdType) => {
return api.delete<boolean>(`/comment/delete/${id}`) as unknown as Promise<boolean>
}
}
+2
View File
@@ -60,6 +60,7 @@ const isAuthFreePath = (url?: string) => {
'/user/reset-password-by-phone',
'/product/get/',
'/product/list/',
'/comment/list/product/',
'/shop/get/',
'/shop/list/public',
'/shop/list/simple',
@@ -150,6 +151,7 @@ api.interceptors.response.use(
url?.includes('/user/phone-login') ||
url?.includes('/product/get/') ||
url?.includes('/product/list/') ||
url?.includes('/comment/list/product/') ||
url?.includes('/shop/get/') ||
url?.includes('/shop/list/public') ||
url?.includes('/shop/list/simple') ||
+6
View File
@@ -135,6 +135,12 @@ const router = createRouter({
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',
+6 -7
View File
@@ -132,7 +132,7 @@
</a-radio>
</a-radio-group>
<div class="coupon-tip">
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
系统会按本次订单金额自动预选减免最高的一张券,也可以手动选择不使用优惠。
</div>
</a-modal>
@@ -313,9 +313,8 @@ const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
return 0
}
const findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
const findBestCoupon = (coupons: UserCoupon[]) => {
return coupons
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
}
@@ -455,10 +454,10 @@ const loadAvailableCoupons = async () => {
}
couponSelectionTouched.value = false
const defaultVipCoupon = findBestSystemVipCoupon(availableCoupons.value)
if (defaultVipCoupon) {
selectedCoupon.value = defaultVipCoupon
couponSelectionKey.value = getCouponKey(defaultVipCoupon)
const defaultCoupon = findBestCoupon(availableCoupons.value)
if (defaultCoupon) {
selectedCoupon.value = defaultCoupon
couponSelectionKey.value = getCouponKey(defaultCoupon)
} else {
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
+202 -537
View File
@@ -1,125 +1,116 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>{{ product.title || product.name || '作品详情' }}</h1>
<div class="detail-page">
<header class="detail-header">
<a-button type="text" @click="router.back()"><LeftOutlined /></a-button>
<h1>{{ productTitle }}</h1>
<a-button type="text" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" :class="['header-star', { active: isFavorite }]" />
<component :is="isFavorite ? StarFilled : StarOutlined" :class="{ active: isFavorite }" />
</a-button>
</header>
<main class="content">
<a-result
v-if="loadError"
status="warning"
title="暂时无法查看作品详情"
:sub-title="loadError"
>
<main class="detail-content">
<a-result v-if="loadError" status="warning" title="暂时无法查看作品详情" :sub-title="loadError">
<template #extra>
<a-button type="primary" @click="handleBackClick">返回上一页</a-button>
<a-button type="primary" @click="router.back()">返回上一页</a-button>
</template>
</a-result>
<template v-else>
<section class="hero-card">
<a-carousel v-if="productImages.length > 1" autoplay dots>
<div v-for="(image, index) in productImages" :key="index" class="carousel-slide">
<img :src="image" :alt="product.title || product.name" class="product-image" />
</div>
</a-carousel>
<div v-else class="single-image">
<img :src="productImages[0] || DEFAULT_PRODUCT_IMAGE" :alt="product.title || product.name" class="product-image" />
</div>
<section class="media-section">
<img :src="productImages[0] || DEFAULT_PRODUCT_IMAGE" :alt="productTitle" />
</section>
<section class="info-card">
<div class="info-header">
<section class="info-section">
<div class="title-row">
<div>
<h2 class="product-name">{{ product.title || product.name }}</h2>
<p class="product-price">¥{{ Number(product.price || 0).toFixed(2) }}</p>
<h2>{{ productTitle }}</h2>
<p class="price">¥{{ Number(product.price || 0).toFixed(2) }}</p>
</div>
<a-tag color="blue">{{ product.approximateDuration || '时长待确认' }}</a-tag>
<a-tag color="blue">{{ product.approximateDuration || '以门店确认为准' }}</a-tag>
</div>
<div class="metric-row">
<button class="metric-card" type="button" @click="openShopDetail" :disabled="!shopInfo?.id">
<div class="metrics">
<button type="button" @click="openShopDetail" :disabled="!shopInfo?.id">
<ShopOutlined />
<div>
<span class="metric-label">所属门店</span>
<strong>{{ shopInfo?.shopName || '暂未绑定门店' }}</strong>
</div>
<span>门店</span>
<strong>{{ shopInfo?.shopName || '暂未绑定门店' }}</strong>
</button>
<div class="metric-card">
<div>
<TeamOutlined />
<div>
<span class="metric-label">可约美甲师</span>
<strong>{{ artistCountText }}</strong>
</div>
<span>可约美甲师</span>
<strong>{{ artistCountText }}</strong>
</div>
<div class="metric-card">
<div>
<CalendarOutlined />
<div>
<span class="metric-label">最早可约</span>
<strong>{{ earliestBookableText }}</strong>
</div>
<span>可约时间</span>
<strong>{{ earliestBookableText }}</strong>
</div>
</div>
<div v-if="shopInfo" class="shop-summary" @click="openShopDetail">
<div class="shop-summary-title">{{ shopInfo.shopName }}</div>
<div class="shop-summary-text">{{ shopInfo.address || '门店地址待完善' }}</div>
<div class="shop-summary-text">{{ shopInfo.businessHours || '营业时间待完善' }}</div>
<div v-if="shopInfo" class="shop-panel" @click="openShopDetail">
<strong>{{ shopInfo.shopName }}</strong>
<span>{{ shopInfo.address || '门店地址待完善' }}</span>
<span>{{ shopInfo.businessHours || '营业时间待完善' }}</span>
</div>
<div class="stats-row">
<button type="button" class="stat-btn" @click="handleLikeClick">
<component :is="isLiked ? HeartFilled : HeartOutlined" :class="{ active: isLiked }" />
<span>{{ product.likeCount || 0 }} 点赞</span>
<div class="actions-row">
<button type="button" :class="{ active: isLiked }" @click="handleLikeClick">
<component :is="isLiked ? HeartFilled : HeartOutlined" />
{{ product.likeCount || 0 }} 点赞
</button>
<button type="button" class="stat-btn" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" :class="{ active: isFavorite }" />
<span>{{ product.collectCount || 0 }} 收藏</span>
<button type="button" :class="{ active: isFavorite }" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" />
{{ product.collectCount || 0 }} 收藏
</button>
<div class="stat-btn static">
<ClockCircleOutlined />
<span>{{ product.approximateDuration || '时长待定' }}</span>
</div>
</div>
<div class="tags">
<a-tag
v-for="tag in product.tagInfos || []"
:key="tag.id"
:style="{
color: tag.textColor || '#333',
backgroundColor: tag.bgColor || '#f0f0f0',
borderColor: tag.borderColor || '#f0f0f0'
}"
>
{{ tag.tagName }}
</a-tag>
<a-tag v-if="!product.tagInfos?.length" color="default">暂无标签</a-tag>
<a-tag v-for="tag in product.tagInfos || []" :key="tag.id">{{ tag.tagName }}</a-tag>
<a-tag v-if="!product.tagInfos?.length">暂无标签</a-tag>
</div>
<div class="description-block">
<h3>作品介绍</h3>
<p>{{ product.description || '店家还没补充作品说明。' }}</p>
<div class="description">
<h3>款式说明</h3>
<p>{{ product.description || '店家暂未补充作品说明。' }}</p>
</div>
</section>
<section class="comment-section">
<div class="section-head">
<h3>作品评论</h3>
<span>{{ comments.length }} 条</span>
</div>
<div class="comment-editor">
<a-textarea v-model:value="commentText" :maxlength="300" :rows="3" :placeholder="replyTarget ? `回复 ${replyTarget.userNickname || '用户'}` : '说说你的看法'" />
<div class="comment-tools">
<a-button v-if="replyTarget" type="text" @click="replyTarget = null">取消回复</a-button>
<a-button type="primary" :loading="submittingComment" @click="submitComment">发布</a-button>
</div>
</div>
<a-empty v-if="!comments.length" description="还没有评论,来写第一条吧" />
<div v-for="comment in comments" :key="comment.id" class="comment-item">
<div class="comment-main">
<strong>{{ comment.userNickname || '用户' }}</strong>
<span>{{ formatTime(comment.createTime) }}</span>
</div>
<p>{{ comment.commentContent }}</p>
<button type="button" @click="replyTarget = comment">回复</button>
<div v-if="comment.replies?.length" class="reply-list">
<div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
<strong>{{ reply.userNickname || '用户' }}</strong>
<span>{{ reply.commentContent }}</span>
</div>
</div>
</div>
</section>
</template>
</main>
<footer v-if="!loadError" class="action-buttons">
<a-button class="add-cart-btn" size="large" @click="handleAddToCart">
<ShoppingCartOutlined />
加入购物车
</a-button>
<a-button class="buy-now-btn" type="primary" size="large" @click="handleBuyNow">
<ThunderboltOutlined />
立即预约
</a-button>
<footer v-if="!loadError" class="detail-footer">
<a-button size="large" @click="handleAddToCart"><ShoppingCartOutlined />加入购物车</a-button>
<a-button type="primary" size="large" @click="handleBuyNow"><ThunderboltOutlined />立即预约</a-button>
</footer>
</div>
</template>
@@ -129,7 +120,6 @@ import { computed, inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
CalendarOutlined,
ClockCircleOutlined,
HeartFilled,
HeartOutlined,
LeftOutlined,
@@ -142,6 +132,7 @@ import {
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { cartApi } from '@/api/cart'
import { commentApi, type CommentVO } from '@/api/comment'
import { fileApi } from '@/api/file'
import { productApi, type ProductVO } from '@/api/product'
import { productLikeApi } from '@/api/productLike'
@@ -160,97 +151,25 @@ const product = ref<ProductVO>({} as ProductVO)
const shopInfo = ref<ShopVO | null>(null)
const productImages = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const comments = ref<CommentVO[]>([])
const commentText = ref('')
const replyTarget = ref<CommentVO | null>(null)
const submittingComment = ref(false)
const isFavorite = ref(false)
const isLiked = ref(false)
const loadError = ref('')
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
const productTitle = computed(() => product.value.title || product.value.name || '作品详情')
const artistCount = computed(() => {
if (typeof product.value.availableBookableArtistCount === 'number') {
return product.value.availableBookableArtistCount
}
const rawValue = product.value.bookableArtists || ''
return rawValue
.split(',')
.map(id => id.trim())
.filter(Boolean).length
if (typeof product.value.availableBookableArtistCount === 'number') return product.value.availableBookableArtistCount
return String(product.value.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean).length
})
const artistCountText = computed(() => {
if (artistCount.value > 0) {
return `${artistCount.value} 位`
}
return product.value.bookableArtistRestricted ? '暂无' : '门店安排'
})
const earliestBookableText = computed(() => estimateEarliestBookable(shopInfo.value?.businessHours))
const parseTimeRange = (businessHours?: string): { start: string; end: string } | null => {
if (!businessHours) {
return null
}
const normalized = businessHours.replace(/\s+/g, '')
const matched = normalized.match(/(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/)
if (!matched) {
return null
}
const [, start, end] = matched
if (!start || !end) {
return null
}
return { start, end }
}
const formatDateTime = (date: Date) => {
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 `${month}-${day} ${hour}:${minute}`
}
const estimateEarliestBookable = (businessHours?: string) => {
const timeRange = parseTimeRange(businessHours)
if (!timeRange) {
return businessHours || '以门店安排为准'
}
const startParts = timeRange.start.split(':').map(Number)
const endParts = timeRange.end.split(':').map(Number)
const startHour = startParts[0]
const startMinute = startParts[1]
const endHour = endParts[0]
const endMinute = endParts[1]
if ([startHour, startMinute, endHour, endMinute].some(value => value === undefined || Number.isNaN(value))) {
return businessHours || '以门店安排为准'
}
const safeStartHour = startHour ?? 0
const safeStartMinute = startMinute ?? 0
const safeEndHour = endHour ?? 0
const safeEndMinute = endMinute ?? 0
const candidate = new Date(Date.now() + 30 * 60 * 1000)
const openTime = new Date(candidate)
openTime.setHours(safeStartHour, safeStartMinute, 0, 0)
const closeTime = new Date(candidate)
closeTime.setHours(safeEndHour, safeEndMinute, 0, 0)
if (candidate <= openTime) {
return `今天 ${timeRange.start}`
}
if (candidate >= closeTime) {
const nextOpen = new Date(openTime)
nextOpen.setDate(nextOpen.getDate() + 1)
return `明天 ${timeRange.start}`
}
return formatDateTime(candidate)
}
const artistCountText = computed(() => artistCount.value > 0 ? `${artistCount.value} 位` : (product.value.bookableArtistRestricted ? '暂无可约' : '门店安排'))
const earliestBookableText = computed(() => shopInfo.value?.businessHours || '以门店安排为准')
const requireLogin = (actionText: string) => {
if (isLoggedIn.value) {
return true
}
if (isLoggedIn.value) return true
message.info(`${actionText}前请先登录`)
router.push('/')
return false
@@ -262,426 +181,172 @@ const loadProductImages = async () => {
productImages.value = [DEFAULT_PRODUCT_IMAGE]
return
}
const urls: string[] = []
for (const id of fileIds) {
try {
if (!imageIdCache.value[id]) {
imageIdCache.value[id] = await fileApi.getSignedUrl(id) as unknown as string
}
if (imageIdCache.value[id]) {
urls.push(imageIdCache.value[id])
}
} catch (error) {
console.error('获取作品图片失败:', error)
}
if (!imageIdCache.value[id]) imageIdCache.value[id] = await fileApi.getSignedUrl(id) as unknown as string
if (imageIdCache.value[id]) urls.push(imageIdCache.value[id])
} catch {}
}
productImages.value = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
const loadShopInfo = async (shopId?: IdType | null) => {
if (!shopId) {
shopInfo.value = null
return
}
try {
const response = await shopApi.getShopById(shopId)
shopInfo.value = response || null
} catch (error) {
console.error('获取门店信息失败:', error)
shopInfo.value = null
}
shopInfo.value = shopId ? await shopApi.getShopById(shopId).catch(() => null) : null
}
const checkWishlistStatus = async () => {
if (!isLoggedIn.value || !product.value.id) {
isFavorite.value = false
return
}
try {
const status = await wishlistApi.checkWishlist(product.value.id)
isFavorite.value = Boolean(status)
} catch (error) {
console.error('获取收藏状态失败:', error)
isFavorite.value = false
}
const loadComments = async () => {
if (!product.value.id) return
comments.value = await commentApi.listByProduct(product.value.id).catch(() => [])
}
const checkLikeStatus = async () => {
const checkInteractionStatus = async () => {
if (!isLoggedIn.value || !product.value.id) {
isFavorite.value = false
isLiked.value = false
return
}
try {
const status = await productLikeApi.checkLikeStatus(product.value.id)
isLiked.value = Boolean(status)
} catch (error) {
console.error('获取点赞状态失败:', error)
isLiked.value = false
}
}
const resolveLoadError = (error: any) => {
const status = error?.response?.status
if (status === 404) {
return '这件作品可能已下架或不存在。'
}
if (status === 401) {
return '作品详情暂时无法加载,请稍后重试。'
}
return error?.message || '网络有点忙,请稍后再试。'
const [favorite, liked] = await Promise.all([
wishlistApi.checkWishlist(product.value.id).catch(() => false),
productLikeApi.checkLikeStatus(product.value.id).catch(() => false)
])
isFavorite.value = Boolean(favorite)
isLiked.value = Boolean(liked)
}
const fetchProductDetail = async () => {
loadError.value = ''
try {
const productId = toOptionalIdString(route.params.id)
if (!productId) {
throw new Error('作品ID不存在')
}
if (!productId) throw new Error('作品不存在')
const response = await productApi.getProductById(productId)
if (!response?.id) {
throw new Error('未找到对应作品')
}
if (!response?.id) throw new Error('作品不存在或已下架')
product.value = response
await Promise.all([
loadProductImages(),
loadShopInfo(response.shopId),
checkWishlistStatus(),
checkLikeStatus()
])
} catch (error) {
console.error('获取作品详情失败:', error)
loadError.value = resolveLoadError(error)
await Promise.all([loadProductImages(), loadShopInfo(response.shopId), checkInteractionStatus(), loadComments()])
} catch (error: any) {
loadError.value = error?.message || '网络异常,请稍后再试'
}
}
const handleBackClick = () => {
router.back()
}
const openShopDetail = () => {
if (!shopInfo.value?.id) {
return
}
router.push(`/shop/${shopInfo.value.id}`)
if (shopInfo.value?.id) router.push(`/shop/${shopInfo.value.id}`)
}
const handleFavoriteClick = async () => {
if (!product.value.id || !requireLogin('收藏作品')) {
return
}
try {
await runWithGlobalLoading(async () => {
if (isFavorite.value) {
await wishlistApi.removeFromWishlist(product.value.id)
product.value.collectCount = Math.max(0, Number(product.value.collectCount || 0) - 1)
message.success('已取消收藏')
} else {
await wishlistApi.addToWishlist(product.value.id)
product.value.collectCount = Number(product.value.collectCount || 0) + 1
message.success('已加入收藏')
}
})
if (!product.value.id || !requireLogin('收藏作品')) return
await runWithGlobalLoading(async () => {
if (isFavorite.value) {
await wishlistApi.removeFromWishlist(product.value.id)
product.value.collectCount = Math.max(0, Number(product.value.collectCount || 0) - 1)
message.success('已取消收藏')
} else {
await wishlistApi.addToWishlist(product.value.id)
product.value.collectCount = Number(product.value.collectCount || 0) + 1
message.success('已加入收藏')
}
isFavorite.value = !isFavorite.value
} catch (error) {
console.error('收藏操作失败:', error)
message.error('收藏操作失败,请稍后重试')
}
}).catch((error: any) => message.error(error?.message || '收藏操作失败'))
}
const handleLikeClick = async () => {
if (!product.value.id || !requireLogin('点赞作品')) {
return
}
try {
await runWithGlobalLoading(async () => {
if (isLiked.value) {
await productLikeApi.unlikeProduct(product.value.id)
product.value.likeCount = Math.max(0, Number(product.value.likeCount || 0) - 1)
message.success('已取消点赞')
} else {
await productLikeApi.likeProduct(product.value.id)
product.value.likeCount = Number(product.value.likeCount || 0) + 1
message.success('已点赞')
}
})
if (!product.value.id || !requireLogin('点赞作品')) return
await runWithGlobalLoading(async () => {
if (isLiked.value) {
await productLikeApi.unlikeProduct(product.value.id)
product.value.likeCount = Math.max(0, Number(product.value.likeCount || 0) - 1)
message.success('已取消点赞')
} else {
await productLikeApi.likeProduct(product.value.id)
product.value.likeCount = Number(product.value.likeCount || 0) + 1
message.success('已点赞')
}
isLiked.value = !isLiked.value
} catch (error) {
console.error('点赞操作失败:', error)
message.error('点赞操作失败,请稍后重试')
}
}).catch((error: any) => message.error(error?.message || '点赞操作失败'))
}
const handleAddToCart = async () => {
if (!product.value.id || !requireLogin('加入购物车')) {
return
}
try {
await runWithGlobalLoading(() => cartApi.addToCart({ productId: product.value.id, quantity: 1 }))
await updateCartCount()
message.success(`已将 ${product.value.title || product.value.name || '作品'} 加入购物车`)
} catch (error) {
console.error('加入购物车失败:', error)
message.error('加入购物车失败,请稍后重试')
}
if (!product.value.id || !requireLogin('加入购物车')) return
await runWithGlobalLoading(() => cartApi.addToCart({ productId: product.value.id, quantity: 1 }))
await updateCartCount()
message.success('已加入购物车')
}
const handleBuyNow = async () => {
if (!product.value.id || !requireLogin('预约下单')) {
return
}
if (!product.value.id || !requireLogin('预约下单')) return
await handleAddToCart()
router.push('/cart')
}
const submitComment = async () => {
if (!product.value.id || !requireLogin('发表评论')) return
const content = commentText.value.trim()
if (!content) return message.warning('请输入评论内容')
submittingComment.value = true
try {
await runWithGlobalLoading(() => cartApi.addToCart({ productId: product.value.id, quantity: 1 }))
await updateCartCount()
router.push('/cart')
} catch (error) {
console.error('立即预约失败:', error)
message.error('操作失败,请稍后重试')
await commentApi.create({
productId: product.value.id,
shopId: product.value.shopId,
parentCommentId: replyTarget.value?.id,
commentContent: content
})
commentText.value = ''
replyTarget.value = null
await loadComments()
message.success('评论已发布')
} catch (error: any) {
message.error(error?.message || '评论发布失败')
} finally {
submittingComment.value = false
}
}
const formatTime = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : ''
onMounted(() => {
void fetchProductDetail()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: sticky;
top: 0;
z-index: 100;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 16px;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(10px);
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
flex: 1;
margin: 0;
font-size: 18px;
font-weight: 700;
text-align: center;
}
.header-star {
font-size: 20px;
color: #8b8b9a;
}
.header-star.active {
color: #f7b500;
}
.content {
padding: 16px 16px 108px;
}
.hero-card,
.info-card {
max-width: 1040px;
margin: 0 auto 16px;
border-radius: 20px;
overflow: hidden;
background: white;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
}
.carousel-slide,
.single-image {
aspect-ratio: 16 / 11;
overflow: hidden;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.info-card {
padding: 24px;
}
.info-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
}
.product-name {
margin: 0 0 8px;
font-size: 26px;
font-weight: 700;
color: #1f1f1f;
}
.product-price {
margin: 0;
font-size: 28px;
font-weight: 700;
color: #ff4d4f;
}
.metric-row {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin-top: 20px;
}
.metric-card {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 14px;
border: 1px solid #edf0f5;
border-radius: 16px;
background: #fafcff;
text-align: left;
}
.metric-card:disabled {
cursor: default;
}
.metric-card :deep(svg) {
font-size: 18px;
color: #1677ff;
}
.metric-label {
display: block;
font-size: 12px;
color: #8b8b9a;
}
.metric-card strong {
font-size: 14px;
color: #1f1f1f;
}
.shop-summary {
margin-top: 18px;
padding: 16px 18px;
border-radius: 18px;
background: linear-gradient(135deg, #f8fbff 0%, #eef4ff 100%);
cursor: pointer;
}
.shop-summary-title {
font-size: 16px;
font-weight: 700;
color: #1f1f1f;
}
.shop-summary-text {
margin-top: 6px;
color: #666;
line-height: 1.6;
}
.stats-row {
display: flex;
gap: 12px;
margin-top: 20px;
}
.stat-btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
border: 1px solid #edf0f5;
border-radius: 999px;
background: white;
color: #666;
}
.stat-btn :deep(svg) {
font-size: 16px;
}
.stat-btn :deep(.active),
.stat-btn :deep(svg.active) {
color: #ff4d4f;
}
.stat-btn .active {
color: #ff4d4f;
}
.stat-btn.static {
cursor: default;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 20px;
}
.description-block {
margin-top: 24px;
}
.description-block h3 {
margin: 0 0 12px;
font-size: 18px;
font-weight: 700;
}
.description-block p {
margin: 0;
color: #666;
line-height: 1.8;
}
.action-buttons {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 120;
display: flex;
gap: 12px;
padding: 16px;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(10px);
border-top: 1px solid #f0f0f0;
}
.action-buttons :deep(.ant-btn) {
flex: 1;
height: 48px;
border-radius: 999px;
font-size: 15px;
font-weight: 700;
}
@media (max-width: 767px) {
.metric-row {
grid-template-columns: 1fr;
}
.stats-row {
flex-wrap: wrap;
}
}
.detail-page { min-height: 100vh; background: #f6f7f9; }
.detail-header { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; background: rgba(255,255,255,.96); border-bottom: 1px solid #eceff3; backdrop-filter: blur(10px); }
.detail-header h1 { flex: 1; margin: 0; font-size: 17px; text-align: center; color: #20232a; }
.detail-header .active { color: #e65d7a; }
.detail-content { max-width: 1040px; margin: 0 auto; padding: 18px 16px 118px; }
.media-section { overflow: hidden; border-radius: 8px; background: #fff; }
.media-section img { display: block; width: 100%; aspect-ratio: 16 / 10; object-fit: cover; }
.info-section, .comment-section { margin-top: 14px; padding: 22px; border-radius: 8px; background: #fff; border: 1px solid #edf0f4; }
.title-row { display: flex; justify-content: space-between; gap: 16px; }
.title-row h2 { margin: 0 0 8px; font-size: 24px; color: #20232a; }
.price { margin: 0; font-size: 26px; font-weight: 700; color: #d94f69; }
.metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; margin-top: 18px; }
.metrics > div, .metrics > button { display: grid; gap: 4px; padding: 14px; border: 1px solid #edf0f4; border-radius: 8px; background: #fbfcfe; text-align: left; }
.metrics svg { color: #3b82f6; }
.metrics span { font-size: 12px; color: #7b8494; }
.metrics strong { color: #20232a; }
.shop-panel { display: grid; gap: 6px; margin-top: 18px; padding: 16px; border-radius: 8px; background: #f7f9fc; cursor: pointer; color: #5f6876; }
.shop-panel strong { color: #20232a; }
.actions-row { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
.actions-row button { display: inline-flex; align-items: center; gap: 8px; padding: 9px 14px; border: 1px solid #edf0f4; border-radius: 999px; background: #fff; color: #5f6876; }
.actions-row button.active { color: #d94f69; border-color: #ffd7e0; background: #fff5f7; }
.tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 18px; }
.description { margin-top: 22px; }
.description h3, .section-head h3 { margin: 0; font-size: 18px; color: #20232a; }
.description p { margin: 10px 0 0; color: #5f6876; line-height: 1.8; }
.section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.section-head span { color: #7b8494; }
.comment-editor { padding: 14px; border: 1px solid #edf0f4; border-radius: 8px; background: #fbfcfe; }
.comment-tools { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }
.comment-item { padding: 16px 0; border-bottom: 1px solid #edf0f4; }
.comment-item:last-child { border-bottom: 0; }
.comment-main { display: flex; justify-content: space-between; gap: 12px; color: #7b8494; }
.comment-main strong { color: #20232a; }
.comment-item p { margin: 8px 0; color: #3b4350; line-height: 1.7; }
.comment-item button { padding: 0; border: 0; background: transparent; color: #3b82f6; cursor: pointer; }
.reply-list { margin-top: 10px; padding: 10px 12px; border-radius: 8px; background: #f7f9fc; }
.reply-item { display: flex; gap: 8px; padding: 6px 0; color: #5f6876; }
.reply-item strong { color: #20232a; }
.detail-footer { position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; display: flex; gap: 12px; padding: 14px 16px calc(14px + env(safe-area-inset-bottom)); background: rgba(255,255,255,.96); border-top: 1px solid #eceff3; backdrop-filter: blur(10px); }
.detail-footer :deep(.ant-btn) { flex: 1; height: 46px; border-radius: 999px; font-weight: 700; }
@media (max-width: 720px) { .metrics { grid-template-columns: 1fr; } .title-row { flex-direction: column; } }
</style>
@@ -209,6 +209,7 @@ import {
HomeOutlined,
IdcardOutlined,
LogoutOutlined,
MessageOutlined,
MenuFoldOutlined,
MenuOutlined,
MenuUnfoldOutlined,
@@ -258,6 +259,7 @@ const menuItems: AdminMenuItem[] = [
{ key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' },
{ key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' },
{ key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' },
{ key: '/admin/comments', icon: MessageOutlined, label: '评论管理', permissionCode: 'comment:view' },
{ key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' },
{ key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' },
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' },
@@ -313,6 +315,7 @@ const activeMobileTab = computed(() => {
route.path.startsWith('/admin/users') ||
route.path.startsWith('/admin/products') ||
route.path.startsWith('/admin/coupons') ||
route.path.startsWith('/admin/comments') ||
route.path.startsWith('/admin/shops') ||
route.path.startsWith('/admin/permissions') ||
route.path.startsWith('/admin/tags') ||
@@ -0,0 +1,116 @@
<template>
<div class="comments-page">
<header class="page-head">
<div>
<h2>评论管理</h2>
<p>查看作品评论与回复,删除不合规内容。</p>
</div>
<a-input-search v-model:value="keyword" class="search" allow-clear placeholder="搜索评论内容" @search="loadComments" />
</header>
<a-table
:columns="columns"
:data-source="comments"
:loading="loading"
:pagination="{ pageSize: 10 }"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'commentContent'">
<div class="comment-cell">
<strong>{{ record.commentContent }}</strong>
<span v-if="record.parentCommentContent">回复:{{ record.parentCommentContent }}</span>
</div>
</template>
<template v-else-if="column.key === 'action'">
<a-popconfirm title="确认删除这条评论?" ok-text="删除" cancel-text="取消" @confirm="deleteComment(record.id)">
<a-button danger type="link">删除</a-button>
</a-popconfirm>
</template>
</template>
</a-table>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { adminCommentApi, type AdminCommentVO } from '@/api/admin'
import type { IdType } from '@/utils/id'
const loading = ref(false)
const keyword = ref('')
const comments = ref<AdminCommentVO[]>([])
const columns = [
{ title: '评论内容', dataIndex: 'commentContent', key: 'commentContent' },
{ title: '用户', dataIndex: 'userNickname', key: 'userNickname', width: 140 },
{ title: '作品', dataIndex: 'productTitle', key: 'productTitle', width: 180 },
{ title: '门店', dataIndex: 'shopName', key: 'shopName', width: 160 },
{ title: '时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
{ title: '操作', key: 'action', width: 100 }
]
const loadComments = async () => {
loading.value = true
try {
comments.value = await adminCommentApi.listComments({ keyword: keyword.value || undefined })
} catch (error: any) {
message.error(error?.message || '评论加载失败')
} finally {
loading.value = false
}
}
const deleteComment = async (id: IdType) => {
await adminCommentApi.deleteComment(id)
message.success('评论已删除')
await loadComments()
}
onMounted(loadComments)
</script>
<style scoped>
.comments-page {
display: grid;
gap: 18px;
}
.page-head {
display: flex;
justify-content: space-between;
gap: 16px;
align-items: flex-start;
}
.page-head h2 {
margin: 0;
font-size: 22px;
color: #20232a;
}
.page-head p {
margin: 6px 0 0;
color: #687385;
}
.search {
width: min(360px, 100%);
}
.comment-cell {
display: grid;
gap: 6px;
}
.comment-cell strong {
color: #20232a;
font-weight: 600;
}
.comment-cell span {
color: #7b8494;
font-size: 12px;
}
</style>
Binary file not shown.
Binary file not shown.