功能:完善订单流程和加固
This commit is contained in:
@@ -3,8 +3,10 @@ package com.xiaowang.yuminailcore;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@EnableDiscoveryClient
|
||||
@EnableScheduling
|
||||
@SpringBootApplication
|
||||
public class YumiNailCoreApplication {
|
||||
|
||||
|
||||
+35
-8
@@ -9,6 +9,8 @@ import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.PermissionService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -36,6 +38,7 @@ public class AdminPermissionController {
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("permission:create")
|
||||
@@ -50,8 +53,14 @@ public class AdminPermissionController {
|
||||
public Result<Long> createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||
Long id = permissionService.createPermission(permissionDTO);
|
||||
return Result.success(id);
|
||||
try {
|
||||
Long id = permissionService.createPermission(permissionDTO);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_CREATE, "permissionId=" + id);
|
||||
return Result.success(id);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_CREATE, "reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@@ -68,8 +77,14 @@ public class AdminPermissionController {
|
||||
public Result<Boolean> updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||
boolean success = permissionService.updatePermission(id, permissionDTO);
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = permissionService.updatePermission(id, permissionDTO);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_UPDATE, "permissionId=" + id + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_UPDATE, "permissionId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@@ -85,8 +100,14 @@ public class AdminPermissionController {
|
||||
public Result<Boolean> deletePermission(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||
boolean success = permissionService.deletePermission(id);
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = permissionService.deletePermission(id);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_DELETE, "permissionId=" + id + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_DELETE, "permissionId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
@@ -199,7 +220,13 @@ public class AdminPermissionController {
|
||||
}
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
userPermissionDTO.setUserId(userId);
|
||||
boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId);
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_ASSIGN, "targetUserId=" + userId + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_ASSIGN, "targetUserId=" + userId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/security-audit")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminSecurityAuditController {
|
||||
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
private final SecurityAuditLogService securityAuditLogService;
|
||||
|
||||
@GetMapping("/logs")
|
||||
@RequirePermission("security:audit:view")
|
||||
public Result<PageResultVO<SecurityAuditLogVO>> listLogs(
|
||||
@RequestParam(required = false) String account,
|
||||
@RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) String result,
|
||||
@RequestParam(required = false) String startTime,
|
||||
@RequestParam(required = false) String endTime,
|
||||
@RequestParam(defaultValue = "1") Integer page,
|
||||
@RequestParam(defaultValue = "20") Integer size) {
|
||||
return Result.success(securityAuditLogService.pageLogs(
|
||||
account,
|
||||
action,
|
||||
result,
|
||||
parseDateTime(startTime),
|
||||
parseDateTime(endTime),
|
||||
page,
|
||||
size
|
||||
));
|
||||
}
|
||||
|
||||
private LocalDateTime parseDateTime(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return LocalDateTime.parse(value.trim(), DATE_TIME_FORMATTER);
|
||||
} catch (DateTimeParseException exception) {
|
||||
return LocalDateTime.parse(value.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-4
@@ -7,6 +7,8 @@ import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||
import lombok.Data;
|
||||
@@ -32,6 +34,7 @@ public class AdminShopController {
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@GetMapping("/list")
|
||||
@RequirePermission("shop:view")
|
||||
@@ -103,8 +106,14 @@ public class AdminShopController {
|
||||
public Result<Boolean> deleteShop(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺");
|
||||
boolean success = shopService.deleteShop(id);
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = shopService.deleteShop(id);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SHOP_DELETE_BLOCKED, "shopId=" + id + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.SHOP_DELETE_BLOCKED, "shopId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PutMapping("/status/{id}")
|
||||
@@ -121,8 +130,14 @@ public class AdminShopController {
|
||||
public Result<Boolean> updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺");
|
||||
boolean success = shopService.updateShopStatus(id, statusRequest.getStatus());
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = shopService.updateShopStatus(id, statusRequest.getStatus());
|
||||
securityAuditSupport.success(request, SecurityAuditActions.SHOP_STATUS_UPDATE, "shopId=" + id + ",status=" + statusRequest.getStatus());
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.SHOP_STATUS_UPDATE, "shopId=" + id + ",status=" + statusRequest.getStatus() + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/list/all")
|
||||
|
||||
+59
-14
@@ -13,6 +13,8 @@ import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.service.ShopRoleService;
|
||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||
import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserStatisticsVO;
|
||||
@@ -56,6 +58,7 @@ public class AdminUserController {
|
||||
* Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final BookableArtistSupport bookableArtistSupport;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@GetMapping("/list")
|
||||
@RequirePermission("user:view")
|
||||
@@ -214,8 +217,14 @@ public class AdminUserController {
|
||||
*/
|
||||
throw new RuntimeException("管理员账号不允许停用");
|
||||
}
|
||||
boolean success = userService.updateUserStatus(id, request.getStatus());
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = userService.updateUserStatus(id, request.getStatus());
|
||||
securityAuditSupport.success(httpRequest, SecurityAuditActions.USER_STATUS_UPDATE, "targetUserId=" + id + ",status=" + request.getStatus());
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(httpRequest, SecurityAuditActions.USER_STATUS_UPDATE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/reset-password/{userId}")
|
||||
@@ -236,8 +245,14 @@ public class AdminUserController {
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码");
|
||||
Long currentUserId = (Long) request.getAttribute("userId");
|
||||
boolean success = userService.resetPassword(userId, currentUserId);
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = userService.resetPassword(userId, currentUserId);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.USER_RESET_PASSWORD, "targetUserId=" + userId + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.USER_RESET_PASSWORD, "targetUserId=" + userId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@@ -265,8 +280,14 @@ public class AdminUserController {
|
||||
*/
|
||||
throw new RuntimeException("管理员账号不允许删除");
|
||||
}
|
||||
boolean success = userService.deleteUser(id);
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = userService.deleteUser(id);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.USER_DELETE, "targetUserId=" + id + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.USER_DELETE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PutMapping("/unbind/{id}")
|
||||
@@ -295,8 +316,14 @@ public class AdminUserController {
|
||||
*/
|
||||
throw new RuntimeException("管理员账号不允许解绑");
|
||||
}
|
||||
boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType());
|
||||
return Result.success(success);
|
||||
try {
|
||||
boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType());
|
||||
securityAuditSupport.success(request, SecurityAuditActions.USER_UNBIND, "targetUserId=" + id + ",result=" + success);
|
||||
return Result.success(success);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.USER_UNBIND, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/asset")
|
||||
@@ -341,8 +368,14 @@ public class AdminUserController {
|
||||
) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额");
|
||||
UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO);
|
||||
return Result.success(assetVO);
|
||||
try {
|
||||
UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id);
|
||||
return Result.success(assetVO);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/vip/override")
|
||||
@@ -355,8 +388,14 @@ public class AdminUserController {
|
||||
) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP");
|
||||
UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO);
|
||||
return Result.success(assetVO);
|
||||
try {
|
||||
UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id);
|
||||
return Result.success(assetVO);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/vip/recalculate")
|
||||
@@ -372,8 +411,14 @@ public class AdminUserController {
|
||||
public Result<UserAssetVO> recalculateUserVip(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP");
|
||||
UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId());
|
||||
return Result.success(assetVO);
|
||||
try {
|
||||
UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId());
|
||||
securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id);
|
||||
return Result.success(assetVO);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/info")
|
||||
|
||||
+22
@@ -1,6 +1,9 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.mapper.EffectDiagramMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
@@ -31,6 +34,9 @@ public class FrontendFileController {
|
||||
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final ProductMapper productMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final EffectDiagramMapper effectDiagramMapper;
|
||||
|
||||
/**
|
||||
* 获取带签名的图片链接。
|
||||
@@ -47,6 +53,9 @@ public class FrontendFileController {
|
||||
if (fileVO == null) {
|
||||
return Result.error("文件不存在");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) {
|
||||
return Result.error("文件不可公开访问");
|
||||
}
|
||||
|
||||
String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl());
|
||||
if (objectName == null || objectName.isEmpty()) {
|
||||
@@ -60,4 +69,17 @@ public class FrontendFileController {
|
||||
return Result.error("获取签名链接失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPublicFileReference(Long fileId) {
|
||||
if (fileId == null) {
|
||||
return false;
|
||||
}
|
||||
return positive(productMapper.countPublicImageReference(fileId))
|
||||
|| positive(shopMapper.countPublicImageReference(fileId))
|
||||
|| positive(effectDiagramMapper.countPublicImageReference(fileId));
|
||||
}
|
||||
|
||||
private boolean positive(Long count) {
|
||||
return count != null && count > 0;
|
||||
}
|
||||
}
|
||||
|
||||
+116
-6
@@ -4,8 +4,16 @@ import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||
import com.xiaowang.yuminailcore.service.OrderService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
@@ -30,6 +38,9 @@ public class OrderController {
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
@Resource
|
||||
private SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@PostMapping("/create")
|
||||
@OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击")
|
||||
/**
|
||||
@@ -145,8 +156,14 @@ public class OrderController {
|
||||
*/
|
||||
throw new RuntimeException("美甲师只能完成属于自己的订单");
|
||||
}
|
||||
orderService.completeArtistOrder(orderId, userId);
|
||||
return Result.success();
|
||||
try {
|
||||
orderService.completeArtistOrder(orderId, userId);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId);
|
||||
return Result.success();
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
if (!Integer.valueOf(4).equals(userType)) {
|
||||
UserVO currentUser = userService.getUserById(userId);
|
||||
@@ -171,8 +188,14 @@ public class OrderController {
|
||||
throw new RuntimeException("无权处理其他店铺订单");
|
||||
}
|
||||
}
|
||||
orderService.processOrder(orderId, status);
|
||||
return Result.success();
|
||||
try {
|
||||
orderService.processOrder(orderId, status);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status);
|
||||
return Result.success();
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
// 美甲师查看自己的订单
|
||||
@@ -244,7 +267,94 @@ public class OrderController {
|
||||
*/
|
||||
throw new RuntimeException("仅美甲师可完成自己的订单");
|
||||
}
|
||||
orderService.completeArtistOrder(orderId, userId);
|
||||
return Result.success();
|
||||
try {
|
||||
orderService.completeArtistOrder(orderId, userId);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId);
|
||||
return Result.success();
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/review/my-pending")
|
||||
public Result<List<OrderArtistReviewVO>> listMyPendingReviews(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(orderService.listMyPendingReviews(userId));
|
||||
}
|
||||
|
||||
@GetMapping("/{orderId}/reviews")
|
||||
public Result<List<OrderArtistReviewVO>> listOrderReviews(@PathVariable Long orderId, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
return Result.success(orderService.listOrderReviews(orderId, userId, userType));
|
||||
}
|
||||
|
||||
@PostMapping("/review/{reviewId}/submit")
|
||||
@OperationGuard(action = "order-artist-review-submit", ttlSeconds = 15, message = "评价正在提交中,请勿重复操作")
|
||||
public Result<OrderArtistReviewVO> submitArtistReview(@PathVariable Long reviewId,
|
||||
@RequestBody OrderArtistReviewSubmitDTO dto,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(orderService.submitArtistReview(reviewId, userId, dto));
|
||||
}
|
||||
|
||||
@RequirePermission("order:artist-change")
|
||||
@GetMapping("/{orderId}/artist-change/options")
|
||||
public Result<OrderArtistChangeOptionsVO> getArtistChangeOptions(@PathVariable Long orderId,
|
||||
@RequestParam Long orderItemId,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
return Result.success(orderService.getArtistChangeOptions(orderId, orderItemId, userId, userType));
|
||||
}
|
||||
|
||||
@RequirePermission("order:artist-change")
|
||||
@PostMapping("/artist-change/request")
|
||||
@OperationGuard(action = "order-artist-change-request", ttlSeconds = 15, message = "改派申请正在提交中,请勿重复操作")
|
||||
public Result<OrderArtistChangeRequestVO> requestArtistChange(@RequestBody OrderArtistChangeRequestDTO dto,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(orderService.requestArtistChange(userId, dto));
|
||||
}
|
||||
|
||||
@GetMapping("/artist-change/my-pending")
|
||||
public Result<List<OrderArtistChangeRequestVO>> listMyPendingArtistChangeRequests(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
return Result.success(orderService.listMyPendingArtistChangeRequests(userId, userType));
|
||||
}
|
||||
|
||||
@PutMapping("/artist-change/{requestId}/approve")
|
||||
@OperationGuard(action = "order-artist-change-approve", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作")
|
||||
public Result<OrderArtistChangeRequestVO> approveArtistChange(@PathVariable Long requestId,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
try {
|
||||
OrderArtistChangeRequestVO result = orderService.approveArtistChange(requestId, userId, userType);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId);
|
||||
return Result.success(result);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PutMapping("/artist-change/{requestId}/reject")
|
||||
@OperationGuard(action = "order-artist-change-reject", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作")
|
||||
public Result<OrderArtistChangeRequestVO> rejectArtistChange(@PathVariable Long requestId,
|
||||
@RequestBody(required = false) OrderArtistChangeRejectDTO dto,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Integer userType = (Integer) request.getAttribute("userType");
|
||||
try {
|
||||
OrderArtistChangeRequestVO result = orderService.rejectArtistChange(requestId, userId, userType, dto);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId);
|
||||
return Result.success(result);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class OrderArtistChangeRejectDTO {
|
||||
private String rejectReason;
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class OrderArtistChangeRequestDTO {
|
||||
private Long orderId;
|
||||
private Long orderItemId;
|
||||
private Long requestedArtistId;
|
||||
private String reason;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class OrderArtistReviewSubmitDTO {
|
||||
private BigDecimal rating;
|
||||
private String content;
|
||||
private List<Long> imageFileIds;
|
||||
}
|
||||
@@ -48,4 +48,10 @@ public class SystemMessageCreateDTO {
|
||||
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Integer popupEnabled = 1;
|
||||
|
||||
private String businessType;
|
||||
|
||||
private Long businessId;
|
||||
|
||||
private String actionPath;
|
||||
}
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.xiaowang.yuminailcore.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_business_event_outbox")
|
||||
public class BusinessEventOutboxDO extends BaseEntity {
|
||||
|
||||
@TableField("event_key")
|
||||
private String eventKey;
|
||||
|
||||
@TableField("event_type")
|
||||
private String eventType;
|
||||
|
||||
@TableField("business_type")
|
||||
private String businessType;
|
||||
|
||||
@TableField("business_id")
|
||||
private Long businessId;
|
||||
|
||||
@TableField("payload_json")
|
||||
private String payloadJson;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("retry_count")
|
||||
private Integer retryCount;
|
||||
|
||||
@TableField("next_retry_time")
|
||||
private LocalDateTime nextRetryTime;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
@TableField("claimed_at")
|
||||
private LocalDateTime claimedAt;
|
||||
|
||||
@TableField("processed_at")
|
||||
private LocalDateTime processedAt;
|
||||
|
||||
@TableField("is_delete")
|
||||
private Integer isDelete;
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.xiaowang.yuminailcore.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_order_artist_change_request")
|
||||
public class OrderArtistChangeRequestDO extends BaseEntity {
|
||||
|
||||
@TableField("order_id")
|
||||
private Long orderId;
|
||||
|
||||
@TableField("order_item_id")
|
||||
private Long orderItemId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("customer_id")
|
||||
private Long customerId;
|
||||
|
||||
@TableField("from_artist_id")
|
||||
private Long fromArtistId;
|
||||
|
||||
@TableField("to_artist_id")
|
||||
private Long toArtistId;
|
||||
|
||||
@TableField("requester_id")
|
||||
private Long requesterId;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("reason")
|
||||
private String reason;
|
||||
|
||||
@TableField("reject_reason")
|
||||
private String rejectReason;
|
||||
|
||||
@TableField("message_id")
|
||||
private Long messageId;
|
||||
|
||||
@TableField("pending_key")
|
||||
private String pendingKey;
|
||||
|
||||
@TableField("approved_time")
|
||||
private LocalDateTime approvedTime;
|
||||
|
||||
@TableField("rejected_time")
|
||||
private LocalDateTime rejectedTime;
|
||||
|
||||
@TableField("expire_time")
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
@TableField("is_delete")
|
||||
private Integer isDelete;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.xiaowang.yuminailcore.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_order_artist_review")
|
||||
public class OrderArtistReviewDO extends BaseEntity {
|
||||
|
||||
@TableField("order_id")
|
||||
private Long orderId;
|
||||
|
||||
@TableField("order_item_id")
|
||||
private Long orderItemId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("artist_id")
|
||||
private Long artistId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("customer_id")
|
||||
private Long customerId;
|
||||
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
@TableField("rating_score")
|
||||
private BigDecimal ratingScore;
|
||||
|
||||
@TableField("content")
|
||||
private String content;
|
||||
|
||||
@TableField("image_file_ids")
|
||||
private String imageFileIds;
|
||||
|
||||
@TableField("reminder_message_id")
|
||||
private Long reminderMessageId;
|
||||
|
||||
@TableField("submitted_at")
|
||||
private LocalDateTime submittedAt;
|
||||
|
||||
@TableField("is_delete")
|
||||
private Integer isDelete;
|
||||
}
|
||||
@@ -65,6 +65,18 @@ public class SystemMessageDO extends BaseEntity {
|
||||
*/
|
||||
private String targetIds;
|
||||
|
||||
@TableField("business_type")
|
||||
private String businessType;
|
||||
|
||||
@TableField("business_id")
|
||||
private Long businessId;
|
||||
|
||||
@TableField("action_path")
|
||||
private String actionPath;
|
||||
|
||||
@TableField("idempotency_key")
|
||||
private String idempotencyKey;
|
||||
|
||||
@TableField("popup_enabled")
|
||||
/**
|
||||
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.xiaowang.yuminailcore.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface BusinessEventOutboxMapper extends BaseMapper<BusinessEventOutboxDO> {
|
||||
|
||||
@Select("SELECT * FROM t_business_event_outbox WHERE status IN ('PENDING', 'FAILED') AND is_delete = 0 AND (next_retry_time IS NULL OR next_retry_time <= #{now}) ORDER BY create_time ASC, id ASC LIMIT #{limit}")
|
||||
List<BusinessEventOutboxDO> selectDueEvents(@Param("now") LocalDateTime now, @Param("limit") int limit);
|
||||
|
||||
@Update("UPDATE t_business_event_outbox SET status = 'PROCESSING', claimed_at = #{now} WHERE id = #{id} AND status IN ('PENDING', 'FAILED') AND is_delete = 0")
|
||||
int claimDueEvent(@Param("id") Long id, @Param("now") LocalDateTime now);
|
||||
|
||||
@Update("UPDATE t_business_event_outbox SET status = 'SUCCEEDED', processed_at = #{now}, last_error = NULL WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0")
|
||||
int markSucceeded(@Param("id") Long id, @Param("now") LocalDateTime now);
|
||||
|
||||
@Update("UPDATE t_business_event_outbox SET status = 'FAILED', retry_count = COALESCE(retry_count, 0) + 1, next_retry_time = #{nextRetryTime}, last_error = #{lastError} WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0")
|
||||
int markFailed(@Param("id") Long id, @Param("nextRetryTime") LocalDateTime nextRetryTime, @Param("lastError") String lastError);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.EffectDiagramDO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
/**
|
||||
* 商品效果图信息表 Mapper
|
||||
@@ -11,4 +13,7 @@ import com.xiaowang.yuminailcore.entity.EffectDiagramDO;
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
public interface EffectDiagramMapper extends BaseMapper<EffectDiagramDO> {
|
||||
|
||||
@Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.xiaowang.yuminailcore.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.OrderArtistChangeRequestDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface OrderArtistChangeRequestMapper extends BaseMapper<OrderArtistChangeRequestDO> {
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_change_request WHERE order_item_id = #{orderItemId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) LIMIT 1")
|
||||
OrderArtistChangeRequestDO selectPendingByOrderItemId(@Param("orderItemId") Long orderItemId);
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_change_request WHERE customer_id = #{userId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
|
||||
List<OrderArtistChangeRequestDO> selectPendingByUserId(@Param("userId") Long userId);
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_change_request WHERE (from_artist_id = #{artistId} OR to_artist_id = #{artistId} OR requester_id = #{artistId}) AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
|
||||
List<OrderArtistChangeRequestDO> selectPendingByArtistId(@Param("artistId") Long artistId);
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_change_request WHERE shop_id = #{shopId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
|
||||
List<OrderArtistChangeRequestDO> selectPendingByShopId(@Param("shopId") Long shopId);
|
||||
|
||||
@Update("UPDATE t_order_artist_change_request SET status = 'APPROVED', approved_time = #{approvedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{approvedTime})")
|
||||
int approvePending(@Param("id") Long id, @Param("approvedTime") LocalDateTime approvedTime);
|
||||
|
||||
@Update("UPDATE t_order_artist_change_request SET status = 'REJECTED', reject_reason = #{rejectReason}, rejected_time = #{rejectedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{rejectedTime})")
|
||||
int rejectPending(@Param("id") Long id, @Param("rejectReason") String rejectReason, @Param("rejectedTime") LocalDateTime rejectedTime);
|
||||
|
||||
@Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}")
|
||||
int expirePendingById(@Param("id") Long id, @Param("now") LocalDateTime now);
|
||||
|
||||
@Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}")
|
||||
int expirePendingBefore(@Param("now") LocalDateTime now);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.xiaowang.yuminailcore.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface OrderArtistReviewMapper extends BaseMapper<OrderArtistReviewDO> {
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_review WHERE customer_id = #{userId} AND status = 0 AND is_delete = 0 ORDER BY create_time DESC, id DESC")
|
||||
List<OrderArtistReviewDO> selectPendingByUserId(@Param("userId") Long userId);
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_review WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC")
|
||||
List<OrderArtistReviewDO> selectByOrderId(@Param("orderId") Long orderId);
|
||||
|
||||
@Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1")
|
||||
OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId);
|
||||
|
||||
@Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0")
|
||||
BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId);
|
||||
}
|
||||
@@ -18,6 +18,9 @@ public interface OrderItemMapper extends BaseMapper<OrderItemDO> {
|
||||
@Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}")
|
||||
List<OrderItemDO> selectByOrderId(@Param("orderId") Long orderId);
|
||||
|
||||
@Select("SELECT * FROM t_order_item WHERE id = #{id} FOR UPDATE")
|
||||
OrderItemDO selectByIdForUpdate(@Param("id") Long id);
|
||||
|
||||
@Select("SELECT oi.* FROM t_order_item oi " +
|
||||
"INNER JOIN t_order o ON o.id = oi.order_id " +
|
||||
"WHERE oi.artist_id = #{artistId} " +
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -25,4 +26,9 @@ public interface OrderMapper extends BaseMapper<OrderDO> {
|
||||
"WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " +
|
||||
"ORDER BY o.create_time DESC")
|
||||
List<OrderDO> selectByArtistId(@Param("artistId") Long artistId);
|
||||
}
|
||||
|
||||
@Update("UPDATE t_order SET status = #{toStatus} WHERE id = #{orderId} AND status = #{fromStatus} AND is_delete = 0")
|
||||
int updateStatusIfCurrent(@Param("orderId") Long orderId,
|
||||
@Param("fromStatus") Integer fromStatus,
|
||||
@Param("toStatus") Integer toStatus);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.mapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
/**
|
||||
@@ -49,4 +50,7 @@ public interface ProductMapper extends BaseMapper<ProductDO> {
|
||||
*/
|
||||
@Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}")
|
||||
int decrementLikeCount(@Param("productId") Long productId);
|
||||
|
||||
@Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
/**
|
||||
* 店铺信息表 Mapper
|
||||
@@ -11,4 +13,7 @@ import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
public interface ShopMapper extends BaseMapper<ShopDO> {
|
||||
|
||||
@Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.xiaowang.yuminailcore.service;
|
||||
|
||||
public interface BusinessEventOutboxService {
|
||||
|
||||
void enqueueOrderCompleted(Long orderId);
|
||||
|
||||
void processDueEvents();
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
package com.xiaowang.yuminailcore.service;
|
||||
|
||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||
import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
@@ -93,4 +99,20 @@ public interface OrderService {
|
||||
* @return List<ArtistCalendarAppointmentVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
List<ArtistCalendarAppointmentVO> getArtistCalendarDay(Long userId, Integer userType, LocalDate date);
|
||||
|
||||
List<OrderArtistReviewVO> listMyPendingReviews(Long userId);
|
||||
|
||||
List<OrderArtistReviewVO> listOrderReviews(Long orderId, Long userId, Integer userType);
|
||||
|
||||
OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto);
|
||||
|
||||
OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType);
|
||||
|
||||
OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto);
|
||||
|
||||
List<OrderArtistChangeRequestVO> listMyPendingArtistChangeRequests(Long userId, Integer userType);
|
||||
|
||||
OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType);
|
||||
|
||||
OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto);
|
||||
}
|
||||
|
||||
+12
@@ -1,8 +1,20 @@
|
||||
package com.xiaowang.yuminailcore.service;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||
|
||||
public interface SecurityAuditLogService {
|
||||
|
||||
void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request);
|
||||
|
||||
PageResultVO<SecurityAuditLogVO> pageLogs(String account,
|
||||
String action,
|
||||
String result,
|
||||
LocalDateTime startTime,
|
||||
LocalDateTime endTime,
|
||||
Integer page,
|
||||
Integer size);
|
||||
}
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||
import com.xiaowang.yuminailcore.mapper.BusinessEventOutboxMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BusinessEventOutboxProcessor {
|
||||
|
||||
private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED";
|
||||
private static final int PROCESS_BATCH_SIZE = 20;
|
||||
|
||||
private final BusinessEventOutboxMapper outboxMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderServiceImpl orderService;
|
||||
|
||||
@Scheduled(fixedDelay = 10000L)
|
||||
@Transactional
|
||||
public void processDueEvents() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
List<BusinessEventOutboxDO> events = outboxMapper.selectDueEvents(now, PROCESS_BATCH_SIZE);
|
||||
for (BusinessEventOutboxDO event : events) {
|
||||
processOne(event);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void processOne(BusinessEventOutboxDO event) {
|
||||
if (event == null || event.getId() == null) {
|
||||
return;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
if (outboxMapper.claimDueEvent(event.getId(), now) == 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (EVENT_ORDER_COMPLETED.equals(event.getEventType())) {
|
||||
OrderDO order = orderMapper.selectById(event.getBusinessId());
|
||||
orderService.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
}
|
||||
outboxMapper.markSucceeded(event.getId(), LocalDateTime.now());
|
||||
} catch (Exception exception) {
|
||||
int retryCount = event.getRetryCount() == null ? 0 : event.getRetryCount();
|
||||
LocalDateTime nextRetryTime = LocalDateTime.now().plusSeconds(Math.min(300L, (long) Math.pow(2, retryCount) * 10L));
|
||||
outboxMapper.markFailed(event.getId(), nextRetryTime,
|
||||
BusinessEventOutboxServiceImpl.limit(exception.getMessage(), 500));
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||
import com.xiaowang.yuminailcore.mapper.BusinessEventOutboxMapper;
|
||||
import com.xiaowang.yuminailcore.service.BusinessEventOutboxService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BusinessEventOutboxServiceImpl implements BusinessEventOutboxService {
|
||||
|
||||
private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED";
|
||||
private static final String BUSINESS_ORDER = "ORDER";
|
||||
private static final String STATUS_PENDING = "PENDING";
|
||||
|
||||
private final BusinessEventOutboxMapper outboxMapper;
|
||||
|
||||
@Override
|
||||
public void enqueueOrderCompleted(Long orderId) {
|
||||
if (orderId == null) {
|
||||
return;
|
||||
}
|
||||
BusinessEventOutboxDO event = new BusinessEventOutboxDO();
|
||||
event.setEventKey("ORDER:" + orderId + ":COMPLETED");
|
||||
event.setEventType(EVENT_ORDER_COMPLETED);
|
||||
event.setBusinessType(BUSINESS_ORDER);
|
||||
event.setBusinessId(orderId);
|
||||
event.setPayloadJson("{\"orderId\":" + orderId + "}");
|
||||
event.setStatus(STATUS_PENDING);
|
||||
event.setRetryCount(0);
|
||||
event.setNextRetryTime(LocalDateTime.now());
|
||||
event.setIsDelete(0);
|
||||
try {
|
||||
outboxMapper.insert(event);
|
||||
} catch (DuplicateKeyException ignored) {
|
||||
// The order-completed event is idempotent by event_key.
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processDueEvents() {
|
||||
// Processing is owned by BusinessEventOutboxProcessor. This method remains on
|
||||
// the public service contract for callers that only need enqueue capability.
|
||||
}
|
||||
|
||||
static String limit(String value, int max) {
|
||||
if (!StringUtils.hasText(value) || value.length() <= max) {
|
||||
return value;
|
||||
}
|
||||
return value.substring(0, max);
|
||||
}
|
||||
}
|
||||
+775
-4
@@ -3,39 +3,55 @@ package com.xiaowang.yuminailcore.service.impl;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderItemDTO;
|
||||
import com.xiaowang.yuminailcore.entity.CartDO;
|
||||
import com.xiaowang.yuminailcore.entity.CouponDO;
|
||||
import com.xiaowang.yuminailcore.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderArtistChangeRequestDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderItemDO;
|
||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
import com.xiaowang.yuminailcore.entity.SystemMessageDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserCouponDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.mapper.CartMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.CouponMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderArtistChangeRequestMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderItemMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.SystemMessageMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.BusinessEventOutboxService;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.OrderService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.OrderStateMachine;
|
||||
import com.xiaowang.yuminailcore.support.OrderStatus;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderItemVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
import com.xiaowang.yuminailcore.vo.UserCouponVO;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
@@ -44,6 +60,7 @@ import org.springframework.util.StringUtils;
|
||||
import javax.annotation.Resource;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -59,6 +76,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -68,6 +86,7 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
/**
|
||||
@@ -81,6 +100,16 @@ public class OrderServiceImpl implements OrderService {
|
||||
private static final String COUPON_SOURCE_NONE = "NONE";
|
||||
private static final String COUPON_SOURCE_USER = "USER_COUPON";
|
||||
private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP";
|
||||
private static final int REVIEW_STATUS_PENDING = 0;
|
||||
private static final int REVIEW_STATUS_SUBMITTED = 1;
|
||||
private static final String CHANGE_STATUS_PENDING = "PENDING";
|
||||
private static final String CHANGE_STATUS_APPROVED = "APPROVED";
|
||||
private static final String CHANGE_STATUS_REJECTED = "REJECTED";
|
||||
private static final String CHANGE_STATUS_EXPIRED = "EXPIRED";
|
||||
private static final String ARTIST_CHANGE_PENDING_KEY_PREFIX = "ORDER_ITEM:";
|
||||
private static final String MESSAGE_TARGET_SELECTED_USERS = "SELECTED_USERS";
|
||||
private static final String REVIEW_BUSINESS_TYPE = "ORDER_ARTIST_REVIEW";
|
||||
private static final String CHANGE_BUSINESS_TYPE = "ORDER_ARTIST_CHANGE";
|
||||
private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:";
|
||||
private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:";
|
||||
private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15);
|
||||
@@ -123,6 +152,12 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private OrderItemMapper orderItemMapper;
|
||||
|
||||
@Resource
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
|
||||
@Resource
|
||||
private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
|
||||
|
||||
@Resource
|
||||
private CartMapper cartMapper;
|
||||
|
||||
@@ -144,6 +179,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private ShopMapper shopMapper;
|
||||
|
||||
@Resource
|
||||
private SystemMessageMapper systemMessageMapper;
|
||||
|
||||
@Resource
|
||||
private CouponService couponService;
|
||||
|
||||
@@ -156,6 +194,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private BookableArtistSupport bookableArtistSupport;
|
||||
|
||||
@Resource
|
||||
private BusinessEventOutboxService businessEventOutboxService;
|
||||
|
||||
@Resource
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@@ -629,6 +670,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
*/
|
||||
throw new RuntimeException("无效的订单状态");
|
||||
}
|
||||
OrderStatus targetStatus = OrderStatus.requireKnown(status);
|
||||
if (order.getStatus() != 1) {
|
||||
/**
|
||||
* Run business method `RuntimeException`.
|
||||
@@ -638,9 +680,15 @@ public class OrderServiceImpl implements OrderService {
|
||||
throw new RuntimeException("订单状态不允许处理");
|
||||
}
|
||||
|
||||
OrderStateMachine.requireAllowedTransition(order.getStatus(), status);
|
||||
if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), status) == 0) {
|
||||
throw new RuntimeException("订单状态已变化,请刷新后重试");
|
||||
}
|
||||
order.setStatus(status);
|
||||
orderMapper.updateById(order);
|
||||
if (status == 3) {
|
||||
if (targetStatus == OrderStatus.COMPLETED) {
|
||||
businessEventOutboxService.enqueueOrderCompleted(order.getId());
|
||||
}
|
||||
if (targetStatus == OrderStatus.CANCELLED) {
|
||||
restoreUserCoupon(order, order.getUserId());
|
||||
}
|
||||
}
|
||||
@@ -694,8 +742,12 @@ public class OrderServiceImpl implements OrderService {
|
||||
throw new RuntimeException("只能完成全部由自己承接的订单");
|
||||
}
|
||||
|
||||
order.setStatus(2);
|
||||
orderMapper.updateById(order);
|
||||
OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.COMPLETED.getCode());
|
||||
if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.COMPLETED.getCode()) == 0) {
|
||||
throw new RuntimeException("订单状态已变化,请刷新后重试");
|
||||
}
|
||||
order.setStatus(OrderStatus.COMPLETED.getCode());
|
||||
businessEventOutboxService.enqueueOrderCompleted(order.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -818,6 +870,710 @@ public class OrderServiceImpl implements OrderService {
|
||||
return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OrderArtistReviewVO> listMyPendingReviews(Long userId) {
|
||||
return orderArtistReviewMapper.selectPendingByUserId(userId).stream()
|
||||
.map(this::buildArtistReviewVO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OrderArtistReviewVO> listOrderReviews(Long orderId, Long userId, Integer userType) {
|
||||
OrderDO order = requireActiveOrder(orderId);
|
||||
if (!canAccessOrder(order, userId, userType)) {
|
||||
throw new RuntimeException("无权查看该订单评价");
|
||||
}
|
||||
return orderArtistReviewMapper.selectByOrderId(orderId).stream()
|
||||
.map(this::buildArtistReviewVO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto) {
|
||||
OrderArtistReviewDO review = orderArtistReviewMapper.selectById(reviewId);
|
||||
if (review == null || Integer.valueOf(1).equals(review.getIsDelete())) {
|
||||
throw new RuntimeException("评价任务不存在");
|
||||
}
|
||||
if (!Objects.equals(userId, review.getCustomerId())) {
|
||||
throw new RuntimeException("只能提交自己的评价");
|
||||
}
|
||||
if (!Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) {
|
||||
throw new RuntimeException("评价已提交,不能重复提交");
|
||||
}
|
||||
|
||||
BigDecimal rating = normalizeReviewRating(dto == null ? null : dto.getRating());
|
||||
review.setRatingScore(rating);
|
||||
review.setContent(trimToNull(dto == null ? null : dto.getContent()));
|
||||
review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds()));
|
||||
review.setStatus(REVIEW_STATUS_SUBMITTED);
|
||||
review.setSubmittedAt(LocalDateTime.now());
|
||||
orderArtistReviewMapper.updateById(review);
|
||||
refreshArtistRating(review.getArtistId());
|
||||
return buildArtistReviewVO(review);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType) {
|
||||
OrderDO order = requireActiveOrder(orderId);
|
||||
if (!canAccessOrder(order, userId, userType)) {
|
||||
throw new RuntimeException("无权查看该订单改派选项");
|
||||
}
|
||||
OrderItemDO item = requireOrderItem(orderItemId, orderId);
|
||||
ProductDO product = requireActiveProduct(item.getProductId());
|
||||
|
||||
OrderArtistChangeOptionsVO vo = new OrderArtistChangeOptionsVO();
|
||||
vo.setOrderId(orderId);
|
||||
vo.setOrderItemId(orderItemId);
|
||||
vo.setCurrentArtistId(item.getArtistId());
|
||||
UserDO currentArtist = item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId());
|
||||
vo.setCurrentArtistName(currentArtist == null ? null : currentArtist.getNickname());
|
||||
vo.setArtists(parseIdSet(product.getBookableArtists()).stream()
|
||||
.filter(artistId -> !Objects.equals(artistId, item.getArtistId()))
|
||||
.filter(artistId -> isArtistAvailableForItem(order.getShopId(), artistId, item, product))
|
||||
.map(this::buildArtistOptionVO)
|
||||
.filter(Objects::nonNull)
|
||||
.toList());
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto) {
|
||||
if (dto == null || dto.getOrderId() == null || dto.getOrderItemId() == null || dto.getRequestedArtistId() == null) {
|
||||
throw new RuntimeException("改派申请信息不完整");
|
||||
}
|
||||
ensureArtistChangeRequester(userId);
|
||||
OrderDO order = requireActiveOrder(dto.getOrderId());
|
||||
if (!canAccessOrder(order, userId, null)) {
|
||||
throw new RuntimeException("只能为自己的订单申请改派");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(order.getStatus())) {
|
||||
throw new RuntimeException("仅待服务订单允许申请改派");
|
||||
}
|
||||
OrderItemDO item = requireOrderItemForUpdate(dto.getOrderItemId(), order.getId());
|
||||
if (!canRequestArtistChangeForItem(order, item, userId)) {
|
||||
throw new RuntimeException("只能为自己承接的待服务订单项申请改派");
|
||||
}
|
||||
if (item.getArtistId() == null) {
|
||||
throw new RuntimeException("订单项未分配美甲师");
|
||||
}
|
||||
if (Objects.equals(item.getArtistId(), dto.getRequestedArtistId())) {
|
||||
throw new RuntimeException("新美甲师不能与原美甲师相同");
|
||||
}
|
||||
if (orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()) != null) {
|
||||
throw new RuntimeException("该订单项已有待处理改派申请");
|
||||
}
|
||||
ProductDO product = requireActiveProduct(item.getProductId());
|
||||
validateRequestedArtistForItem(order.getShopId(), dto.getRequestedArtistId(), item, product);
|
||||
|
||||
OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO();
|
||||
request.setOrderId(order.getId());
|
||||
request.setOrderItemId(item.getId());
|
||||
request.setProductId(item.getProductId());
|
||||
request.setShopId(order.getShopId());
|
||||
request.setCustomerId(order.getUserId());
|
||||
request.setFromArtistId(item.getArtistId());
|
||||
request.setToArtistId(dto.getRequestedArtistId());
|
||||
request.setRequesterId(userId);
|
||||
request.setStatus(CHANGE_STATUS_PENDING);
|
||||
request.setReason(trimToNull(dto.getReason()));
|
||||
request.setPendingKey(buildArtistChangePendingKey(item.getId()));
|
||||
request.setExpireTime(LocalDateTime.now().plusDays(2));
|
||||
request.setIsDelete(0);
|
||||
try {
|
||||
orderArtistChangeRequestMapper.insert(request);
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw new RuntimeException("该订单项已有待处理改派申请");
|
||||
}
|
||||
createArtistChangeMessage(order, request);
|
||||
return buildArtistChangeRequestVO(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OrderArtistChangeRequestVO> listMyPendingArtistChangeRequests(Long userId, Integer userType) {
|
||||
expireDueArtistChangeRequests();
|
||||
List<OrderArtistChangeRequestDO> requests;
|
||||
if (Integer.valueOf(2).equals(userType)) {
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
requests = user != null && user.getShopId() != null
|
||||
? orderArtistChangeRequestMapper.selectPendingByShopId(user.getShopId())
|
||||
: orderArtistChangeRequestMapper.selectPendingByArtistId(userId);
|
||||
} else if (Integer.valueOf(3).equals(userType)) {
|
||||
requests = orderArtistChangeRequestMapper.selectPendingByArtistId(userId);
|
||||
} else {
|
||||
requests = orderArtistChangeRequestMapper.selectPendingByUserId(userId);
|
||||
}
|
||||
return requests.stream()
|
||||
.map(this::buildArtistChangeRequestVO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType) {
|
||||
OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId);
|
||||
assertCanProcessArtistChange(request, userId, userType);
|
||||
|
||||
OrderDO order = requireActiveOrder(request.getOrderId());
|
||||
if (!Integer.valueOf(1).equals(order.getStatus())) {
|
||||
throw new RuntimeException("仅待服务订单允许改派");
|
||||
}
|
||||
if (!Objects.equals(order.getUserId(), request.getCustomerId())) {
|
||||
throw new RuntimeException("改派申请客户与订单不匹配");
|
||||
}
|
||||
|
||||
OrderItemDO item = orderItemMapper.selectByIdForUpdate(request.getOrderItemId());
|
||||
if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), order.getId())) {
|
||||
throw new RuntimeException("订单项不存在");
|
||||
}
|
||||
if (!Objects.equals(item.getArtistId(), request.getFromArtistId())) {
|
||||
throw new RuntimeException("原美甲师已变更,无法继续改派");
|
||||
}
|
||||
|
||||
ProductDO product = requireActiveProduct(item.getProductId());
|
||||
validateRequestedArtistForItem(order.getShopId(), request.getToArtistId(), item, product);
|
||||
|
||||
LocalDateTime approvedTime = LocalDateTime.now();
|
||||
if (orderArtistChangeRequestMapper.approvePending(request.getId(), approvedTime) == 0) {
|
||||
throw new RuntimeException("改派申请已处理");
|
||||
}
|
||||
item.setArtistId(request.getToArtistId());
|
||||
orderItemMapper.updateById(item);
|
||||
request.setStatus(CHANGE_STATUS_APPROVED);
|
||||
request.setApprovedTime(approvedTime);
|
||||
request.setPendingKey(null);
|
||||
return buildArtistChangeRequestVO(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto) {
|
||||
OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId);
|
||||
assertCanProcessArtistChange(request, userId, userType);
|
||||
LocalDateTime rejectedTime = LocalDateTime.now();
|
||||
String rejectReason = trimToNull(dto == null ? null : dto.getRejectReason());
|
||||
if (orderArtistChangeRequestMapper.rejectPending(request.getId(), rejectReason, rejectedTime) == 0) {
|
||||
throw new RuntimeException("改派申请已处理");
|
||||
}
|
||||
request.setStatus(CHANGE_STATUS_REJECTED);
|
||||
request.setRejectReason(rejectReason);
|
||||
request.setRejectedTime(rejectedTime);
|
||||
request.setPendingKey(null);
|
||||
return buildArtistChangeRequestVO(request);
|
||||
}
|
||||
|
||||
public void createPendingArtistReviewTasksAndNotifyFromOutbox(OrderDO order) {
|
||||
createPendingArtistReviewTasksAndNotify(order);
|
||||
}
|
||||
|
||||
private void createPendingArtistReviewTasksAndNotify(OrderDO order) {
|
||||
if (order == null || order.getId() == null || !Integer.valueOf(2).equals(order.getStatus())) {
|
||||
return;
|
||||
}
|
||||
List<OrderItemDO> items = orderItemMapper.selectByOrderId(order.getId());
|
||||
if (items == null || items.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (OrderItemDO item : items) {
|
||||
if (item == null
|
||||
|| item.getId() == null
|
||||
|| Integer.valueOf(1).equals(item.getIsDelete())
|
||||
|| item.getArtistId() == null) {
|
||||
continue;
|
||||
}
|
||||
if (orderArtistReviewMapper.selectByOrderItemId(item.getId()) != null) {
|
||||
continue;
|
||||
}
|
||||
ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>());
|
||||
OrderArtistReviewDO review = new OrderArtistReviewDO();
|
||||
review.setOrderId(order.getId());
|
||||
review.setOrderItemId(item.getId());
|
||||
review.setProductId(item.getProductId());
|
||||
review.setShopId(order.getShopId());
|
||||
review.setArtistId(item.getArtistId());
|
||||
review.setCustomerId(order.getUserId());
|
||||
review.setStatus(REVIEW_STATUS_PENDING);
|
||||
review.setIsDelete(0);
|
||||
review = insertPendingArtistReview(review);
|
||||
if (review == null || review.getId() == null) {
|
||||
continue;
|
||||
}
|
||||
Long messageId = createReviewReminderMessage(order, item, product, review);
|
||||
if (messageId != null) {
|
||||
review.setReminderMessageId(messageId);
|
||||
orderArtistReviewMapper.updateById(review);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private OrderArtistReviewDO insertPendingArtistReview(OrderArtistReviewDO review) {
|
||||
try {
|
||||
orderArtistReviewMapper.insert(review);
|
||||
return review;
|
||||
} catch (DuplicateKeyException exception) {
|
||||
OrderArtistReviewDO existingReview = review == null || review.getOrderItemId() == null
|
||||
? null
|
||||
: orderArtistReviewMapper.selectByOrderItemId(review.getOrderItemId());
|
||||
if (existingReview != null) {
|
||||
return existingReview;
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
private Long createReviewReminderMessage(OrderDO order, OrderItemDO item, ProductDO product, OrderArtistReviewDO review) {
|
||||
String productTitle = product == null ? "订单项目" : product.getTitle();
|
||||
UserDO artist = item == null || item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId());
|
||||
String artistName = artist == null || !StringUtils.hasText(artist.getNickname()) ? "美甲师" : artist.getNickname();
|
||||
return createSystemBusinessMessage(
|
||||
order == null ? null : order.getUserId(),
|
||||
"订单已完成,记得评价美甲师",
|
||||
"您预约的「" + productTitle + "」已完成,请为" + artistName + "提交本次服务评价。",
|
||||
REVIEW_BUSINESS_TYPE,
|
||||
review == null ? null : review.getId(),
|
||||
order == null ? null : "/orders?orderId=" + order.getId(),
|
||||
0L,
|
||||
"系统通知",
|
||||
4
|
||||
);
|
||||
}
|
||||
|
||||
private OrderArtistReviewVO buildArtistReviewVO(OrderArtistReviewDO review) {
|
||||
if (review == null) {
|
||||
return null;
|
||||
}
|
||||
OrderArtistReviewVO vo = new OrderArtistReviewVO();
|
||||
vo.setId(review.getId());
|
||||
vo.setOrderId(review.getOrderId());
|
||||
vo.setOrderItemId(review.getOrderItemId());
|
||||
vo.setProductId(review.getProductId());
|
||||
ProductDO product = getProductFromCache(review.getProductId(), new HashMap<>());
|
||||
vo.setProductTitle(product == null ? null : product.getTitle());
|
||||
vo.setArtistId(review.getArtistId());
|
||||
UserDO artist = review.getArtistId() == null ? null : userMapper.selectById(review.getArtistId());
|
||||
vo.setArtistName(artist == null ? null : artist.getNickname());
|
||||
vo.setArtistAvatar(artist == null ? null : objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar()));
|
||||
vo.setUserId(review.getCustomerId());
|
||||
vo.setCustomerId(review.getCustomerId());
|
||||
vo.setRating(review.getRatingScore());
|
||||
vo.setRatingScore(review.getRatingScore());
|
||||
vo.setContent(review.getContent());
|
||||
vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds())));
|
||||
vo.setStatus(review.getStatus());
|
||||
vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价");
|
||||
vo.setReminderMessageId(review.getReminderMessageId());
|
||||
vo.setSubmitTime(review.getSubmittedAt());
|
||||
vo.setSubmittedAt(review.getSubmittedAt());
|
||||
vo.setCreateTime(review.getCreateTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private OrderDO requireActiveOrder(Long orderId) {
|
||||
if (orderId == null) {
|
||||
throw new RuntimeException("订单信息不完整");
|
||||
}
|
||||
OrderDO order = orderMapper.selectById(orderId);
|
||||
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
|
||||
throw new RuntimeException("订单不存在");
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
private boolean canAccessOrder(OrderDO order, Long userId, Integer userType) {
|
||||
if (order == null || userId == null) {
|
||||
return false;
|
||||
}
|
||||
if (Objects.equals(order.getUserId(), userId)) {
|
||||
return true;
|
||||
}
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
Integer effectiveType = userType == null && user != null ? user.getType() : userType;
|
||||
if (Integer.valueOf(4).equals(effectiveType)) {
|
||||
return true;
|
||||
}
|
||||
if (order.getShopId() != null && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId())) {
|
||||
return true;
|
||||
}
|
||||
List<OrderItemDO> items = orderItemMapper.selectByOrderId(order.getId());
|
||||
return items != null && items.stream()
|
||||
.filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete()))
|
||||
.anyMatch(item -> Objects.equals(item.getArtistId(), userId));
|
||||
}
|
||||
|
||||
private BigDecimal normalizeReviewRating(BigDecimal rating) {
|
||||
if (rating == null) {
|
||||
throw new RuntimeException("评分不能为空");
|
||||
}
|
||||
BigDecimal normalized;
|
||||
try {
|
||||
normalized = rating.setScale(1, RoundingMode.UNNECESSARY);
|
||||
} catch (ArithmeticException exception) {
|
||||
throw new RuntimeException("评分必须按0.5分递增");
|
||||
}
|
||||
if (normalized.compareTo(new BigDecimal("0.5")) < 0 || normalized.compareTo(new BigDecimal("5.0")) > 0) {
|
||||
throw new RuntimeException("评分必须在0.5到5分之间");
|
||||
}
|
||||
BigDecimal doubled = normalized.multiply(new BigDecimal("2"));
|
||||
if (doubled.stripTrailingZeros().scale() > 0) {
|
||||
throw new RuntimeException("评分必须按0.5分递增");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String trimToNull(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private String joinLongIds(List<Long> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String joined = ids.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.joining(","));
|
||||
return joined.isBlank() ? null : joined;
|
||||
}
|
||||
|
||||
private Set<Long> parseIdSet(String rawIds) {
|
||||
if (!StringUtils.hasText(rawIds)) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
LinkedHashSet<Long> result = new LinkedHashSet<>();
|
||||
for (String part : rawIds.split("[,;]")) {
|
||||
if (!StringUtils.hasText(part)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
result.add(Long.parseLong(part.trim()));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void refreshArtistRating(Long artistId) {
|
||||
if (artistId == null) {
|
||||
return;
|
||||
}
|
||||
BigDecimal average = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
|
||||
if (average == null) {
|
||||
return;
|
||||
}
|
||||
NailArtistInfoDO artistInfo = getArtistInfoByUserId(artistId);
|
||||
if (artistInfo == null) {
|
||||
return;
|
||||
}
|
||||
artistInfo.setRating(average.setScale(1, RoundingMode.HALF_UP));
|
||||
nailArtistInfoMapper.updateById(artistInfo);
|
||||
}
|
||||
|
||||
private OrderItemDO requireOrderItem(Long orderItemId, Long orderId) {
|
||||
return requireOrderItem(orderItemId, orderId, false);
|
||||
}
|
||||
|
||||
private OrderItemDO requireOrderItemForUpdate(Long orderItemId, Long orderId) {
|
||||
return requireOrderItem(orderItemId, orderId, true);
|
||||
}
|
||||
|
||||
private String buildArtistChangePendingKey(Long orderItemId) {
|
||||
return orderItemId == null ? null : ARTIST_CHANGE_PENDING_KEY_PREFIX + orderItemId;
|
||||
}
|
||||
|
||||
private OrderItemDO requireOrderItem(Long orderItemId, Long orderId, boolean forUpdate) {
|
||||
if (orderItemId == null) {
|
||||
throw new RuntimeException("订单项信息不完整");
|
||||
}
|
||||
OrderItemDO item = forUpdate
|
||||
? orderItemMapper.selectByIdForUpdate(orderItemId)
|
||||
: orderItemMapper.selectById(orderItemId);
|
||||
if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), orderId)) {
|
||||
throw new RuntimeException("订单项不存在");
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
private ProductDO requireActiveProduct(Long productId) {
|
||||
ProductDO product = getProductFromCache(productId, new HashMap<>());
|
||||
if (product == null) {
|
||||
throw new RuntimeException("商品不存在或已删除");
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
private boolean isArtistAvailableForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) {
|
||||
try {
|
||||
validateRequestedArtistForItem(shopId, artistId, item, product);
|
||||
return true;
|
||||
} catch (RuntimeException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private OrderArtistChangeOptionsVO.ArtistOptionVO buildArtistOptionVO(Long artistId) {
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) || !bookableArtistSupport.isBookableServiceUser(artist)) {
|
||||
return null;
|
||||
}
|
||||
NailArtistInfoDO info = getArtistInfoByUserId(artistId);
|
||||
OrderArtistChangeOptionsVO.ArtistOptionVO vo = new OrderArtistChangeOptionsVO.ArtistOptionVO();
|
||||
vo.setArtistId(artist.getId());
|
||||
vo.setArtistName(artist.getNickname());
|
||||
vo.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar()));
|
||||
vo.setUserType(artist.getType());
|
||||
vo.setParticipateProduction(info != null && Integer.valueOf(1).equals(info.getParticipateProduction()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private void validateRequestedArtistForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) {
|
||||
validateArtistForProduct(product, artistId);
|
||||
if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) {
|
||||
throw new RuntimeException("新美甲师不可预约或不属于当前店铺");
|
||||
}
|
||||
if (item == null || item.getAppointmentTime() == null) {
|
||||
return;
|
||||
}
|
||||
int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity());
|
||||
long durationMinutes = resolveServiceDurationMinutes(product) * quantity;
|
||||
LocalDateTime startTime = item.getAppointmentTime();
|
||||
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
|
||||
validateBusinessHours(getShopFromCache(shopId == null ? product.getShopId() : shopId, new HashMap<>()), startTime, endTime, product.getTitle());
|
||||
validateArtistScheduleConflicts(artistId, Collections.singletonList(new AppointmentSlot(product.getTitle(), startTime, endTime)), new HashMap<>());
|
||||
}
|
||||
|
||||
private Long createArtistChangeMessage(OrderDO order, OrderArtistChangeRequestDO request) {
|
||||
ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>());
|
||||
UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId());
|
||||
UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId());
|
||||
String fromName = fromArtist == null || !StringUtils.hasText(fromArtist.getNickname()) ? "原美甲师" : fromArtist.getNickname();
|
||||
String toName = toArtist == null || !StringUtils.hasText(toArtist.getNickname()) ? "新美甲师" : toArtist.getNickname();
|
||||
Long messageId = createSystemBusinessMessage(
|
||||
request.getCustomerId(),
|
||||
"美甲师改派申请待确认",
|
||||
"您的订单项目「" + (product == null ? "订单项目" : product.getTitle()) + "」申请由" + fromName + "改派给" + toName + ",请在订单页确认。",
|
||||
CHANGE_BUSINESS_TYPE,
|
||||
request.getId(),
|
||||
order == null ? null : "/orders?orderId=" + order.getId(),
|
||||
request.getRequesterId(),
|
||||
fromName,
|
||||
3
|
||||
);
|
||||
if (messageId != null) {
|
||||
request.setMessageId(messageId);
|
||||
orderArtistChangeRequestMapper.updateById(request);
|
||||
}
|
||||
return messageId;
|
||||
}
|
||||
|
||||
private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request) {
|
||||
if (request == null) {
|
||||
return null;
|
||||
}
|
||||
OrderArtistChangeRequestVO vo = new OrderArtistChangeRequestVO();
|
||||
vo.setId(request.getId());
|
||||
vo.setOrderId(request.getOrderId());
|
||||
vo.setOrderItemId(request.getOrderItemId());
|
||||
vo.setProductId(request.getProductId());
|
||||
ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>());
|
||||
vo.setProductTitle(product == null ? null : product.getTitle());
|
||||
vo.setShopId(request.getShopId());
|
||||
vo.setUserId(request.getCustomerId());
|
||||
vo.setCustomerId(request.getCustomerId());
|
||||
vo.setOriginalArtistId(request.getFromArtistId());
|
||||
vo.setFromArtistId(request.getFromArtistId());
|
||||
UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId());
|
||||
vo.setOriginalArtistName(fromArtist == null ? null : fromArtist.getNickname());
|
||||
vo.setFromArtistName(fromArtist == null ? null : fromArtist.getNickname());
|
||||
vo.setRequestedArtistId(request.getToArtistId());
|
||||
vo.setToArtistId(request.getToArtistId());
|
||||
UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId());
|
||||
vo.setRequestedArtistName(toArtist == null ? null : toArtist.getNickname());
|
||||
vo.setToArtistName(toArtist == null ? null : toArtist.getNickname());
|
||||
vo.setRequesterId(request.getRequesterId());
|
||||
UserDO requester = request.getRequesterId() == null ? null : userMapper.selectById(request.getRequesterId());
|
||||
vo.setRequesterName(requester == null ? null : requester.getNickname());
|
||||
vo.setStatus(request.getStatus());
|
||||
vo.setStatusText(resolveArtistChangeStatusText(request.getStatus()));
|
||||
vo.setReason(request.getReason());
|
||||
vo.setRejectReason(request.getRejectReason());
|
||||
vo.setReviewerId(request.getCustomerId());
|
||||
vo.setMessageId(request.getMessageId());
|
||||
vo.setReviewTime(request.getApprovedTime() != null ? request.getApprovedTime() : request.getRejectedTime());
|
||||
vo.setApprovedTime(request.getApprovedTime());
|
||||
vo.setRejectedTime(request.getRejectedTime());
|
||||
vo.setExpireTime(request.getExpireTime());
|
||||
vo.setCreateTime(request.getCreateTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private OrderArtistChangeRequestDO requirePendingArtistChangeRequest(Long requestId) {
|
||||
if (requestId == null) {
|
||||
throw new RuntimeException("改派申请信息不完整");
|
||||
}
|
||||
OrderArtistChangeRequestDO request = orderArtistChangeRequestMapper.selectById(requestId);
|
||||
if (request == null || Integer.valueOf(1).equals(request.getIsDelete())) {
|
||||
throw new RuntimeException("改派申请不存在");
|
||||
}
|
||||
if (!CHANGE_STATUS_PENDING.equals(request.getStatus())) {
|
||||
throw new RuntimeException("改派申请已处理");
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
if (request.getExpireTime() != null && !request.getExpireTime().isAfter(now)) {
|
||||
orderArtistChangeRequestMapper.expirePendingById(request.getId(), now);
|
||||
request.setStatus(CHANGE_STATUS_EXPIRED);
|
||||
request.setPendingKey(null);
|
||||
throw new RuntimeException("改派申请已过期");
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private void assertCanProcessArtistChange(OrderArtistChangeRequestDO request, Long userId, Integer userType) {
|
||||
if (request == null || userId == null || !Objects.equals(request.getCustomerId(), userId)) {
|
||||
throw new RuntimeException("仅订单客户可以处理改派申请");
|
||||
}
|
||||
}
|
||||
|
||||
@org.springframework.scheduling.annotation.Scheduled(fixedDelay = 300000L)
|
||||
public void expireDueArtistChangeRequests() {
|
||||
orderArtistChangeRequestMapper.expirePendingBefore(LocalDateTime.now());
|
||||
}
|
||||
|
||||
private boolean canRequestArtistChangeForItem(OrderDO order, OrderItemDO item, Long userId) {
|
||||
if (order == null || item == null || userId == null) {
|
||||
return false;
|
||||
}
|
||||
if (Objects.equals(item.getArtistId(), userId)) {
|
||||
return true;
|
||||
}
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
if (user == null || !Integer.valueOf(2).equals(user.getType())) {
|
||||
return false;
|
||||
}
|
||||
NailArtistInfoDO info = getArtistInfoByUserId(userId);
|
||||
return info != null
|
||||
&& Integer.valueOf(1).equals(info.getParticipateProduction())
|
||||
&& order.getShopId() != null
|
||||
&& userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId());
|
||||
}
|
||||
|
||||
private void ensureArtistChangeRequester(Long userId) {
|
||||
UserDO user = userMapper.selectById(userId);
|
||||
if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) {
|
||||
throw new RuntimeException("请先登录有效账号");
|
||||
}
|
||||
if (Integer.valueOf(3).equals(user.getType())) {
|
||||
return;
|
||||
}
|
||||
if (Integer.valueOf(2).equals(user.getType())) {
|
||||
NailArtistInfoDO info = getArtistInfoByUserId(userId);
|
||||
if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("仅美甲师或参与制作的店长可以申请改派");
|
||||
}
|
||||
|
||||
private NailArtistInfoDO getArtistInfoByUserId(Long userId) {
|
||||
if (userId == null) {
|
||||
return null;
|
||||
}
|
||||
return nailArtistInfoMapper.selectOne(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getUserId, userId)
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private String resolveArtistChangeStatusText(String status) {
|
||||
if (CHANGE_STATUS_APPROVED.equals(status)) {
|
||||
return "已同意";
|
||||
}
|
||||
if (CHANGE_STATUS_REJECTED.equals(status)) {
|
||||
return "已拒绝";
|
||||
}
|
||||
return "待确认";
|
||||
}
|
||||
|
||||
private Long createSystemBusinessMessage(Long targetUserId,
|
||||
String title,
|
||||
String content,
|
||||
String businessType,
|
||||
Long businessId,
|
||||
String actionPath,
|
||||
Long publisherId,
|
||||
String publisherName,
|
||||
Integer publisherType) {
|
||||
if (targetUserId == null) {
|
||||
return null;
|
||||
}
|
||||
String targetIds = String.valueOf(targetUserId);
|
||||
String idempotencyKey = buildSystemMessageIdempotencyKey(businessType, businessId, targetUserId);
|
||||
if (StringUtils.hasText(idempotencyKey)) {
|
||||
Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey);
|
||||
if (existingMessageId != null) {
|
||||
return existingMessageId;
|
||||
}
|
||||
}
|
||||
SystemMessageDO message = new SystemMessageDO();
|
||||
message.setTitle(title);
|
||||
message.setContent(content);
|
||||
message.setPublisherId(publisherId == null ? 0L : publisherId);
|
||||
message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知");
|
||||
message.setPublisherType(publisherType == null ? 4 : publisherType);
|
||||
message.setTargetType(MESSAGE_TARGET_SELECTED_USERS);
|
||||
message.setTargetIds(targetIds);
|
||||
message.setBusinessType(businessType);
|
||||
message.setBusinessId(businessId);
|
||||
message.setActionPath(actionPath);
|
||||
message.setIdempotencyKey(idempotencyKey);
|
||||
message.setPopupEnabled(1);
|
||||
message.setStatus(1);
|
||||
message.setPublishTime(LocalDateTime.now());
|
||||
message.setIsDelete(0);
|
||||
try {
|
||||
systemMessageMapper.insert(message);
|
||||
} catch (DuplicateKeyException exception) {
|
||||
Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey);
|
||||
if (existingMessageId != null) {
|
||||
return existingMessageId;
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
return message.getId();
|
||||
}
|
||||
|
||||
private String buildSystemMessageIdempotencyKey(String businessType, Long businessId, Long targetUserId) {
|
||||
if (!StringUtils.hasText(businessType) || businessId == null || targetUserId == null) {
|
||||
return null;
|
||||
}
|
||||
return businessType + ":" + businessId + ":" + targetUserId;
|
||||
}
|
||||
|
||||
private Long findSystemBusinessMessageId(String businessType,
|
||||
Long businessId,
|
||||
String targetIds,
|
||||
String idempotencyKey) {
|
||||
if (!StringUtils.hasText(idempotencyKey)) {
|
||||
return null;
|
||||
}
|
||||
SystemMessageDO existingMessage = systemMessageMapper.selectOne(new LambdaQueryWrapper<SystemMessageDO>()
|
||||
.eq(SystemMessageDO::getBusinessType, businessType)
|
||||
.eq(SystemMessageDO::getBusinessId, businessId)
|
||||
.eq(SystemMessageDO::getTargetType, MESSAGE_TARGET_SELECTED_USERS)
|
||||
.eq(SystemMessageDO::getTargetIds, targetIds)
|
||||
.eq(SystemMessageDO::getIsDelete, 0)
|
||||
.and(wrapper -> wrapper
|
||||
.eq(SystemMessageDO::getIdempotencyKey, idempotencyKey)
|
||||
.or()
|
||||
.isNull(SystemMessageDO::getIdempotencyKey))
|
||||
.last("LIMIT 1"));
|
||||
return existingMessage == null ? null : existingMessage.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `buildOrderVO`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -1045,6 +1801,21 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
|
||||
OrderArtistReviewDO review = orderArtistReviewMapper.selectByOrderItemId(item.getId());
|
||||
if (review != null) {
|
||||
OrderArtistReviewVO reviewVO = buildArtistReviewVO(review);
|
||||
if (Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) {
|
||||
itemVO.setPendingReview(reviewVO);
|
||||
} else if (Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus())) {
|
||||
itemVO.setReviewSummary(reviewVO);
|
||||
}
|
||||
}
|
||||
|
||||
OrderArtistChangeRequestDO pendingChangeRequest = orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId());
|
||||
if (pendingChangeRequest != null) {
|
||||
itemVO.setPendingArtistChangeRequest(buildArtistChangeRequestVO(pendingChangeRequest));
|
||||
}
|
||||
|
||||
orderItemVOs.add(itemVO);
|
||||
}
|
||||
|
||||
|
||||
+99
-52
@@ -193,6 +193,17 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
*/
|
||||
public List<PermissionVO> listUserPermissions(Long userId) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<UserShopRoleDO> activeShopRoles = listActiveShopRoles(userId);
|
||||
if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) {
|
||||
return listPermissionsByIds(listPermissionIdsByShopRoles(activeShopRoles)).stream()
|
||||
.filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
@@ -224,7 +235,9 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
return permissionVOs;
|
||||
return permissionVOs.stream()
|
||||
.filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -440,6 +453,21 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
*/
|
||||
public boolean hasPermission(Long userId, String permissionCode) {
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
if (isShopBootstrapAdmin(userDO)) {
|
||||
return SHOP_BOOTSTRAP_PERMISSION_CODES.contains(permissionCode);
|
||||
}
|
||||
if (!isPermissionAllowedForUserType(userDO, permissionCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<UserShopRoleDO> activeShopRoles = listActiveShopRoles(userId);
|
||||
if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) {
|
||||
return hasShopRolePermission(activeShopRoles, permissionCode);
|
||||
}
|
||||
|
||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
@@ -463,50 +491,14 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
);
|
||||
if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) {
|
||||
/**
|
||||
* Run business method `hasShopRolePermission`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
* @param permissionCode parameter `permissionCode` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return hasShopRolePermission(userId, permissionCode);
|
||||
}
|
||||
|
||||
if (isShopBootstrapAdmin(userDO)) {
|
||||
return SHOP_BOOTSTRAP_PERMISSION_CODES.contains(permissionCode);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `hasShopRolePermission`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
* @param permissionCode parameter `permissionCode` supplied by the caller
|
||||
* @return private boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private boolean hasShopRolePermission(Long userId, String permissionCode) {
|
||||
List<UserShopRoleDO> roles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class)
|
||||
.eq(UserShopRoleDO::getUserId, userId)
|
||||
.eq(UserShopRoleDO::getIsDelete, 0)
|
||||
.eq(UserShopRoleDO::getStatus, 1));
|
||||
if (roles.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<Long> roleIds = roles.stream().map(UserShopRoleDO::getRoleId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
|
||||
if (roleIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<Long> permissionIds = shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class)
|
||||
.in(ShopRolePermissionDO::getRoleId, roleIds)
|
||||
.eq(ShopRolePermissionDO::getIsDelete, 0))
|
||||
.stream()
|
||||
.map(ShopRolePermissionDO::getPermissionId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
private boolean hasShopRolePermission(List<UserShopRoleDO> activeShopRoles, String permissionCode) {
|
||||
List<Long> permissionIds = listPermissionIdsByShopRoles(activeShopRoles);
|
||||
if (permissionIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
@@ -555,21 +547,58 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
* @return private Set<String> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private Set<String> listPermissionCodesByUserId(Long userId) {
|
||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||
.eq(UserPermissionDO::getUserId, userId)
|
||||
);
|
||||
if (userPermissions.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
return listUserPermissions(userId).stream()
|
||||
.map(PermissionVO::getPermissionCode)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private List<UserShopRoleDO> listActiveShopRoles(Long userId) {
|
||||
if (userId == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Long> permissionIds = userPermissions.stream()
|
||||
.map(UserPermissionDO::getPermissionId)
|
||||
Long currentShopId = RequestShopContext.getCurrentShopId();
|
||||
List<UserShopRoleDO> activeShopRoles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class)
|
||||
.eq(UserShopRoleDO::getUserId, userId)
|
||||
.eq(currentShopId != null, UserShopRoleDO::getShopId, currentShopId)
|
||||
.eq(UserShopRoleDO::getIsDelete, 0)
|
||||
.eq(UserShopRoleDO::getStatus, 1));
|
||||
if (currentShopId == null) {
|
||||
return activeShopRoles;
|
||||
}
|
||||
return activeShopRoles.stream()
|
||||
.filter(role -> Objects.equals(currentShopId, role.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<Long> listPermissionIdsByShopRoles(List<UserShopRoleDO> activeShopRoles) {
|
||||
if (activeShopRoles == null || activeShopRoles.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Long> roleIds = activeShopRoles.stream()
|
||||
.map(UserShopRoleDO::getRoleId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (permissionIds.isEmpty()) {
|
||||
return Collections.emptySet();
|
||||
if (roleIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
return shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class)
|
||||
.in(ShopRolePermissionDO::getRoleId, roleIds)
|
||||
.eq(ShopRolePermissionDO::getIsDelete, 0))
|
||||
.stream()
|
||||
.filter(permission -> roleIds.contains(permission.getRoleId()))
|
||||
.map(ShopRolePermissionDO::getPermissionId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<PermissionVO> listPermissionsByIds(List<Long> permissionIds) {
|
||||
if (permissionIds == null || permissionIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
return permissionMapper.selectList(
|
||||
@@ -577,8 +606,26 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
||||
.in(PermissionDO::getId, permissionIds)
|
||||
.eq(PermissionDO::getIsDelete, 0)
|
||||
).stream()
|
||||
.map(PermissionDO::getPermissionCode)
|
||||
.collect(Collectors.toSet());
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private boolean usesShopRoleEffectivePermissions(UserDO userDO, List<UserShopRoleDO> activeShopRoles) {
|
||||
return !isPlatformAdmin(userDO) && activeShopRoles != null && !activeShopRoles.isEmpty();
|
||||
}
|
||||
|
||||
private boolean isPermissionAllowedForUserType(UserDO userDO, String permissionCode) {
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
if (isPlatformAdmin(userDO)) {
|
||||
return true;
|
||||
}
|
||||
return PermissionPolicy.getDefaultPermissionCodeSet(userDO.getType()).contains(permissionCode);
|
||||
}
|
||||
|
||||
private boolean isPlatformAdmin(UserDO userDO) {
|
||||
return userDO != null && Integer.valueOf(4).equals(userDO.getType());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+55
@@ -1,9 +1,13 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO;
|
||||
import com.xiaowang.yuminailcore.mapper.SecurityAuditLogMapper;
|
||||
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -35,6 +39,57 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<SecurityAuditLogVO> pageLogs(String account,
|
||||
String action,
|
||||
String result,
|
||||
LocalDateTime startTime,
|
||||
LocalDateTime endTime,
|
||||
Integer page,
|
||||
Integer size) {
|
||||
int pageNo = page == null || page < 1 ? 1 : page;
|
||||
int pageSize = size == null || size < 1 ? 20 : Math.min(size, 100);
|
||||
LambdaQueryWrapper<SecurityAuditLogDO> wrapper = new LambdaQueryWrapper<>();
|
||||
if (StringUtils.hasText(account)) {
|
||||
wrapper.like(SecurityAuditLogDO::getAccount, account.trim());
|
||||
}
|
||||
if (StringUtils.hasText(action)) {
|
||||
wrapper.eq(SecurityAuditLogDO::getAction, action.trim());
|
||||
}
|
||||
if (StringUtils.hasText(result)) {
|
||||
wrapper.eq(SecurityAuditLogDO::getResult, result.trim());
|
||||
}
|
||||
if (startTime != null) {
|
||||
wrapper.ge(SecurityAuditLogDO::getOperateTime, startTime);
|
||||
}
|
||||
if (endTime != null) {
|
||||
wrapper.le(SecurityAuditLogDO::getOperateTime, endTime);
|
||||
}
|
||||
wrapper.orderByDesc(SecurityAuditLogDO::getOperateTime).orderByDesc(SecurityAuditLogDO::getId);
|
||||
Page<SecurityAuditLogDO> logPage = auditLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
|
||||
|
||||
PageResultVO<SecurityAuditLogVO> resultVO = new PageResultVO<>();
|
||||
resultVO.setList(logPage.getRecords().stream().map(this::toVO).toList());
|
||||
resultVO.setTotal(logPage.getTotal());
|
||||
resultVO.setPage(pageNo);
|
||||
resultVO.setSize(pageSize);
|
||||
return resultVO;
|
||||
}
|
||||
|
||||
private SecurityAuditLogVO toVO(SecurityAuditLogDO log) {
|
||||
SecurityAuditLogVO vo = new SecurityAuditLogVO();
|
||||
vo.setId(log.getId());
|
||||
vo.setUserId(log.getUserId());
|
||||
vo.setAccount(log.getAccount());
|
||||
vo.setAction(log.getAction());
|
||||
vo.setResult(log.getResult());
|
||||
vo.setReason(log.getReason());
|
||||
vo.setIpAddress(log.getIpAddress());
|
||||
vo.setDeviceId(log.getDeviceId());
|
||||
vo.setOperateTime(log.getOperateTime());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private String resolveClientIp(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return null;
|
||||
|
||||
+6
-47
@@ -50,6 +50,8 @@ import java.util.stream.Collectors;
|
||||
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements ShopService {
|
||||
private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:";
|
||||
private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:";
|
||||
private static final String SHOP_DELETE_DISABLED_MESSAGE = "店铺删除已停用,请使用停用封存";
|
||||
private static final String DISABLED_SHOP_ARCHIVED_MESSAGE = "停用店铺已封存,仅允许重新启用";
|
||||
/**
|
||||
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
@@ -134,6 +136,9 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
if (shopDO == null) {
|
||||
return false;
|
||||
}
|
||||
if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) {
|
||||
throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE);
|
||||
}
|
||||
shopDO.setShopName(shopDTO.getShopName());
|
||||
shopDO.setDescription(shopDTO.getDescription());
|
||||
shopDO.setAddress(shopDTO.getAddress());
|
||||
@@ -170,53 +175,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public boolean deleteShop(Long id) {
|
||||
ShopDO shopDO = shopMapper.selectById(id);
|
||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
||||
return false;
|
||||
}
|
||||
List<Long> couponIds = couponMapper.selectList(Wrappers.lambdaQuery(CouponDO.class)
|
||||
.select(CouponDO::getId)
|
||||
.eq(CouponDO::getShopId, id)
|
||||
.eq(CouponDO::getIsDelete, 0))
|
||||
.stream()
|
||||
.map(CouponDO::getId)
|
||||
.toList();
|
||||
productMapper.update(null, Wrappers.lambdaUpdate(ProductDO.class)
|
||||
.eq(ProductDO::getShopId, id)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.set(ProductDO::getIsDelete, 1));
|
||||
couponMapper.update(null, Wrappers.lambdaUpdate(CouponDO.class)
|
||||
.eq(CouponDO::getShopId, id)
|
||||
.eq(CouponDO::getIsDelete, 0)
|
||||
.set(CouponDO::getIsDelete, 1));
|
||||
tagMapper.update(null, Wrappers.lambdaUpdate(TagDO.class)
|
||||
.eq(TagDO::getShopId, id)
|
||||
.eq(TagDO::getIsDelete, 0)
|
||||
.set(TagDO::getIsDelete, 1));
|
||||
commentMapper.update(null, Wrappers.lambdaUpdate(CommentDO.class)
|
||||
.eq(CommentDO::getShopId, id)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.set(CommentDO::getIsDelete, 1));
|
||||
if (!couponIds.isEmpty()) {
|
||||
userCouponMapper.update(null, Wrappers.lambdaUpdate(UserCouponDO.class)
|
||||
.in(UserCouponDO::getCouponId, couponIds)
|
||||
.eq(UserCouponDO::getIsDelete, 0)
|
||||
.set(UserCouponDO::getIsDelete, 1));
|
||||
}
|
||||
userShopBindingSupport.deleteBindingsByShopId(id);
|
||||
shopDO.setStatus(0);
|
||||
shopDO.setIsDelete(1);
|
||||
boolean deleted = shopMapper.updateById(shopDO) > 0;
|
||||
if (deleted) {
|
||||
/**
|
||||
* Run business method `evictShopCaches`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param id parameter `id` supplied by the caller
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
evictShopCaches(id);
|
||||
}
|
||||
return deleted;
|
||||
throw new RuntimeException(SHOP_DELETE_DISABLED_MESSAGE);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+13
@@ -134,6 +134,9 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
message.setPublisherType(currentUser.getType());
|
||||
message.setTargetType(targetType);
|
||||
message.setTargetIds(joinIds(targetIds));
|
||||
message.setBusinessType(trimToNull(dto.getBusinessType()));
|
||||
message.setBusinessId(dto.getBusinessId());
|
||||
message.setActionPath(trimToNull(dto.getActionPath()));
|
||||
message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1);
|
||||
message.setStatus(1);
|
||||
message.setPublishTime(LocalDateTime.now());
|
||||
@@ -640,6 +643,9 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
vo.setTargetType(message.getTargetType());
|
||||
vo.setTargetTypeName(targetTypeName(message.getTargetType()));
|
||||
vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds())));
|
||||
vo.setBusinessType(message.getBusinessType());
|
||||
vo.setBusinessId(message.getBusinessId());
|
||||
vo.setActionPath(message.getActionPath());
|
||||
vo.setPopupEnabled(message.getPopupEnabled());
|
||||
vo.setStatus(message.getStatus());
|
||||
vo.setPublishTime(message.getPublishTime());
|
||||
@@ -775,6 +781,13 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
return targetType.trim().toUpperCase();
|
||||
}
|
||||
|
||||
private String trimToNull(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `normalizeIds`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
public final class OrderStateMachine {
|
||||
|
||||
private OrderStateMachine() {
|
||||
}
|
||||
|
||||
public static boolean isAllowedTransition(Integer fromStatus, Integer toStatus) {
|
||||
OrderStatus from = OrderStatus.requireKnown(fromStatus);
|
||||
OrderStatus to = OrderStatus.requireKnown(toStatus);
|
||||
return from == OrderStatus.PENDING_SERVICE
|
||||
&& (to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED);
|
||||
}
|
||||
|
||||
public static void requireAllowedTransition(Integer fromStatus, Integer toStatus) {
|
||||
if (!isAllowedTransition(fromStatus, toStatus)) {
|
||||
throw new RuntimeException("订单状态不允许处理");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public enum OrderStatus {
|
||||
PENDING_SERVICE(1),
|
||||
COMPLETED(2),
|
||||
CANCELLED(3);
|
||||
|
||||
private final int code;
|
||||
|
||||
OrderStatus(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public static OrderStatus requireKnown(Integer code) {
|
||||
return Arrays.stream(values())
|
||||
.filter(status -> Integer.valueOf(status.code).equals(code))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("无效的订单状态"));
|
||||
}
|
||||
}
|
||||
+10
-6
@@ -26,11 +26,12 @@ public final class PermissionCatalog {
|
||||
"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",
|
||||
"order:view", "order:process", "order:edit", "order:delete", "order:artist-change",
|
||||
"nail_artist:view", "nail_artist:edit",
|
||||
"message:view", "message:create", "message:delete",
|
||||
"announcement:view", "announcement:create", "announcement:delete",
|
||||
"messagehub:config:manage",
|
||||
"security:audit:view",
|
||||
"legal_agreement:manage"
|
||||
);
|
||||
|
||||
@@ -46,7 +47,7 @@ public final class PermissionCatalog {
|
||||
"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",
|
||||
"order:view", "order:process", "order:edit", "order:delete", "order:artist-change",
|
||||
"nail_artist:view", "nail_artist:edit",
|
||||
"message:view", "message:create",
|
||||
"announcement:view", "announcement:create"
|
||||
@@ -54,14 +55,14 @@ public final class PermissionCatalog {
|
||||
|
||||
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
|
||||
"home:view",
|
||||
"user:view", "user:create",
|
||||
"user:view",
|
||||
"user:balance:view",
|
||||
"product:view", "product:create",
|
||||
"product:view",
|
||||
"shop:view",
|
||||
"tag:view", "tag:create",
|
||||
"tag:view",
|
||||
"coupon:view",
|
||||
"comment:view",
|
||||
"order:view", "order:process"
|
||||
"order:view", "order:process", "order:artist-change"
|
||||
);
|
||||
|
||||
private static final Set<String> PLATFORM_OVERVIEW_PREFIXES = Set.of(
|
||||
@@ -74,6 +75,7 @@ public final class PermissionCatalog {
|
||||
|
||||
private static final Set<String> PLATFORM_OVERVIEW_PERMISSIONS = Set.of(
|
||||
"messagehub:config:manage",
|
||||
"security:audit:view",
|
||||
"legal_agreement:manage"
|
||||
);
|
||||
|
||||
@@ -202,6 +204,7 @@ public final class PermissionCatalog {
|
||||
put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单");
|
||||
put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限");
|
||||
put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限");
|
||||
put(definitions, "order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请");
|
||||
put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口");
|
||||
put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息");
|
||||
put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知");
|
||||
@@ -211,6 +214,7 @@ public final class PermissionCatalog {
|
||||
put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告");
|
||||
put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
|
||||
put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数");
|
||||
put(definitions, "security:audit:view", "查看安全审计", "安全审计", "查看高危操作和登录安全审计日志");
|
||||
put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本");
|
||||
return Map.copyOf(definitions);
|
||||
}
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
public final class SecurityAuditActions {
|
||||
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
public static final String FAIL = "FAIL";
|
||||
|
||||
public static final String ORDER_PROCESS = "ORDER_PROCESS";
|
||||
public static final String ARTIST_CHANGE_APPROVE = "ARTIST_CHANGE_APPROVE";
|
||||
public static final String ARTIST_CHANGE_REJECT = "ARTIST_CHANGE_REJECT";
|
||||
public static final String SHOP_DELETE_BLOCKED = "SHOP_DELETE_BLOCKED";
|
||||
public static final String SHOP_STATUS_UPDATE = "SHOP_STATUS_UPDATE";
|
||||
public static final String PERMISSION_CREATE = "PERMISSION_CREATE";
|
||||
public static final String PERMISSION_UPDATE = "PERMISSION_UPDATE";
|
||||
public static final String PERMISSION_DELETE = "PERMISSION_DELETE";
|
||||
public static final String PERMISSION_ASSIGN = "PERMISSION_ASSIGN";
|
||||
public static final String USER_STATUS_UPDATE = "USER_STATUS_UPDATE";
|
||||
public static final String USER_RESET_PASSWORD = "USER_RESET_PASSWORD";
|
||||
public static final String USER_DELETE = "USER_DELETE";
|
||||
public static final String USER_UNBIND = "USER_UNBIND";
|
||||
public static final String USER_BALANCE_CHANGE = "USER_BALANCE_CHANGE";
|
||||
public static final String USER_VIP_OVERRIDE = "USER_VIP_OVERRIDE";
|
||||
public static final String USER_VIP_RECALCULATE = "USER_VIP_RECALCULATE";
|
||||
|
||||
private SecurityAuditActions() {
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityAuditSupport {
|
||||
|
||||
private final SecurityAuditLogService securityAuditLogService;
|
||||
|
||||
public void success(HttpServletRequest request, String action, String reason) {
|
||||
record(request, action, SecurityAuditActions.SUCCESS, reason);
|
||||
}
|
||||
|
||||
public void fail(HttpServletRequest request, String action, String reason) {
|
||||
record(request, action, SecurityAuditActions.FAIL, reason);
|
||||
}
|
||||
|
||||
private void record(HttpServletRequest request, String action, String result, String reason) {
|
||||
try {
|
||||
Long userId = request == null ? null : asLong(request.getAttribute("userId"));
|
||||
String account = request == null ? null : asString(request.getAttribute("account"));
|
||||
securityAuditLogService.record(userId, account, action, result, reason, request);
|
||||
} catch (Exception ignored) {
|
||||
// Audit failure must never block the guarded business operation.
|
||||
}
|
||||
}
|
||||
|
||||
private Long asLong(Object value) {
|
||||
if (value instanceof Long) {
|
||||
return (Long) value;
|
||||
}
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String asString(Object value) {
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class OrderArtistChangeOptionsVO {
|
||||
private Long orderId;
|
||||
private Long orderItemId;
|
||||
private Long currentArtistId;
|
||||
private String currentArtistName;
|
||||
private List<ArtistOptionVO> artists;
|
||||
|
||||
@Data
|
||||
public static class ArtistOptionVO {
|
||||
private Long artistId;
|
||||
private String artistName;
|
||||
private String artistAvatar;
|
||||
private Integer userType;
|
||||
private Boolean participateProduction;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class OrderArtistChangeRequestVO {
|
||||
private Long id;
|
||||
private Long orderId;
|
||||
private Long orderItemId;
|
||||
private Long productId;
|
||||
private String productTitle;
|
||||
private Long shopId;
|
||||
private Long userId;
|
||||
private Long customerId;
|
||||
private Long originalArtistId;
|
||||
private String originalArtistName;
|
||||
private Long requestedArtistId;
|
||||
private String requestedArtistName;
|
||||
private Long fromArtistId;
|
||||
private String fromArtistName;
|
||||
private Long toArtistId;
|
||||
private String toArtistName;
|
||||
private Long requesterId;
|
||||
private String requesterName;
|
||||
private String status;
|
||||
private String statusText;
|
||||
private String reason;
|
||||
private String rejectReason;
|
||||
private Long reviewerId;
|
||||
private Long messageId;
|
||||
private LocalDateTime reviewTime;
|
||||
private LocalDateTime approvedTime;
|
||||
private LocalDateTime rejectedTime;
|
||||
private LocalDateTime expireTime;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class OrderArtistReviewVO {
|
||||
private Long id;
|
||||
private Long orderId;
|
||||
private Long orderItemId;
|
||||
private Long productId;
|
||||
private String productTitle;
|
||||
private Long artistId;
|
||||
private String artistName;
|
||||
private String artistAvatar;
|
||||
private Long userId;
|
||||
private Long customerId;
|
||||
private BigDecimal rating;
|
||||
private BigDecimal ratingScore;
|
||||
private String content;
|
||||
private List<Long> imageFileIds;
|
||||
private Integer status;
|
||||
private String statusText;
|
||||
private Long reminderMessageId;
|
||||
private LocalDateTime submitTime;
|
||||
private LocalDateTime submittedAt;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -54,4 +54,7 @@ public class OrderItemVO {
|
||||
* Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String appointmentTime;
|
||||
private OrderArtistReviewVO pendingReview;
|
||||
private OrderArtistReviewVO reviewSummary;
|
||||
private OrderArtistChangeRequestVO pendingArtistChangeRequest;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SecurityAuditLogVO {
|
||||
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String account;
|
||||
private String action;
|
||||
private String result;
|
||||
private String reason;
|
||||
private String ipAddress;
|
||||
private String deviceId;
|
||||
private LocalDateTime operateTime;
|
||||
}
|
||||
@@ -55,6 +55,9 @@ public class SystemMessageVO {
|
||||
* Field `targetIds` (List<Long>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private List<Long> targetIds;
|
||||
private String businessType;
|
||||
private Long businessId;
|
||||
private String actionPath;
|
||||
/**
|
||||
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
|
||||
@@ -19,6 +19,7 @@ create table t_balance
|
||||
last_recharge_time datetime null comment '最近一次充值时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间',
|
||||
last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
constraint uk_user_id
|
||||
unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)'
|
||||
)
|
||||
@@ -336,6 +337,75 @@ create index idx_order_id
|
||||
on t_order_item (order_id)
|
||||
comment '按订单查询商品的索引';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS t_order_artist_review
|
||||
(
|
||||
id bigint unsigned auto_increment comment '评价任务ID'
|
||||
primary key,
|
||||
order_id bigint unsigned not null comment '订单ID',
|
||||
order_item_id bigint unsigned not null comment '订单项ID',
|
||||
customer_id bigint unsigned not null comment '下单客户ID',
|
||||
shop_id bigint unsigned null comment '店铺ID',
|
||||
artist_id bigint unsigned not null comment '被评价美甲师ID',
|
||||
product_id bigint unsigned null comment '商品ID',
|
||||
rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5',
|
||||
content varchar(1000) null comment '评价文字',
|
||||
image_file_ids text null comment '评价图片文件ID集合',
|
||||
status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价',
|
||||
reminder_message_id bigint unsigned null comment '提醒消息ID',
|
||||
submitted_at datetime null comment '提交时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||
)
|
||||
comment '订单美甲师评价任务表';
|
||||
|
||||
create unique index uk_order_artist_review_item
|
||||
on t_order_artist_review (order_item_id, is_delete);
|
||||
|
||||
create index idx_order_artist_review_customer
|
||||
on t_order_artist_review (customer_id, status, create_time);
|
||||
|
||||
create index idx_order_artist_review_artist
|
||||
on t_order_artist_review (artist_id, status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS t_order_artist_change_request
|
||||
(
|
||||
id bigint unsigned auto_increment comment '改派申请ID'
|
||||
primary key,
|
||||
order_id bigint unsigned not null comment '订单ID',
|
||||
order_item_id bigint unsigned not null comment '订单项ID',
|
||||
customer_id bigint unsigned not null comment '下单客户ID',
|
||||
shop_id bigint unsigned null comment '店铺ID',
|
||||
product_id bigint unsigned null comment '商品ID',
|
||||
from_artist_id bigint unsigned not null comment '原美甲师ID',
|
||||
to_artist_id bigint unsigned not null comment '新美甲师ID',
|
||||
requester_id bigint unsigned not null comment '申请人ID',
|
||||
status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED',
|
||||
reason varchar(500) null comment '申请原因',
|
||||
reject_reason varchar(500) null comment '拒绝原因',
|
||||
message_id bigint unsigned null comment '提醒消息ID',
|
||||
pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度',
|
||||
approved_time datetime null comment '同意时间',
|
||||
rejected_time datetime null comment '拒绝时间',
|
||||
expire_time datetime null comment '过期时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||
)
|
||||
comment '订单美甲师改派申请表';
|
||||
|
||||
create index idx_order_artist_change_customer
|
||||
on t_order_artist_change_request (customer_id, status, create_time);
|
||||
|
||||
create index idx_order_artist_change_artist
|
||||
on t_order_artist_change_request (from_artist_id, to_artist_id, status);
|
||||
|
||||
create index idx_order_artist_change_shop
|
||||
on t_order_artist_change_request (shop_id, status, create_time);
|
||||
|
||||
create unique index uk_order_artist_change_pending_key
|
||||
on t_order_artist_change_request (pending_key);
|
||||
|
||||
-- auto-generated definition
|
||||
create table t_permission
|
||||
(
|
||||
@@ -572,6 +642,10 @@ create table if not exists t_system_message
|
||||
publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员',
|
||||
target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS',
|
||||
target_ids text null comment '目标ID集合,多个ID以逗号分隔',
|
||||
business_type varchar(64) null comment '业务类型',
|
||||
business_id bigint unsigned null comment '业务ID',
|
||||
action_path varchar(255) null comment '业务跳转路径',
|
||||
idempotency_key varchar(160) null comment '业务消息幂等键',
|
||||
popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗',
|
||||
status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回',
|
||||
publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间',
|
||||
@@ -587,6 +661,9 @@ create index idx_t_system_message_publish_time
|
||||
create index idx_t_system_message_target
|
||||
on t_system_message (target_type, status);
|
||||
|
||||
create unique index uk_t_system_message_idempotency
|
||||
on t_system_message (idempotency_key);
|
||||
|
||||
create table if not exists t_system_message_user_state
|
||||
(
|
||||
id bigint unsigned auto_increment comment '用户消息状态主键'
|
||||
@@ -804,6 +881,7 @@ DELIMITER ;
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额''');
|
||||
CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间''');
|
||||
CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间''');
|
||||
|
||||
UPDATE t_balance
|
||||
SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00)
|
||||
@@ -1195,6 +1273,99 @@ CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NU
|
||||
CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)');
|
||||
CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID''');
|
||||
|
||||
CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型''');
|
||||
CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID''');
|
||||
CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径''');
|
||||
CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键''');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS t_order_artist_review
|
||||
(
|
||||
id bigint unsigned auto_increment comment '评价任务ID'
|
||||
primary key,
|
||||
order_id bigint unsigned not null comment '订单ID',
|
||||
order_item_id bigint unsigned not null comment '订单项ID',
|
||||
customer_id bigint unsigned not null comment '下单客户ID',
|
||||
shop_id bigint unsigned null comment '店铺ID',
|
||||
artist_id bigint unsigned not null comment '被评价美甲师ID',
|
||||
product_id bigint unsigned null comment '商品ID',
|
||||
rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5',
|
||||
content varchar(1000) null comment '评价文字',
|
||||
image_file_ids text null comment '评价图片文件ID集合',
|
||||
status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价',
|
||||
reminder_message_id bigint unsigned null comment '提醒消息ID',
|
||||
submitted_at datetime null comment '提交时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||
)
|
||||
comment '订单美甲师评价任务表';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS t_order_artist_change_request
|
||||
(
|
||||
id bigint unsigned auto_increment comment '改派申请ID'
|
||||
primary key,
|
||||
order_id bigint unsigned not null comment '订单ID',
|
||||
order_item_id bigint unsigned not null comment '订单项ID',
|
||||
customer_id bigint unsigned not null comment '下单客户ID',
|
||||
shop_id bigint unsigned null comment '店铺ID',
|
||||
product_id bigint unsigned null comment '商品ID',
|
||||
from_artist_id bigint unsigned not null comment '原美甲师ID',
|
||||
to_artist_id bigint unsigned not null comment '新美甲师ID',
|
||||
requester_id bigint unsigned not null comment '申请人ID',
|
||||
status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED',
|
||||
reason varchar(500) null comment '申请原因',
|
||||
reject_reason varchar(500) null comment '拒绝原因',
|
||||
message_id bigint unsigned null comment '提醒消息ID',
|
||||
pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度',
|
||||
approved_time datetime null comment '同意时间',
|
||||
rejected_time datetime null comment '拒绝时间',
|
||||
expire_time datetime null comment '过期时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||
)
|
||||
comment '订单美甲师改派申请表';
|
||||
|
||||
CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)');
|
||||
CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)');
|
||||
CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度''');
|
||||
CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)');
|
||||
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS t_business_event_outbox
|
||||
(
|
||||
id bigint unsigned auto_increment comment '事件ID'
|
||||
primary key,
|
||||
event_key varchar(160) not null comment '事件幂等键',
|
||||
event_type varchar(64) not null comment '事件类型',
|
||||
business_type varchar(64) not null comment '业务类型',
|
||||
business_id bigint unsigned not null comment '业务ID',
|
||||
payload_json text null comment '事件载荷',
|
||||
status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED',
|
||||
retry_count int unsigned default 0 not null comment '重试次数',
|
||||
next_retry_time datetime null comment '下次重试时间',
|
||||
last_error varchar(500) null comment '最近错误',
|
||||
claimed_at datetime null comment '认领时间',
|
||||
processed_at datetime null comment '处理完成时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除'
|
||||
)
|
||||
comment '业务事件Outbox表';
|
||||
|
||||
CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)');
|
||||
CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)');
|
||||
|
||||
-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request.
|
||||
-- EXPIRED
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` (
|
||||
`id` bigint unsigned NOT NULL COMMENT '主键ID',
|
||||
`scene_code` varchar(80) NOT NULL COMMENT '业务场景编码',
|
||||
@@ -1312,6 +1483,15 @@ ON DUPLICATE KEY UPDATE
|
||||
update_time = NOW(),
|
||||
is_delete = 0;
|
||||
|
||||
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
|
||||
VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
permission_name = VALUES(permission_name),
|
||||
permission_group = VALUES(permission_group),
|
||||
description = VALUES(description),
|
||||
update_time = NOW(),
|
||||
is_delete = 0;
|
||||
|
||||
INSERT INTO t_user (
|
||||
shop_id,
|
||||
nickname,
|
||||
@@ -1396,6 +1576,7 @@ INNER JOIN t_permission p
|
||||
'comment:delete',
|
||||
'order:view',
|
||||
'order:process',
|
||||
'order:artist-change',
|
||||
'order:edit',
|
||||
'order:delete',
|
||||
'nail_artist:view',
|
||||
@@ -1456,6 +1637,7 @@ INNER JOIN t_permission p
|
||||
'comment:delete',
|
||||
'order:view',
|
||||
'order:process',
|
||||
'order:artist-change',
|
||||
'order:edit',
|
||||
'order:delete',
|
||||
'nail_artist:view',
|
||||
@@ -1482,17 +1664,15 @@ INNER JOIN t_permission p
|
||||
AND p.permission_code IN (
|
||||
'home:view',
|
||||
'user:view',
|
||||
'user:create',
|
||||
'user:balance:view',
|
||||
'product:view',
|
||||
'product:create',
|
||||
'shop:view',
|
||||
'tag:view',
|
||||
'tag:create',
|
||||
'coupon:view',
|
||||
'comment:view',
|
||||
'order:view',
|
||||
'order:process'
|
||||
'order:process',
|
||||
'order:artist-change'
|
||||
)
|
||||
WHERE u.is_delete = 0
|
||||
AND u.type = 3
|
||||
@@ -1884,3 +2064,13 @@ ON DUPLICATE KEY UPDATE
|
||||
is_delete = 0,
|
||||
update_by = VALUES(update_by),
|
||||
update_time = NOW();
|
||||
|
||||
INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
|
||||
VALUES
|
||||
(313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
permission_name = VALUES(permission_name),
|
||||
permission_group = VALUES(permission_group),
|
||||
description = VALUES(description),
|
||||
is_delete = 0,
|
||||
update_time = NOW();
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AdminSecurityAuditControllerTest {
|
||||
|
||||
@Mock
|
||||
private SecurityAuditLogService securityAuditLogService;
|
||||
|
||||
private AdminSecurityAuditController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
controller = new AdminSecurityAuditController(securityAuditLogService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listLogsDelegatesToServiceWithFilters() {
|
||||
PageResultVO<SecurityAuditLogVO> page = new PageResultVO<>();
|
||||
page.setTotal(0L);
|
||||
when(securityAuditLogService.pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
|
||||
any(), any(), eq(1), eq(20))).thenReturn(page);
|
||||
|
||||
Result<PageResultVO<SecurityAuditLogVO>> result = controller.listLogs(
|
||||
"admin", "ORDER_PROCESS", "SUCCESS",
|
||||
"2026-05-01 00:00:00", "2026-05-23 23:59:59", 1, 20);
|
||||
|
||||
assertThat(result.getData()).isSameAs(page);
|
||||
verify(securityAuditLogService).pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
|
||||
any(), any(), eq(1), eq(20));
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.xiaowang.yuminailcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcore.common.Result;
|
||||
import com.xiaowang.yuminailcore.mapper.EffectDiagramMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class FrontendFileControllerTest {
|
||||
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
private MinioService minioService;
|
||||
private ProductMapper productMapper;
|
||||
private ShopMapper shopMapper;
|
||||
private EffectDiagramMapper effectDiagramMapper;
|
||||
private FrontendFileController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectStorageFileService = mock(ObjectStorageFileService.class);
|
||||
minioService = mock(MinioService.class);
|
||||
ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class);
|
||||
productMapper = mock(ProductMapper.class);
|
||||
shopMapper = mock(ShopMapper.class);
|
||||
effectDiagramMapper = mock(EffectDiagramMapper.class);
|
||||
controller = new FrontendFileController(
|
||||
objectStorageFileService,
|
||||
minioService,
|
||||
objectStorageUrlSupport,
|
||||
productMapper,
|
||||
shopMapper,
|
||||
effectDiagramMapper
|
||||
);
|
||||
when(objectStorageUrlSupport.extractObjectName("https://cdn.test/public/a.png")).thenReturn("public/a.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSignedUrlRejectsAvailableFileWhenItIsNotPubliclyReferenced() throws Exception {
|
||||
ObjectStorageFileVO file = file();
|
||||
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||
when(productMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||
when(shopMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||
when(effectDiagramMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||
|
||||
Result<String> result = controller.getSignedUrl(12L, 60);
|
||||
|
||||
assertThat(result.getCode()).isNotEqualTo(200);
|
||||
assertThat(result.getMessage()).contains("文件不可公开访问");
|
||||
verify(minioService, never()).getPresignedUrl(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSignedUrlAllowsPublicProductImageReference() throws Exception {
|
||||
ObjectStorageFileVO file = file();
|
||||
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||
when(productMapper.countPublicImageReference(12L)).thenReturn(1L);
|
||||
when(minioService.getPresignedUrl("public/a.png", 30)).thenReturn("https://signed.test/public/a.png");
|
||||
|
||||
Result<String> result = controller.getSignedUrl(12L, 30);
|
||||
|
||||
assertThat(result.getCode()).isEqualTo(200);
|
||||
assertThat(result.getData()).isEqualTo("https://signed.test/public/a.png");
|
||||
}
|
||||
|
||||
private ObjectStorageFileVO file() {
|
||||
ObjectStorageFileVO file = new ObjectStorageFileVO();
|
||||
file.setId(12L);
|
||||
file.setStatus(1);
|
||||
file.setFileUrl("https://cdn.test/public/a.png");
|
||||
return file;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||
import com.xiaowang.yuminailcore.mapper.BusinessEventOutboxMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class BusinessEventOutboxServiceTest {
|
||||
|
||||
@Mock
|
||||
private BusinessEventOutboxMapper outboxMapper;
|
||||
|
||||
private BusinessEventOutboxServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new BusinessEventOutboxServiceImpl(outboxMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enqueueOrderCompletedCreatesIdempotentEvent() {
|
||||
service.enqueueOrderCompleted(1L);
|
||||
|
||||
ArgumentCaptor<BusinessEventOutboxDO> captor = ArgumentCaptor.forClass(BusinessEventOutboxDO.class);
|
||||
verify(outboxMapper).insert(captor.capture());
|
||||
BusinessEventOutboxDO event = captor.getValue();
|
||||
assertThat(event.getEventType()).isEqualTo("ORDER_COMPLETED");
|
||||
assertThat(event.getBusinessType()).isEqualTo("ORDER");
|
||||
assertThat(event.getBusinessId()).isEqualTo(1L);
|
||||
assertThat(event.getEventKey()).isEqualTo("ORDER:1:COMPLETED");
|
||||
assertThat(event.getStatus()).isEqualTo("PENDING");
|
||||
assertThat(event.getPayloadJson()).contains("\"orderId\":1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateOrderCompletedEventIsIgnored() {
|
||||
when(outboxMapper.insert(any(BusinessEventOutboxDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||
|
||||
service.enqueueOrderCompleted(1L);
|
||||
|
||||
verify(outboxMapper).insert(any(BusinessEventOutboxDO.class));
|
||||
}
|
||||
}
|
||||
+513
@@ -0,0 +1,513 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||
import com.xiaowang.yuminailcore.entity.NailArtistInfoDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderArtistChangeRequestDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||
import com.xiaowang.yuminailcore.entity.OrderItemDO;
|
||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||
import com.xiaowang.yuminailcore.entity.SystemMessageDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderArtistChangeRequestMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderItemMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.SystemMessageMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.BusinessEventOutboxService;
|
||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class OrderServiceImplReviewChangeTest {
|
||||
|
||||
@Mock
|
||||
private OrderMapper orderMapper;
|
||||
@Mock
|
||||
private OrderItemMapper orderItemMapper;
|
||||
@Mock
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
@Mock
|
||||
private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
@Mock
|
||||
private SystemMessageMapper systemMessageMapper;
|
||||
@Mock
|
||||
private NailArtistInfoMapper nailArtistInfoMapper;
|
||||
@Mock
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
@Mock
|
||||
private BookableArtistSupport bookableArtistSupport;
|
||||
@Mock
|
||||
private BusinessEventOutboxService businessEventOutboxService;
|
||||
|
||||
private OrderServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new OrderServiceImpl();
|
||||
ReflectionTestUtils.setField(service, "orderMapper", orderMapper);
|
||||
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
|
||||
ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper);
|
||||
ReflectionTestUtils.setField(service, "orderArtistChangeRequestMapper", orderArtistChangeRequestMapper);
|
||||
ReflectionTestUtils.setField(service, "productMapper", productMapper);
|
||||
ReflectionTestUtils.setField(service, "userMapper", userMapper);
|
||||
ReflectionTestUtils.setField(service, "systemMessageMapper", systemMessageMapper);
|
||||
ReflectionTestUtils.setField(service, "nailArtistInfoMapper", nailArtistInfoMapper);
|
||||
ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport);
|
||||
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
|
||||
ReflectionTestUtils.setField(service, "bookableArtistSupport", bookableArtistSupport);
|
||||
ReflectionTestUtils.setField(service, "businessEventOutboxService", businessEventOutboxService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void processOrderCompletionUpdatesStatusAndEnqueuesOutboxEvent() {
|
||||
OrderDO order = pendingOrder();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(1);
|
||||
|
||||
service.processOrder(1L, 2);
|
||||
|
||||
verify(orderMapper).updateStatusIfCurrent(1L, 1, 2);
|
||||
verify(businessEventOutboxService).enqueueOrderCompleted(1L);
|
||||
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void processOrderCompletionRejectsConcurrentStatusChangeBeforeSideEffects() {
|
||||
OrderDO order = pendingOrder();
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(0);
|
||||
|
||||
assertThatThrownBy(() -> service.processOrder(1L, 2))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("状态已变化");
|
||||
|
||||
verify(businessEventOutboxService, never()).enqueueOrderCompleted(any());
|
||||
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedCreatesPendingReviewTaskAndPopupMessageOnce() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO artist = artist(30L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(30L)).thenReturn(artist);
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||
review.setId(1000L);
|
||||
return 1;
|
||||
});
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
|
||||
OrderArtistReviewDO review = reviewCaptor.getValue();
|
||||
assertThat(review.getOrderItemId()).isEqualTo(10L);
|
||||
assertThat(review.getCustomerId()).isEqualTo(2L);
|
||||
assertThat(review.getArtistId()).isEqualTo(30L);
|
||||
assertThat(review.getStatus()).isZero();
|
||||
|
||||
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
|
||||
verify(systemMessageMapper).insert(messageCaptor.capture());
|
||||
assertThat(messageCaptor.getValue().getBusinessType()).isEqualTo("ORDER_ARTIST_REVIEW");
|
||||
assertThat(messageCaptor.getValue().getTargetIds()).isEqualTo("2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedDoesNotCreateDuplicateReviewTask() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
|
||||
existingReview.setId(99L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(existingReview);
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedRecoversWhenConcurrentReviewTaskInsertWins() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
|
||||
existingReview.setId(99L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null, existingReview);
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
verify(orderArtistReviewMapper).insert(any(OrderArtistReviewDO.class));
|
||||
verify(orderArtistReviewMapper, never()).updateById(existingReview);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedReusesExistingReviewReminderMessage() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
SystemMessageDO existingMessage = new SystemMessageDO();
|
||||
existingMessage.setId(300L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||
review.setId(1000L);
|
||||
return 1;
|
||||
});
|
||||
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(existingMessage);
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
|
||||
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||
verify(orderArtistReviewMapper).updateById(reviewCaptor.getValue());
|
||||
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(300L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxOrderCompletedRecoversReviewReminderWhenConcurrentInsertWins() {
|
||||
OrderDO order = completedOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
SystemMessageDO existingMessage = new SystemMessageDO();
|
||||
existingMessage.setId(301L);
|
||||
|
||||
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||
review.setId(1001L);
|
||||
return 1;
|
||||
});
|
||||
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null, existingMessage);
|
||||
when(systemMessageMapper.insert(any(SystemMessageDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||
|
||||
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||
|
||||
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
|
||||
verify(systemMessageMapper).insert(messageCaptor.capture());
|
||||
assertThat(messageCaptor.getValue().getIdempotencyKey()).isEqualTo("ORDER_ARTIST_REVIEW:1001:2");
|
||||
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||
verify(orderArtistReviewMapper).updateById(reviewCaptor.capture());
|
||||
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(301L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestArtistChangeLocksOrderItemBeforeCheckingPendingRequest() {
|
||||
OrderDO order = pendingOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO requester = artist(30L);
|
||||
UserDO requestedArtist = artist(31L);
|
||||
product.setBookableArtists("30,31");
|
||||
OrderArtistChangeRequestDTO dto = new OrderArtistChangeRequestDTO();
|
||||
dto.setOrderId(1L);
|
||||
dto.setOrderItemId(10L);
|
||||
dto.setRequestedArtistId(31L);
|
||||
dto.setReason("临时调整");
|
||||
|
||||
when(userMapper.selectById(30L)).thenReturn(requester);
|
||||
when(userMapper.selectById(31L)).thenReturn(requestedArtist);
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(30L, 3L)).thenReturn(true);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||
when(bookableArtistSupport.isBookableServiceUser(requestedArtist)).thenReturn(true);
|
||||
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||
|
||||
service.requestArtistChange(30L, dto);
|
||||
|
||||
ArgumentCaptor<OrderArtistChangeRequestDO> requestCaptor = ArgumentCaptor.forClass(OrderArtistChangeRequestDO.class);
|
||||
verify(orderArtistChangeRequestMapper).insert(requestCaptor.capture());
|
||||
assertThat(requestCaptor.getValue().getPendingKey()).isEqualTo("ORDER_ITEM:10");
|
||||
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderItemMapper).selectByIdForUpdate(10L);
|
||||
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderArtistChangeRequestMapper).selectPendingByOrderItemId(10L);
|
||||
verify(orderItemMapper, never()).selectById(10L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeRejectsAlreadyProcessedRequest() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
request.setStatus("APPROVED");
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
|
||||
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("改派申请已处理");
|
||||
|
||||
verify(orderItemMapper, never()).selectByIdForUpdate(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeUsesPendingConditionalUpdateBeforeAssigningArtist() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
OrderDO order = pendingOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO newArtist = artist(31L);
|
||||
product.setBookableArtists("30,31");
|
||||
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(31L)).thenReturn(newArtist);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
|
||||
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(1);
|
||||
|
||||
service.approveArtistChange(500L, 2L, 0);
|
||||
|
||||
inOrder(orderArtistChangeRequestMapper, orderItemMapper)
|
||||
.verify(orderArtistChangeRequestMapper).approvePending(eq(500L), any(LocalDateTime.class));
|
||||
inOrder(orderArtistChangeRequestMapper, orderItemMapper).verify(orderItemMapper).updateById(item);
|
||||
assertThat(item.getArtistId()).isEqualTo(31L);
|
||||
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeRejectsConcurrentProcessedRequestBeforeAssigningArtist() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
OrderDO order = pendingOrder();
|
||||
OrderItemDO item = orderItem();
|
||||
ProductDO product = product();
|
||||
UserDO newArtist = artist(31L);
|
||||
product.setBookableArtists("30,31");
|
||||
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||
when(productMapper.selectById(20L)).thenReturn(product);
|
||||
when(userMapper.selectById(31L)).thenReturn(newArtist);
|
||||
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
|
||||
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(0);
|
||||
|
||||
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("改派申请已处理");
|
||||
|
||||
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void approveArtistChangeExpiresPendingRequestBeforeProcessing() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
request.setExpireTime(LocalDateTime.now().minusMinutes(1));
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
|
||||
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessageContaining("过期");
|
||||
|
||||
verify(orderArtistChangeRequestMapper).expirePendingById(eq(500L), any(LocalDateTime.class));
|
||||
verify(orderItemMapper, never()).selectByIdForUpdate(any());
|
||||
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectArtistChangeUsesPendingConditionalUpdate() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(1);
|
||||
|
||||
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
|
||||
dto.setRejectReason("客户不方便");
|
||||
|
||||
service.rejectArtistChange(500L, 2L, 0, dto);
|
||||
|
||||
verify(orderArtistChangeRequestMapper).rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class));
|
||||
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectArtistChangeRejectsConcurrentProcessedRequest() {
|
||||
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(0);
|
||||
|
||||
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
|
||||
dto.setRejectReason("客户不方便");
|
||||
|
||||
assertThatThrownBy(() -> service.rejectArtistChange(500L, 2L, 0, dto))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("改派申请已处理");
|
||||
|
||||
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listMyPendingArtistChangeRequestsExpiresDueRequestsFirst() {
|
||||
when(orderArtistChangeRequestMapper.selectPendingByUserId(2L)).thenReturn(List.of());
|
||||
|
||||
assertThat(service.listMyPendingArtistChangeRequests(2L, 0)).isEmpty();
|
||||
|
||||
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
|
||||
verify(orderArtistChangeRequestMapper).selectPendingByUserId(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitArtistReviewRequiresHalfPointRating() {
|
||||
OrderArtistReviewDO review = pendingReview();
|
||||
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
|
||||
|
||||
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
|
||||
dto.setRating(new BigDecimal("4.25"));
|
||||
|
||||
assertThatThrownBy(() -> service.submitArtistReview(100L, 2L, dto))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("评分必须按0.5分递增");
|
||||
|
||||
verify(orderArtistReviewMapper, never()).updateById(any(OrderArtistReviewDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitArtistReviewAcceptsValidRatingAndRefreshesArtistRating() {
|
||||
OrderArtistReviewDO review = pendingReview();
|
||||
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
|
||||
artistInfo.setId(200L);
|
||||
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
|
||||
when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(30L)).thenReturn(new BigDecimal("4.75"));
|
||||
when(nailArtistInfoMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(artistInfo);
|
||||
|
||||
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
|
||||
dto.setRating(new BigDecimal("4.5"));
|
||||
dto.setContent("服务很细致");
|
||||
|
||||
assertThat(service.submitArtistReview(100L, 2L, dto).getRatingScore()).isEqualByComparingTo("4.5");
|
||||
|
||||
verify(orderArtistReviewMapper).updateById(review);
|
||||
verify(nailArtistInfoMapper).updateById(artistInfo);
|
||||
assertThat(artistInfo.getRating()).isEqualByComparingTo("4.8");
|
||||
}
|
||||
|
||||
private OrderDO pendingOrder() {
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(1L);
|
||||
order.setUserId(2L);
|
||||
order.setShopId(3L);
|
||||
order.setStatus(1);
|
||||
order.setIsDelete(0);
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderDO completedOrder() {
|
||||
OrderDO order = pendingOrder();
|
||||
order.setStatus(2);
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderItemDO orderItem() {
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(10L);
|
||||
item.setOrderId(1L);
|
||||
item.setProductId(20L);
|
||||
item.setArtistId(30L);
|
||||
item.setQuantity(1);
|
||||
item.setIsDelete(0);
|
||||
return item;
|
||||
}
|
||||
|
||||
private ProductDO product() {
|
||||
ProductDO product = new ProductDO();
|
||||
product.setId(20L);
|
||||
product.setTitle("凝胶美甲");
|
||||
product.setIsDelete(0);
|
||||
return product;
|
||||
}
|
||||
|
||||
private UserDO artist(Long id) {
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(id);
|
||||
artist.setType(3);
|
||||
artist.setStatus(1);
|
||||
artist.setIsDelete(0);
|
||||
artist.setNickname("美甲师" + id);
|
||||
return artist;
|
||||
}
|
||||
|
||||
private OrderArtistReviewDO pendingReview() {
|
||||
OrderArtistReviewDO review = new OrderArtistReviewDO();
|
||||
review.setId(100L);
|
||||
review.setOrderId(1L);
|
||||
review.setOrderItemId(10L);
|
||||
review.setProductId(20L);
|
||||
review.setCustomerId(2L);
|
||||
review.setArtistId(30L);
|
||||
review.setStatus(0);
|
||||
review.setIsDelete(0);
|
||||
return review;
|
||||
}
|
||||
|
||||
private OrderArtistChangeRequestDO pendingChangeRequest() {
|
||||
OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO();
|
||||
request.setId(500L);
|
||||
request.setOrderId(1L);
|
||||
request.setOrderItemId(10L);
|
||||
request.setProductId(20L);
|
||||
request.setShopId(3L);
|
||||
request.setCustomerId(2L);
|
||||
request.setFromArtistId(30L);
|
||||
request.setToArtistId(31L);
|
||||
request.setRequesterId(30L);
|
||||
request.setStatus("PENDING");
|
||||
request.setExpireTime(LocalDateTime.now().plusDays(1));
|
||||
request.setIsDelete(0);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.xiaowang.yuminailcore.entity.PermissionDO;
|
||||
import com.xiaowang.yuminailcore.entity.ShopRolePermissionDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserPermissionDO;
|
||||
import com.xiaowang.yuminailcore.entity.UserShopRoleDO;
|
||||
import com.xiaowang.yuminailcore.mapper.PermissionMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopRolePermissionMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserPermissionMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserShopRoleMapper;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class PermissionServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private PermissionMapper permissionMapper;
|
||||
|
||||
@Mock
|
||||
private UserPermissionMapper userPermissionMapper;
|
||||
|
||||
@Mock
|
||||
private ShopRolePermissionMapper shopRolePermissionMapper;
|
||||
|
||||
@Mock
|
||||
private UserShopRoleMapper userShopRoleMapper;
|
||||
|
||||
@Mock
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
private PermissionServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new PermissionServiceImpl(
|
||||
permissionMapper,
|
||||
userPermissionMapper,
|
||||
shopRolePermissionMapper,
|
||||
userShopRoleMapper,
|
||||
userMapper,
|
||||
userShopBindingSupport
|
||||
);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeShopRoleRestrictsWritePermissionFromDefaultUserPermissions() {
|
||||
long userId = 10L;
|
||||
long productCreateId = 101L;
|
||||
long productViewId = 102L;
|
||||
long roleId = 201L;
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(2);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
UserPermissionDO defaultProductCreate = new UserPermissionDO();
|
||||
defaultProductCreate.setUserId(userId);
|
||||
defaultProductCreate.setPermissionId(productCreateId);
|
||||
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
|
||||
|
||||
PermissionDO productCreate = permission(productCreateId, "product:create");
|
||||
PermissionDO productView = permission(productViewId, "product:view");
|
||||
when(permissionMapper.selectOne(any()))
|
||||
.thenReturn(productCreate)
|
||||
.thenReturn(productView);
|
||||
|
||||
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||
roleBinding.setUserId(userId);
|
||||
roleBinding.setRoleId(roleId);
|
||||
roleBinding.setStatus(1);
|
||||
roleBinding.setIsDelete(0);
|
||||
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
|
||||
|
||||
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(productViewId);
|
||||
rolePermission.setIsDelete(0);
|
||||
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
|
||||
|
||||
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||
assertThat(service.hasPermission(userId, "product:view")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listUserPermissionsUsesActiveShopRoleAsVisiblePermissions() {
|
||||
long userId = 10L;
|
||||
long productCreateId = 101L;
|
||||
long productViewId = 102L;
|
||||
long roleId = 201L;
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(2);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
UserPermissionDO defaultProductCreate = new UserPermissionDO();
|
||||
defaultProductCreate.setUserId(userId);
|
||||
defaultProductCreate.setPermissionId(productCreateId);
|
||||
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
|
||||
|
||||
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||
roleBinding.setUserId(userId);
|
||||
roleBinding.setRoleId(roleId);
|
||||
roleBinding.setStatus(1);
|
||||
roleBinding.setIsDelete(0);
|
||||
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
|
||||
|
||||
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(productViewId);
|
||||
rolePermission.setIsDelete(0);
|
||||
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
|
||||
|
||||
when(permissionMapper.selectList(any())).thenReturn(List.of(permission(productViewId, "product:view")));
|
||||
|
||||
List<PermissionVO> permissions = service.listUserPermissions(userId);
|
||||
|
||||
assertThat(permissions)
|
||||
.extracting(PermissionVO::getPermissionCode)
|
||||
.containsExactly("product:view");
|
||||
verify(shopRolePermissionMapper).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleDirectPermissionsCannotExceedUserTypeDefaultPermissions() {
|
||||
long userId = 30L;
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(3);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||
|
||||
verifyNoInteractions(userPermissionMapper);
|
||||
verifyNoInteractions(userShopRoleMapper);
|
||||
verifyNoInteractions(shopRolePermissionMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeShopRolesAreScopedToCurrentShop() {
|
||||
long userId = 10L;
|
||||
long currentShopId = 301L;
|
||||
long otherShopId = 302L;
|
||||
long currentShopRoleId = 401L;
|
||||
long otherShopRoleId = 402L;
|
||||
long productCreateId = 101L;
|
||||
long productViewId = 102L;
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
|
||||
UserDO user = new UserDO();
|
||||
user.setId(userId);
|
||||
user.setType(2);
|
||||
user.setIsDelete(0);
|
||||
when(userMapper.selectById(userId)).thenReturn(user);
|
||||
|
||||
UserShopRoleDO currentShopRole = roleBinding(userId, currentShopId, currentShopRoleId);
|
||||
UserShopRoleDO otherShopRole = roleBinding(userId, otherShopId, otherShopRoleId);
|
||||
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(currentShopRole, otherShopRole));
|
||||
|
||||
ShopRolePermissionDO currentShopPermission = rolePermission(currentShopRoleId, productViewId);
|
||||
ShopRolePermissionDO otherShopPermission = rolePermission(otherShopRoleId, productCreateId);
|
||||
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(currentShopPermission, otherShopPermission));
|
||||
|
||||
when(permissionMapper.selectOne(any()))
|
||||
.thenReturn(permission(productCreateId, "product:create"))
|
||||
.thenReturn(permission(productViewId, "product:view"));
|
||||
|
||||
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||
assertThat(service.hasPermission(userId, "product:view")).isTrue();
|
||||
}
|
||||
|
||||
private UserShopRoleDO roleBinding(long userId, long shopId, long roleId) {
|
||||
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||
roleBinding.setUserId(userId);
|
||||
roleBinding.setShopId(shopId);
|
||||
roleBinding.setRoleId(roleId);
|
||||
roleBinding.setStatus(1);
|
||||
roleBinding.setIsDelete(0);
|
||||
return roleBinding;
|
||||
}
|
||||
|
||||
private ShopRolePermissionDO rolePermission(long roleId, long permissionId) {
|
||||
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||
rolePermission.setRoleId(roleId);
|
||||
rolePermission.setPermissionId(permissionId);
|
||||
rolePermission.setIsDelete(0);
|
||||
return rolePermission;
|
||||
}
|
||||
|
||||
private PermissionDO permission(long id, String code) {
|
||||
PermissionDO permission = new PermissionDO();
|
||||
permission.setId(id);
|
||||
permission.setPermissionCode(code);
|
||||
permission.setPermissionName(code);
|
||||
permission.setPermissionGroup("test");
|
||||
permission.setIsDelete(0);
|
||||
return permission;
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO;
|
||||
import com.xiaowang.yuminailcore.mapper.SecurityAuditLogMapper;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SecurityAuditLogServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private SecurityAuditLogMapper auditLogMapper;
|
||||
|
||||
private SecurityAuditLogServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new SecurityAuditLogServiceImpl(auditLogMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordTruncatesOversizedFieldsAndCapturesForwardedIp() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("X-Forwarded-For", "10.0.0.1, 10.0.0.2");
|
||||
|
||||
service.record(1L, "a".repeat(100), "b".repeat(100), "SUCCESS", "c".repeat(600), request);
|
||||
|
||||
ArgumentCaptor<SecurityAuditLogDO> captor = ArgumentCaptor.forClass(SecurityAuditLogDO.class);
|
||||
verify(auditLogMapper).insert(captor.capture());
|
||||
SecurityAuditLogDO log = captor.getValue();
|
||||
assertThat(log.getAccount()).hasSize(80);
|
||||
assertThat(log.getAction()).hasSize(80);
|
||||
assertThat(log.getReason()).hasSize(500);
|
||||
assertThat(log.getIpAddress()).isEqualTo("10.0.0.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void pageLogsFiltersAndMapsPagedResult() {
|
||||
SecurityAuditLogDO log = new SecurityAuditLogDO();
|
||||
log.setId(100L);
|
||||
log.setUserId(1L);
|
||||
log.setAccount("admin");
|
||||
log.setAction("ORDER_PROCESS");
|
||||
log.setResult("SUCCESS");
|
||||
log.setReason("orderId=1");
|
||||
log.setIpAddress("127.0.0.1");
|
||||
log.setDeviceId("device-1");
|
||||
log.setOperateTime(LocalDateTime.now());
|
||||
Page<SecurityAuditLogDO> page = new Page<>(2, 5);
|
||||
page.setRecords(List.of(log));
|
||||
page.setTotal(11);
|
||||
when(auditLogMapper.selectPage(any(Page.class), any(LambdaQueryWrapper.class))).thenReturn(page);
|
||||
|
||||
PageResultVO<SecurityAuditLogVO> result = service.pageLogs("admin", "ORDER_PROCESS", "SUCCESS",
|
||||
LocalDateTime.now().minusDays(1), LocalDateTime.now(), 2, 5);
|
||||
|
||||
assertThat(result.getTotal()).isEqualTo(11);
|
||||
assertThat(result.getPage()).isEqualTo(2);
|
||||
assertThat(result.getSize()).isEqualTo(5);
|
||||
assertThat(result.getList()).hasSize(1);
|
||||
assertThat(result.getList().get(0).getAction()).isEqualTo("ORDER_PROCESS");
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||
import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||
import com.xiaowang.yuminailcore.mapper.CommentMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.CouponMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.MapService;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ShopServiceImplTest {
|
||||
@Mock
|
||||
private ShopMapper shopMapper;
|
||||
@Mock
|
||||
private CouponService couponService;
|
||||
@Mock
|
||||
private CouponMapper couponMapper;
|
||||
@Mock
|
||||
private ProductMapper productMapper;
|
||||
@Mock
|
||||
private TagMapper tagMapper;
|
||||
@Mock
|
||||
private CommentMapper commentMapper;
|
||||
@Mock
|
||||
private UserCouponMapper userCouponMapper;
|
||||
@Mock
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
@Mock
|
||||
private MultiLevelCacheService multiLevelCacheService;
|
||||
@Mock
|
||||
private AppCacheProperties appCacheProperties;
|
||||
@Mock
|
||||
private MapService mapService;
|
||||
|
||||
private ShopServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
service = new ShopServiceImpl(
|
||||
shopMapper,
|
||||
couponService,
|
||||
couponMapper,
|
||||
productMapper,
|
||||
tagMapper,
|
||||
commentMapper,
|
||||
userCouponMapper,
|
||||
userShopBindingSupport,
|
||||
multiLevelCacheService,
|
||||
appCacheProperties,
|
||||
mapService
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteShopRejectsBusinessDeleteWithoutCascadeSoftDelete() {
|
||||
assertThatThrownBy(() -> service.deleteShop(1L))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("店铺删除已停用,请使用停用封存");
|
||||
|
||||
verifyNoInteractions(
|
||||
shopMapper,
|
||||
couponMapper,
|
||||
productMapper,
|
||||
tagMapper,
|
||||
commentMapper,
|
||||
userCouponMapper,
|
||||
userShopBindingSupport
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateShopRejectsDisabledArchivedShop() {
|
||||
ShopDO disabledShop = new ShopDO();
|
||||
disabledShop.setId(1L);
|
||||
disabledShop.setStatus(0);
|
||||
disabledShop.setIsDelete(0);
|
||||
when(shopMapper.selectById(1L)).thenReturn(disabledShop);
|
||||
|
||||
assertThatThrownBy(() -> service.updateShop(1L, new ShopDTO()))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("停用店铺已封存,仅允许重新启用");
|
||||
|
||||
verify(shopMapper, never()).updateById(disabledShop);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class OrderStateMachineTest {
|
||||
|
||||
@Test
|
||||
void allowsPendingOrderToCompleteOrCancel() {
|
||||
assertThat(OrderStateMachine.isAllowedTransition(1, 2)).isTrue();
|
||||
assertThat(OrderStateMachine.isAllowedTransition(1, 3)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidOrderTransition() {
|
||||
assertThat(OrderStateMachine.isAllowedTransition(2, 3)).isFalse();
|
||||
assertThatThrownBy(() -> OrderStateMachine.requireAllowedTransition(2, 3))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("订单状态不允许处理");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnknownTargetStatus() {
|
||||
assertThatThrownBy(() -> OrderStatus.requireKnown(9))
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("无效的订单状态");
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -18,7 +18,7 @@ class PermissionCatalogTest {
|
||||
@Test
|
||||
void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() {
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
|
||||
.contains("messagehub:config:manage", "legal_agreement:manage");
|
||||
.contains("messagehub:config:manage", "security:audit:view", "legal_agreement:manage");
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:create")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:balance:manage")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue();
|
||||
@@ -26,6 +26,7 @@ class PermissionCatalogTest {
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("messagehub:config:manage")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("security:audit:view")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("legal_agreement:manage")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:view")).isTrue();
|
||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue();
|
||||
@@ -42,6 +43,23 @@ class PermissionCatalogTest {
|
||||
.containsAll(PermissionCatalog.getDefaultPermissionCodes(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nailArtistDefaultPermissionsAreWorkbenchOnly() {
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(3))
|
||||
.contains("product:view", "tag:view", "coupon:view", "order:view", "order:process", "order:artist-change")
|
||||
.doesNotContain("product:create", "product:edit", "product:delete",
|
||||
"tag:create", "tag:edit", "tag:delete",
|
||||
"user:create", "user:edit", "coupon:create", "coupon:assign");
|
||||
}
|
||||
|
||||
@Test
|
||||
void artistChangePermissionIsGrantedToProductionRoles() {
|
||||
assertChinesePermission("order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请");
|
||||
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(2)).contains("order:artist-change");
|
||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(3)).contains("order:artist-change");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyManagedDefaultPermissionUsesChineseDisplayText() {
|
||||
PermissionCatalog.getManagedDefinitions().forEach(definition -> {
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.xiaowang.yuminailcore.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class YumiNailSqlSchemaTest {
|
||||
|
||||
@Test
|
||||
void balanceTableDefinesUpdateTimeColumnBeforeSeedMigrations() throws Exception {
|
||||
String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql"));
|
||||
|
||||
assertThat(sql).containsPattern("(?is)create table t_balance\\s*\\([^;]*\\bupdate_time\\s+datetime");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_balance', 'update_time'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orderArtistReviewAndChangeSchemasAreSeeded() throws Exception {
|
||||
String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql"));
|
||||
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_review");
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_change_request");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_type'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_id'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'action_path'");
|
||||
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key'");
|
||||
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency'");
|
||||
assertThat(sql).contains("pending_key");
|
||||
assertThat(sql).contains("EXPIRED");
|
||||
assertThat(sql).contains("idx_order_artist_change_expire");
|
||||
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key'");
|
||||
assertThat(sql).contains("'order:artist-change'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void businessEventOutboxAndSecurityAuditPermissionAreSeeded() throws Exception {
|
||||
String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql"));
|
||||
|
||||
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_business_event_outbox");
|
||||
assertThat(sql).contains("uk_business_event_outbox_event_key");
|
||||
assertThat(sql).contains("idx_business_event_outbox_due");
|
||||
assertThat(sql).contains("'security:audit:view'");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user