diff --git a/WeChatProgram/api/comment.js b/WeChatProgram/api/comment.js new file mode 100644 index 00000000..8c7430c3 --- /dev/null +++ b/WeChatProgram/api/comment.js @@ -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' + }) + } +} diff --git a/WeChatProgram/pages/cart/index.js b/WeChatProgram/pages/cart/index.js index 5cef611a..30aaa61d 100644 --- a/WeChatProgram/pages/cart/index.js +++ b/WeChatProgram/pages/cart/index.js @@ -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 } } diff --git a/WeChatProgram/pages/product-detail/index.js b/WeChatProgram/pages/product-detail/index.js index a646a996..2aab32ec 100644 --- a/WeChatProgram/pages/product-detail/index.js +++ b/WeChatProgram/pages/product-detail/index.js @@ -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' }) + } + } }) diff --git a/WeChatProgram/pages/product-detail/index.wxml b/WeChatProgram/pages/product-detail/index.wxml index 0cbfb816..f82c399f 100644 --- a/WeChatProgram/pages/product-detail/index.wxml +++ b/WeChatProgram/pages/product-detail/index.wxml @@ -78,6 +78,35 @@ {{product.descriptionText}} + + + + 作品评论 + {{comments.length}} 条 + + + + + 取消回复 + 发布 + + + 还没有评论,来写第一条吧 + + + {{item.userNickname || '用户'}} + {{item.createTime}} + + {{item.commentContent}} + 回复 + + + {{reply.userNickname || '用户'}}: + {{reply.commentContent}} + + + + diff --git a/WeChatProgram/pages/product-detail/index.wxss b/WeChatProgram/pages/product-detail/index.wxss index d1e30780..ee844901 100644 --- a/WeChatProgram/pages/product-detail/index.wxss +++ b/WeChatProgram/pages/product-detail/index.wxss @@ -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; diff --git a/WeChatProgram/utils/request.js b/WeChatProgram/utils/request.js index 7f56c183..6fc9b4ce 100644 --- a/WeChatProgram/utils/request.js +++ b/WeChatProgram/utils/request.js @@ -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', diff --git a/YumiNail-Admin-Program/api/comment.js b/YumiNail-Admin-Program/api/comment.js new file mode 100644 index 00000000..f157fddc --- /dev/null +++ b/YumiNail-Admin-Program/api/comment.js @@ -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' + }) + } +} diff --git a/YumiNail-Admin-Program/app.json b/YumiNail-Admin-Program/app.json index fc4baf51..42c54c85 100644 --- a/YumiNail-Admin-Program/app.json +++ b/YumiNail-Admin-Program/app.json @@ -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" } diff --git a/YumiNail-Admin-Program/pages/comments/index.js b/YumiNail-Admin-Program/pages/comments/index.js new file mode 100644 index 00000000..b1633482 --- /dev/null +++ b/YumiNail-Admin-Program/pages/comments/index.js @@ -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' }) + } + } + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/comments/index.wxml b/YumiNail-Admin-Program/pages/comments/index.wxml new file mode 100644 index 00000000..2b8190e6 --- /dev/null +++ b/YumiNail-Admin-Program/pages/comments/index.wxml @@ -0,0 +1,21 @@ + + + + + + 搜索 + + + 暂无评论 + + + + {{item.userNickname || '用户'}} + {{item.createTime}} + + {{item.commentContent}} + 回复:{{item.parentCommentContent}} + {{item.productTitle || '作品'}} · {{item.shopName || '门店'}} + 删除 + + diff --git a/YumiNail-Admin-Program/pages/comments/index.wxss b/YumiNail-Admin-Program/pages/comments/index.wxss new file mode 100644 index 00000000..eb6afa29 --- /dev/null +++ b/YumiNail-Admin-Program/pages/comments/index.wxss @@ -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; +} diff --git a/YumiNail-Admin-Program/utils/permission.js b/YumiNail-Admin-Program/utils/permission.js index 92ae932b..fa12e7a7 100644 --- a/YumiNail-Admin-Program/utils/permission.js +++ b/YumiNail-Admin-Program/utils/permission.js @@ -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: '标签管理', diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java index 094a274b..85b8cbbc 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java @@ -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", diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java new file mode 100644 index 00000000..de372499 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java @@ -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> 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 deleteComment(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long managedShopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(commentService.adminDeleteComment(id, managedShopId)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java index 459f248e..78a82839 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java @@ -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 createComment(@RequestBody CommentDTO commentDTO) { - Long id = commentService.createComment(commentDTO); + public Result 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 updateComment(@PathVariable Long id, @RequestBody CommentDTO commentDTO) { - boolean success = commentService.updateComment(id, commentDTO); + public Result 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 deleteComment(@PathVariable Long id) { - boolean success = commentService.deleteComment(id); + public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = commentService.deleteComment(id, userId); return Result.success(success); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java index 85f8da8d..82fe9b28 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java @@ -24,6 +24,8 @@ public interface CommentService extends IService { */ Long createComment(CommentDTO commentDTO); + Long createComment(Long currentUserId, CommentDTO commentDTO); + /** * 更新评论 * @@ -33,6 +35,8 @@ public interface CommentService extends IService { */ boolean updateComment(Long id, CommentDTO commentDTO); + boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO); + /** * 删除评论 * @@ -41,6 +45,12 @@ public interface CommentService extends IService { */ boolean deleteComment(Long id); + boolean deleteComment(Long id, Long currentUserId); + + boolean adminDeleteComment(Long id, Long managedShopId); + + List listAdminComments(Long productId, Long userId, Long shopId, String keyword); + /** * 根据ID查询评论 * diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java index 562a54ea..b40acb08 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java @@ -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 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 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 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 im @Override public List listAllComments() { - List 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 im List 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 im List 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 im List 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 im List 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 listAdminComments(Long productId, Long userId, Long shopId, String keyword) { + List 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 im commentVO.setLikeCount(commentDO.getLikeCount()); commentVO.setCreateTime(commentDO.getCreateTime()); commentVO.setUpdateTime(commentDO.getUpdateTime()); + fillDisplayFields(commentVO, commentDO); return commentVO; } + + private List toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper) { + return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList()); + } + + private List buildTree(List commentDOs) { + Map rootMap = new HashMap<>(); + List roots = new ArrayList<>(); + List 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 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; + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java index 15c2448e..97e68399 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java @@ -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 availableCoupons, BigDecimal totalAmount) { + private CouponSelection selectBestAvailableCoupon(List 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); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java index 61635ed9..3f47a6cb 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java @@ -127,6 +127,8 @@ public class UserServiceImpl extends ServiceImpl 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("编辑订单", "订单管理", "编辑订单信息的预留权限")); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java index 8c1fcf37..21de839c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java @@ -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" ); diff --git a/YumiNail-Core/src/main/resources/files/YumiNail.sql b/YumiNail-Core/src/main/resources/files/YumiNail.sql index e0ae2f48..e63a2772 100644 --- a/YumiNail-Core/src/main/resources/files/YumiNail.sql +++ b/YumiNail-Core/src/main/resources/files/YumiNail.sql @@ -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' ) diff --git a/YumiNail-Frontend/src/api/admin.ts b/YumiNail-Frontend/src/api/admin.ts index b27bbcac..c3f8a5f3 100644 --- a/YumiNail-Frontend/src/api/admin.ts +++ b/YumiNail-Frontend/src/api/admin.ts @@ -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('/comment/list', { params }) as unknown as Promise + }, + deleteComment: (id: IdType) => { + return adminApi.delete(`/comment/delete/${id}`) as unknown as Promise + } +} + export interface Product { id: IdType shopId: IdType diff --git a/YumiNail-Frontend/src/api/comment.ts b/YumiNail-Frontend/src/api/comment.ts new file mode 100644 index 00000000..3a7d526b --- /dev/null +++ b/YumiNail-Frontend/src/api/comment.ts @@ -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(`/comment/list/product/${productId}`) as unknown as Promise + }, + create: (data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }) => { + return api.post('/comment/create', data) as unknown as Promise + }, + delete: (id: IdType) => { + return api.delete(`/comment/delete/${id}`) as unknown as Promise + } +} diff --git a/YumiNail-Frontend/src/api/index.ts b/YumiNail-Frontend/src/api/index.ts index d1c241f2..8b37ab2a 100644 --- a/YumiNail-Frontend/src/api/index.ts +++ b/YumiNail-Frontend/src/api/index.ts @@ -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') || diff --git a/YumiNail-Frontend/src/router/index.ts b/YumiNail-Frontend/src/router/index.ts index 87e5b047..da49594f 100644 --- a/YumiNail-Frontend/src/router/index.ts +++ b/YumiNail-Frontend/src/router/index.ts @@ -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', diff --git a/YumiNail-Frontend/src/views/CartView.vue b/YumiNail-Frontend/src/views/CartView.vue index e5d46f83..edd6cc49 100644 --- a/YumiNail-Frontend/src/views/CartView.vue +++ b/YumiNail-Frontend/src/views/CartView.vue @@ -132,7 +132,7 @@
- 系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。 + 系统会按本次订单金额自动预选减免最高的一张券,也可以手动选择不使用优惠。
@@ -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 diff --git a/YumiNail-Frontend/src/views/ProductDetailView.vue b/YumiNail-Frontend/src/views/ProductDetailView.vue index d0143794..5478953c 100644 --- a/YumiNail-Frontend/src/views/ProductDetailView.vue +++ b/YumiNail-Frontend/src/views/ProductDetailView.vue @@ -1,125 +1,116 @@ @@ -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({} as ProductVO) const shopInfo = ref(null) const productImages = ref([]) const imageIdCache = ref>({}) +const comments = ref([]) +const commentText = ref('') +const replyTarget = ref(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() }) diff --git a/YumiNail-Frontend/src/views/admin/AdminLayout.vue b/YumiNail-Frontend/src/views/admin/AdminLayout.vue index 47b53d6a..6b21b642 100644 --- a/YumiNail-Frontend/src/views/admin/AdminLayout.vue +++ b/YumiNail-Frontend/src/views/admin/AdminLayout.vue @@ -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') || diff --git a/YumiNail-Frontend/src/views/admin/CommentsView.vue b/YumiNail-Frontend/src/views/admin/CommentsView.vue new file mode 100644 index 00000000..73f8e888 --- /dev/null +++ b/YumiNail-Frontend/src/views/admin/CommentsView.vue @@ -0,0 +1,116 @@ + + + + + diff --git a/docx/YumiNail-测试报告.docx b/docx/YumiNail-测试报告.docx new file mode 100644 index 00000000..89e5256e Binary files /dev/null and b/docx/YumiNail-测试报告.docx differ diff --git a/docx/YumiNail-测试案例.docx b/docx/YumiNail-测试案例.docx new file mode 100644 index 00000000..f0883d64 Binary files /dev/null and b/docx/YumiNail-测试案例.docx differ