功能:完善多店铺登录与首次部署SQL

This commit is contained in:
xiaowang
2026-03-26 10:28:28 +08:00
parent 5601428087
commit 764bfadb51
79 changed files with 6524 additions and 2603 deletions
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.config;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.support.RequestShopContext;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@@ -16,6 +18,7 @@ public class AuthInterceptor implements HandlerInterceptor {
private final JwtUtil jwtUtil;
private final UserMapper userMapper;
private final UserShopBindingSupport userShopBindingSupport;
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_PREFIX = "Bearer ";
@@ -49,6 +52,7 @@ public class AuthInterceptor implements HandlerInterceptor {
Long userId = jwtUtil.getUserIdFromToken(token);
String account = jwtUtil.getAccountFromToken(token);
Long currentShopId = jwtUtil.getShopIdFromToken(token);
UserDO currentUser = userMapper.selectById(userId);
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
@@ -60,14 +64,30 @@ public class AuthInterceptor implements HandlerInterceptor {
return false;
}
if (isAdminPath(path) && (currentUser.getType() == null || currentUser.getType() < 2)) {
boolean adminPath = isAdminPath(path);
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
return false;
}
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
userId,
currentShopId,
adminPath,
currentUser.getType()
);
if (!canAccessShop) {
String message = currentShopId == null || currentShopId <= 0
? "当前登录未选择可用店铺,请重新登录"
: "当前登录店铺已停用或账号已失去该店铺访问权限";
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message);
return false;
}
request.setAttribute("userId", userId);
request.setAttribute("account", account);
request.setAttribute("userType", currentUser.getType());
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
return true;
}
@@ -23,8 +23,15 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/user/send-verification-code",
"/user/phone-login",
"/user/reset-password-by-phone",
"/product/get/**",
"/product/list/**",
"/shop/get/**",
"/shop/list/public",
"/shop/list/simple",
"/tag/list/all",
"/file/get-signed-url/**",
"/admin/auth/login",
"/admin/auth/login-shops/**",
"/admin/auth/refresh",
"/error",
"/health/**"
@@ -3,11 +3,15 @@ package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.LoginRequestDTO;
import com.xiaowang.yuminailcore.dto.RefreshTokenRequestDTO;
import com.xiaowang.yuminailcore.dto.SwitchShopRequestDTO;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/admin/auth")
@RequiredArgsConstructor
@@ -21,6 +25,17 @@ public class AdminAuthController {
return Result.success(loginResponseVO);
}
@GetMapping("/login-shops/{account}")
public Result<LoginShopSelectionVO> getLoginShops(@PathVariable String account) {
return Result.success(userService.getAdminLoginShopSelection(account));
}
@PostMapping("/switch-shop")
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId()));
}
@PostMapping("/logout")
public Result<Boolean> logout() {
return Result.success(true);
@@ -135,7 +135,7 @@ public class AdminCouponController {
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权给其他店铺用户发放优惠券");
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
return Result.success(success);
@@ -158,7 +158,7 @@ public class AdminCouponController {
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权给其他店铺用户发放优惠券");
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
}
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
@@ -6,6 +6,7 @@ import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -24,6 +25,9 @@ public class AdminNailArtistController {
@Autowired
private UserService userService;
@Autowired
private AdminScopeHelper adminScopeHelper;
/**
* 获取所有美甲师信息
@@ -32,8 +36,7 @@ public class AdminNailArtistController {
@RequirePermission("nail_artist:view")
@GetMapping("/list")
public Result<List<NailArtistInfoDTO>> getAllNailArtists(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
UserDO currentUser = userService.getById(userId);
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (currentUser == null) {
return Result.error("用户信息不存在");
@@ -61,7 +64,7 @@ public class AdminNailArtistController {
@GetMapping("/get/{userId}")
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId, HttpServletRequest request) {
Long currentUserId = (Long) request.getAttribute("userId");
UserDO currentUser = userService.getById(currentUserId);
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (currentUser == null) {
return Result.error("用户信息不存在");
@@ -70,11 +73,7 @@ public class AdminNailArtistController {
// 检查权限:管理员可以查看所有,店长只能查看本店铺的,美甲师只能查看自己的
if (currentUser.getType() != 4) { // 不是管理员
if (currentUser.getType() == 2) { // 店长
// 检查美甲师是否属于当前店长的店铺
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
if (nailArtistInfoDTO == null || !nailArtistInfoDTO.getShopId().equals(currentUser.getShopId())) {
return Result.error("无权限访问");
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权限访问");
} else if (currentUser.getType() == 3) { // 美甲师
// 只能查看自己的信息
if (!currentUser.getId().equals(userId)) {
@@ -97,7 +96,7 @@ public class AdminNailArtistController {
@PostMapping("/save")
public Result<NailArtistInfoDTO> saveNailArtistInfo(@RequestBody NailArtistInfoDTO nailArtistInfoDTO, HttpServletRequest request) {
Long currentUserId = (Long) request.getAttribute("userId");
UserDO currentUser = userService.getById(currentUserId);
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (currentUser == null) {
return Result.error("用户信息不存在");
@@ -106,11 +105,7 @@ public class AdminNailArtistController {
// 检查权限:管理员可以编辑所有,店长只能编辑本店铺的,美甲师只能编辑自己的
if (currentUser.getType() != 4) { // 不是管理员
if (currentUser.getType() == 2) { // 店长
// 检查美甲师是否属于当前店长的店铺
NailArtistInfoDTO existing = nailArtistInfoService.getByUserId(nailArtistInfoDTO.getUserId());
if (existing == null || !existing.getShopId().equals(currentUser.getShopId())) {
return Result.error("无权限编辑");
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, nailArtistInfoDTO.getUserId(), "无权限编辑");
} else if (currentUser.getType() == 3) { // 美甲师
// 只能编辑自己的信息
if (!currentUser.getId().equals(nailArtistInfoDTO.getUserId())) {
@@ -81,7 +81,7 @@ public class AdminPermissionController {
if (targetUser == null) {
throw new RuntimeException("目标用户不存在");
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权查看其他店铺用户权限");
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限");
}
List<PermissionVO> permissionVOs = permissionService.listUserPermissions(userId);
return Result.success(permissionVOs);
@@ -100,6 +100,10 @@ public class AdminPermissionController {
HttpServletRequest request,
@PathVariable Long userId,
@RequestBody UserPermissionDTO userPermissionDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户分配权限");
}
Long currentUserId = (Long) request.getAttribute("userId");
userPermissionDTO.setUserId(userId);
boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId);
@@ -8,6 +8,7 @@ import com.xiaowang.yuminailcore.service.ShopService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.ShopVO;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@@ -68,13 +69,22 @@ public class AdminShopController {
return Result.success(success);
}
@PutMapping("/status/{id}")
@RequirePermission("shop:edit")
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);
}
@GetMapping("/list/all")
@RequirePermission("shop:view")
public Result<List<ShopVO>> listAllShops(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<ShopVO> shops;
if (adminScopeHelper.isPlatformAdmin(currentUser)) {
shops = shopService.listAllShops();
shops = shopService.listAllShopsForAdmin();
} else {
ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser));
shops = currentShop == null ? List.of() : List.of(currentShop);
@@ -90,4 +100,9 @@ public class AdminShopController {
ShopVO shop = shopService.getShopById(id);
return Result.success(shop);
}
@Data
public static class StatusRequest {
private Integer status;
}
}
@@ -52,7 +52,9 @@ public class AdminUserController {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
userDTO.setShopId(adminScopeHelper.getManagedShopId(currentUser));
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
userDTO.setShopId(managedShopId);
userDTO.setShopIds(List.of(managedShopId));
}
Long id = userService.createUser(userDTO);
return Result.success(id);
@@ -71,7 +73,8 @@ public class AdminUserController {
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
}
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
userDTO.setShopId(adminScopeHelper.getManagedShopId(currentUser));
userDTO.setShopId(null);
userDTO.setShopIds(null);
}
boolean success = userService.updateUser(id, userDTO);
return Result.success(success);
@@ -85,8 +88,8 @@ public class AdminUserController {
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权变更其他店铺用户状态");
boolean success = userService.updateUserStatus(id, request.getStatus());
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权变更其他店铺用户状态");
boolean success = userService.updateUserStatusInShop(id, request.getStatus(), currentUser.getShopId());
return Result.success(success);
}
@@ -98,7 +101,7 @@ public class AdminUserController {
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权重置其他店铺用户密码");
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码");
Long currentUserId = (Long) request.getAttribute("userId");
boolean success = userService.resetPassword(userId, currentUserId);
return Result.success(success);
@@ -112,8 +115,8 @@ public class AdminUserController {
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权删除其他店铺用户");
boolean success = userService.deleteUser(id);
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权删除其他店铺用户");
boolean success = userService.deleteUserInShop(id, currentUser.getShopId());
return Result.success(success);
}
@@ -207,7 +210,7 @@ public class AdminUserController {
if (shopId != null) {
final Long resolvedShopId = shopId;
artists = artists.stream()
.filter(artist -> resolvedShopId.equals(artist.getShopId()))
.filter(artist -> artist.getShopIds() != null && artist.getShopIds().contains(resolvedShopId))
.collect(Collectors.toList());
}
return Result.success(artists);
@@ -218,7 +221,7 @@ public class AdminUserController {
if (targetUser == null) {
throw new RuntimeException("目标用户不存在");
}
adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), message);
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message);
return targetUser;
}
@@ -3,13 +3,18 @@ package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.CouponDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.CouponVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.UserCouponVO;
import com.xiaowang.yuminailcore.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@@ -21,13 +26,17 @@ import java.util.List;
public class CouponController {
private final CouponService couponService;
private final UserService userService;
private final AdminScopeHelper adminScopeHelper;
/**
* 创建优惠券
*/
@PostMapping("/create")
@RequirePermission("coupon:create")
public Result<Long> createCoupon(@RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
Long couponId = couponService.createCoupon(couponDTO, shopId);
return Result.success(couponId);
}
@@ -37,7 +46,15 @@ public class CouponController {
*/
@PutMapping("/update/{id}")
@RequirePermission("coupon:edit")
public Result<Boolean> updateCoupon(@PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵浼樻儬鍒?");
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
return Result.success(success);
}
@@ -47,7 +64,14 @@ public class CouponController {
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("coupon:delete")
public Result<Boolean> deleteCoupon(@PathVariable Long id, @RequestParam(required = false) Long shopId) {
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵浼樻儬鍒?");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.deleteCoupon(id, shopId);
return Result.success(success);
}
@@ -57,8 +81,12 @@ public class CouponController {
*/
@GetMapping("/detail/{id}")
@RequirePermission("coupon:view")
public Result<CouponVO> getCouponById(@PathVariable Long id) {
public Result<CouponVO> getCouponById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(id);
if (couponVO != null) {
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵浼樻儬鍒?");
}
return Result.success(couponVO);
}
@@ -67,7 +95,9 @@ public class CouponController {
*/
@GetMapping("/list")
@RequirePermission("coupon:view")
public Result<PageResultVO<CouponVO>> listCoupons(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
public Result<PageResultVO<CouponVO>> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
return Result.success(pageResult);
}
@@ -77,7 +107,19 @@ public class CouponController {
*/
@PostMapping("/assign")
@RequirePermission("coupon:assign")
public Result<Boolean> assignCouponToUser(@RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(couponId);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?");
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜");
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
return Result.success(success);
}
@@ -119,7 +161,21 @@ public class CouponController {
*/
@PostMapping("/distribute")
@RequirePermission("coupon:assign")
public Result<Boolean> distributeCoupon(@RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
CouponVO couponVO = couponService.getCouponById(couponId);
if (couponVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?");
for (Long userId : userIds) {
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
return Result.success(false);
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜");
}
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
return Result.success(success);
}
@@ -15,6 +15,7 @@ import com.xiaowang.yuminailcore.mapper.ProductMapper;
import com.xiaowang.yuminailcore.mapper.ShopMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.DashboardStatsVO;
import com.xiaowang.yuminailcore.vo.HotProductVO;
import com.xiaowang.yuminailcore.vo.RecentActivityVO;
@@ -42,6 +43,7 @@ public class DashboardController {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final AdminScopeHelper adminScopeHelper;
private final UserShopBindingSupport userShopBindingSupport;
@GetMapping("/stats")
@RequirePermission("dashboard:view")
@@ -59,14 +61,14 @@ public class DashboardController {
stats.setTotalShops(shopMapper.selectCount(null));
stats.setTodayOrders(getTodayOrders(null));
} else { // 店长或美甲师
Long shopId = currentUser.getShopId();
if (shopId != null) {
shopIdScope = shopId;
// 只显示当前店铺的数据
stats.setTotalUsers(userMapper.selectCount(new LambdaQueryWrapper<UserDO>().eq(UserDO::getShopId, shopId)));
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
Long shopId = currentUser.getShopId();
if (shopId != null) {
shopIdScope = shopId;
// 只显示当前店铺的数据
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
} else {
// 没有店铺ID的情况
stats.setTotalUsers(0L);
@@ -162,7 +164,12 @@ public class DashboardController {
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
userWrapper.eq(UserDO::getShopId, shopId);
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
userWrapper.eq(UserDO::getId, -1L);
} else {
userWrapper.in(UserDO::getId, userIds);
}
}
userWrapper.orderByDesc(UserDO::getCreateTime)
.last("LIMIT 3");
@@ -4,7 +4,10 @@ import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.PermissionDTO;
import com.xiaowang.yuminailcore.dto.UserPermissionDTO;
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.vo.PermissionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@@ -25,6 +28,8 @@ import java.util.List;
public class PermissionController {
private final PermissionService permissionService;
private final UserService userService;
private final AdminScopeHelper adminScopeHelper;
/**
* 创建权限
@@ -34,7 +39,9 @@ public class PermissionController {
*/
@PostMapping("/create")
@RequirePermission("permission:create")
public Result<Long> createPermission(@RequestBody PermissionDTO permissionDTO) {
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);
}
@@ -48,7 +55,9 @@ public class PermissionController {
*/
@PutMapping("/update/{id}")
@RequirePermission("permission:edit")
public Result<Boolean> updatePermission(@PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
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);
}
@@ -61,7 +70,9 @@ public class PermissionController {
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("permission:delete")
public Result<Boolean> deletePermission(@PathVariable Long id) {
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);
}
@@ -112,7 +123,15 @@ public class PermissionController {
*/
@GetMapping("/list/user/{userId}")
@RequirePermission("permission:view")
public Result<List<PermissionVO>> listUserPermissions(@PathVariable Long userId) {
public Result<List<PermissionVO>> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
UserDO targetUser = userService.getById(userId);
if (targetUser == null) {
throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?");
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛鏉冮檺");
}
List<PermissionVO> permissionVOs = permissionService.listUserPermissions(userId);
return Result.success(permissionVOs);
}
@@ -126,6 +145,14 @@ public class PermissionController {
@PostMapping("/assign")
@RequirePermission("permission:assign")
public Result<Boolean> assignPermissions(HttpServletRequest request, @RequestBody UserPermissionDTO userPermissionDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
UserDO targetUser = userService.getById(userPermissionDTO.getUserId());
if (targetUser == null) {
throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?");
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰垎閰嶆潈闄?");
}
Long userId = (Long) request.getAttribute("userId");
boolean success = permissionService.assignPermissions(userPermissionDTO, userId);
return Result.success(success);
@@ -3,12 +3,15 @@ package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.ProductDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.service.ProductService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.ProductVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@@ -17,24 +20,41 @@ import java.util.List;
public class ProductController {
private final ProductService productService;
private final AdminScopeHelper adminScopeHelper;
@PostMapping("/create")
@RequirePermission("product:create")
public Result<Long> createProduct(@RequestBody ProductDTO productDTO) {
public Result<Long> createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId()));
Long id = productService.createProduct(productDTO);
return Result.success(id);
}
@PutMapping("/update/{id}")
@RequirePermission("product:edit")
public Result<Boolean> updateProduct(@PathVariable Long id, @RequestBody ProductDTO productDTO) {
public Result<Boolean> updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ProductVO productVO = productService.getProductById(id);
if (productVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鍟嗗搧");
Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId();
productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId));
boolean success = productService.updateProduct(id, productDTO);
return Result.success(success);
}
@DeleteMapping("/delete/{id}")
@RequirePermission("product:delete")
public Result<Boolean> deleteProduct(@PathVariable Long id) {
public Result<Boolean> deleteProduct(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ProductVO productVO = productService.getProductById(id);
if (productVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鍟嗗搧");
boolean success = productService.deleteProduct(id);
return Result.success(success);
}
@@ -3,12 +3,16 @@ package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
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.vo.ShopSimpleVO;
import com.xiaowang.yuminailcore.vo.ShopVO;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
@@ -18,28 +22,48 @@ import java.util.stream.Collectors;
public class ShopController {
private final ShopService shopService;
private final AdminScopeHelper adminScopeHelper;
@PostMapping("/create")
@RequirePermission("shop:create")
public Result<Long> createShop(@RequestBody ShopDTO shopDTO) {
public Result<Long> createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垱寤哄簵閾?");
Long id = shopService.createShop(shopDTO);
return Result.success(id);
}
@PutMapping("/update/{id}")
@RequirePermission("shop:edit")
public Result<Boolean> updateShop(@PathVariable Long id, @RequestBody ShopDTO shopDTO) {
public Result<Boolean> updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ShopVO shopVO = shopService.getShopById(id);
if (shopVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵淇℃伅");
boolean success = shopService.updateShop(id, shopDTO);
return Result.success(success);
}
@DeleteMapping("/delete/{id}")
@RequirePermission("shop:delete")
public Result<Boolean> deleteShop(@PathVariable Long id) {
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);
}
@PutMapping("/status/{id}")
@RequirePermission("shop:edit")
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);
}
@GetMapping("/get/{id}")
public Result<ShopVO> getShopById(@PathVariable Long id) {
ShopVO shopVO = shopService.getShopById(id);
@@ -48,8 +72,15 @@ public class ShopController {
@GetMapping("/list/all")
@RequirePermission("shop:view")
public Result<List<ShopVO>> listAllShops() {
List<ShopVO> shopVOs = shopService.listAllShops();
public Result<List<ShopVO>> listAllShops(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<ShopVO> shopVOs;
if (adminScopeHelper.isPlatformAdmin(currentUser)) {
shopVOs = shopService.listAllShopsForAdmin();
} else {
ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser));
shopVOs = currentShop == null ? List.of() : List.of(currentShop);
}
return Result.success(shopVOs);
}
@@ -67,4 +98,14 @@ public class ShopController {
.collect(Collectors.toList());
return Result.success(simpleVOs);
}
@GetMapping("/list/public")
public Result<List<ShopVO>> listPublicShops() {
return Result.success(shopService.listAllShops());
}
@Data
public static class StatusRequest {
private Integer status;
}
}
@@ -3,11 +3,14 @@ package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.TagDTO;
import com.xiaowang.yuminailcore.vo.TagVO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.service.TagService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.TagVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
@@ -23,6 +26,7 @@ import java.util.List;
public class TagController {
private final TagService tagService;
private final AdminScopeHelper adminScopeHelper;
/**
* 创建标签
@@ -32,7 +36,9 @@ public class TagController {
*/
@PostMapping("/create")
@RequirePermission("tag:create")
public Result<Long> createTag(@RequestBody TagDTO tagDTO) {
public Result<Long> createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId()));
Long id = tagService.createTag(tagDTO);
return Result.success(id);
}
@@ -46,7 +52,15 @@ public class TagController {
*/
@PutMapping("/update/{id}")
@RequirePermission("tag:edit")
public Result<Boolean> updateTag(@PathVariable Long id, @RequestBody TagDTO tagDTO) {
public Result<Boolean> updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
TagVO tagVO = tagService.getTagById(id);
if (tagVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鏍囩");
Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId();
tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId));
boolean success = tagService.updateTag(id, tagDTO);
return Result.success(success);
}
@@ -59,7 +73,13 @@ public class TagController {
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("tag:delete")
public Result<Boolean> deleteTag(@PathVariable Long id) {
public Result<Boolean> deleteTag(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
TagVO tagVO = tagService.getTagById(id);
if (tagVO == null) {
return Result.success(false);
}
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鏍囩");
boolean success = tagService.deleteTag(id);
return Result.success(success);
}
@@ -72,8 +92,12 @@ public class TagController {
*/
@GetMapping("/get/{id}")
@RequirePermission("tag:view")
public Result<TagVO> getTagById(@PathVariable Long id) {
public Result<TagVO> getTagById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
TagVO tagVO = tagService.getTagById(id);
if (tagVO != null) {
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩");
}
return Result.success(tagVO);
}
@@ -96,7 +120,9 @@ public class TagController {
*/
@GetMapping("/list/by-shop/{shopId}")
@RequirePermission("tag:view")
public Result<List<TagVO>> listTagsByShopId(@PathVariable Long shopId) {
public Result<List<TagVO>> listTagsByShopId(HttpServletRequest request, @PathVariable Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
List<TagVO> tagVOs = tagService.listTagsByShopId(shopId);
return Result.success(tagVOs);
}
@@ -109,8 +135,12 @@ public class TagController {
*/
@GetMapping("/get/tagName/{tagName}")
@RequirePermission("tag:view")
public Result<TagVO> getTagByTagName(@PathVariable String tagName) {
public Result<TagVO> getTagByTagName(HttpServletRequest request, @PathVariable String tagName) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
TagVO tagVO = tagService.getTagByTagName(tagName);
if (tagVO != null) {
adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩");
}
return Result.success(tagVO);
}
}
@@ -5,6 +5,8 @@ import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.*;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.UserVO;
import com.xiaowang.yuminailcore.service.MinioService;
@@ -18,6 +20,7 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* 系统用户信息表 Controller
@@ -35,16 +38,24 @@ public class UserController {
private final MinioService minioService;
private final VerificationCodeService verificationCodeService;
private final UserMapper userMapper;
private final AdminScopeHelper adminScopeHelper;
/**
* 创建用户
*
* @param userDTO 用户DTO
* @return 用户ID
*/
*/
@PostMapping("/create")
@RequirePermission("user:create")
public Result<Long> createUser(@RequestBody UserDTO userDTO) {
public Result<Long> createUser(HttpServletRequest request, @RequestBody UserDTO userDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
userDTO.setShopId(managedShopId);
userDTO.setShopIds(List.of(managedShopId));
}
Long id = userService.createUser(userDTO);
return Result.success(id);
}
@@ -55,10 +66,19 @@ public class UserController {
* @param id 用户ID
* @param userDTO 用户DTO
* @return 是否更新成功
*/
*/
@PutMapping("/update/{id}")
@RequirePermission("user:edit")
public Result<Boolean> updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
public Result<Boolean> updateUser(HttpServletRequest request, @PathVariable Long id, @RequestBody UserDTO userDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO targetUser = requireAccessibleUser(currentUser, id, "鏃犳潈缂栬緫鍏朵粬搴楅摵鐢ㄦ埛");
if (userDTO.getType() != null) {
adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType());
}
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
userDTO.setShopId(null);
userDTO.setShopIds(null);
}
boolean success = userService.updateUser(id, userDTO);
return Result.success(success);
}
@@ -68,11 +88,15 @@ public class UserController {
*
* @param id 用户ID
* @return 是否删除成功
*/
*/
@DeleteMapping("/delete/{id}")
@RequirePermission("user:delete")
public Result<Boolean> deleteUser(@PathVariable Long id) {
boolean success = userService.deleteUser(id);
public Result<Boolean> deleteUser(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
requireAccessibleUser(currentUser, id, "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鐢ㄦ埛");
boolean success = adminScopeHelper.isPlatformAdmin(currentUser)
? userService.deleteUserInShop(id, currentUser.getShopId())
: userService.deleteUserInShop(id, adminScopeHelper.getManagedShopId(currentUser));
return Result.success(success);
}
@@ -81,11 +105,12 @@ public class UserController {
*
* @param id 用户ID
* @return 用户VO
*/
*/
@GetMapping("/get/{id}")
@RequirePermission("user:view")
public Result<UserVO> getUserById(@PathVariable Long id) {
UserVO userVO = userService.getUserById(id);
public Result<UserVO> getUserById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO userVO = requireAccessibleUser(currentUser, id, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛");
return Result.success(userVO);
}
@@ -93,11 +118,14 @@ public class UserController {
* 查询所有用户
*
* @return 用户VO列表
*/
*/
@GetMapping("/list/all")
@RequirePermission("user:view")
public Result<List<UserVO>> listAllUsers() {
List<UserVO> userVOs = userService.listAllUsers();
public Result<List<UserVO>> listAllUsers(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<UserVO> userVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? userService.listAllUsers()
: userService.listUsersByShopId(adminScopeHelper.getManagedShopId(currentUser));
return Result.success(userVOs);
}
@@ -106,10 +134,12 @@ public class UserController {
*
* @param shopId 店铺ID
* @return 用户VO列表
*/
*/
@GetMapping("/list/shop/{shopId}")
@RequirePermission("user:view")
public Result<List<UserVO>> listUsersByShopId(@PathVariable Long shopId) {
public Result<List<UserVO>> listUsersByShopId(HttpServletRequest request, @PathVariable Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
List<UserVO> userVOs = userService.listUsersByShopId(shopId);
return Result.success(userVOs);
}
@@ -119,10 +149,16 @@ public class UserController {
*
* @param type 用户类型
* @return 用户VO列表
*/
*/
@GetMapping("/list/type/{type}")
public Result<List<UserVO>> listUsersByType(@PathVariable Integer type) {
List<UserVO> userVOs = userService.listUsersByType(type);
if (!Integer.valueOf(3).equals(type)) {
throw new RuntimeException("仅支持查询可预约的美甲师列表");
}
List<UserVO> userVOs = userService.listUsersByType(type).stream()
.filter(user -> Integer.valueOf(1).equals(user.getStatus()))
.map(this::sanitizePublicArtist)
.collect(Collectors.toList());
return Result.success(userVOs);
}
@@ -131,11 +167,15 @@ public class UserController {
*
* @param account 账号
* @return 用户VO
*/
*/
@GetMapping("/get/account/{account}")
@RequirePermission("user:view")
public Result<UserVO> getUserByAccount(@PathVariable String account) {
public Result<UserVO> getUserByAccount(HttpServletRequest request, @PathVariable String account) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
UserVO userVO = userService.getUserByAccount(account);
if (userVO != null) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛");
}
return Result.success(userVO);
}
@@ -166,6 +206,16 @@ public class UserController {
return Result.success(new LoginAccountAvailabilityVO(exists, nickname, message));
}
@GetMapping("/check/login-shops/account/{account}")
public Result<LoginShopSelectionVO> getLoginShopsByAccount(@PathVariable String account) {
return Result.success(userService.getLoginShopSelectionByAccount(account));
}
@GetMapping("/check/login-shops/phone/{phone}")
public Result<LoginShopSelectionVO> getLoginShopsByPhone(@PathVariable String phone) {
return Result.success(userService.getLoginShopSelectionByPhone(phone));
}
@GetMapping("/check/phone/{phone}")
public Result<AvailabilityVO> checkPhoneAvailability(@PathVariable String phone) {
UserDO userDO = userMapper.selectOne(
@@ -202,6 +252,12 @@ public class UserController {
return Result.success(loginResponseVO);
}
@PostMapping("/switch-shop")
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId()));
}
/**
* 用户注册
*
@@ -348,6 +404,8 @@ public class UserController {
@PostMapping("/reset-password/{userId}")
@RequirePermission("user:reset_password")
public Result<Boolean> resetPassword(HttpServletRequest request, @PathVariable Long userId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
requireAccessibleUser(currentUser, userId, "鏃犳潈閲嶇疆鍏朵粬搴楅摵鐢ㄦ埛瀵嗙爜");
Long currentUserId = (Long) request.getAttribute("userId");
boolean success = userService.resetPassword(userId, currentUserId);
return Result.success(success);
@@ -421,6 +479,31 @@ public class UserController {
return Result.success(success);
}
private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) {
UserVO targetUser = userService.getUserById(userId);
if (targetUser == null) {
throw new RuntimeException("目标用户不存在");
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message);
return targetUser;
}
private UserVO sanitizePublicArtist(UserVO userVO) {
UserVO sanitized = new UserVO();
sanitized.setId(userVO.getId());
sanitized.setShopId(userVO.getShopId());
sanitized.setShopName(userVO.getShopName());
sanitized.setShopIds(userVO.getShopIds());
sanitized.setShopNames(userVO.getShopNames());
sanitized.setNickname(userVO.getNickname());
sanitized.setAvatar(userVO.getAvatar());
sanitized.setType(userVO.getType());
sanitized.setStatus(userVO.getStatus());
sanitized.setCreateTime(userVO.getCreateTime());
sanitized.setUpdateTime(userVO.getUpdateTime());
return sanitized;
}
@Data
public static class PasswordDTO {
private String password;
@@ -41,4 +41,9 @@ public class ShopDTO {
* 店铺图片文件ID集合,多个ID以逗号分隔
*/
private String imageFileIds;
/**
* 店铺状态:1-启用,0-停用
*/
private Integer status;
}
@@ -0,0 +1,9 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
@Data
public class SwitchShopRequestDTO {
private Long shopId;
}
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import java.util.List;
/**
* 系统用户信息表 DTO
* 用于用户信息的传输
@@ -17,6 +19,11 @@ public class UserDTO {
*/
private Long shopId;
/**
* 绑定店铺ID列表
*/
private List<Long> shopIds;
/**
* 用户昵称
*/
@@ -62,6 +62,12 @@ public class ShopDO extends BaseEntity {
@TableField("image_file_ids")
private String imageFileIds;
/**
* 店铺状态:1-启用,0-停用
*/
@TableField("status")
private Integer status;
/**
* 逻辑删除:0-未删,1-已删
*/
@@ -0,0 +1,37 @@
package com.xiaowang.yuminailcore.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
/**
* 用户与店铺绑定关系。
*/
@Getter
@Setter
@TableName("t_user_shop_binding")
public class UserShopBindingDO extends BaseEntity {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@TableField("user_id")
private Long userId;
@TableField("shop_id")
private Long shopId;
/**
* 绑定状态:1-正常,0-禁用。
*/
@TableField("status")
private Integer status;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,7 @@
package com.xiaowang.yuminailcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.entity.UserShopBindingDO;
public interface UserShopBindingMapper extends BaseMapper<UserShopBindingDO> {
}
@@ -57,6 +57,13 @@ public interface ShopService extends IService<ShopDO> {
*/
List<ShopVO> listAllShops();
/**
* 查询后台全部店铺(含停用,不含删除)
*
* @return 店铺列表
*/
List<ShopVO> listAllShopsForAdmin();
/**
* 根据店铺名称查询店铺
*
@@ -74,4 +81,13 @@ public interface ShopService extends IService<ShopDO> {
* @return 分页结果
*/
PageResultVO<ShopVO> pageShops(Integer page, Integer size, String keyword, Long shopId);
/**
* 更新店铺状态
*
* @param id 店铺ID
* @param status 状态:1-启用,0-停用
* @return 是否成功
*/
boolean updateShopStatus(Long id, Integer status);
}
@@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.dto.ResetPasswordRequestDTO;
import com.xiaowang.yuminailcore.dto.UpdatePhoneRequestDTO;
import com.xiaowang.yuminailcore.dto.UserDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.UserVO;
@@ -40,6 +41,16 @@ public interface UserService extends IService<UserDO> {
LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO);
LoginShopSelectionVO getLoginShopSelectionByAccount(String account);
LoginShopSelectionVO getLoginShopSelectionByPhone(String phone);
LoginShopSelectionVO getAdminLoginShopSelection(String account);
LoginResponseVO switchShop(Long userId, Long shopId);
LoginResponseVO switchAdminShop(Long userId, Long shopId);
boolean register(RegisterRequestDTO registerRequestDTO);
LoginResponseVO refreshToken(String refreshToken);
@@ -61,6 +72,10 @@ public interface UserService extends IService<UserDO> {
PageResultVO<UserVO> pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type);
boolean updateUserStatus(Long id, Integer status);
boolean updateUserStatusInShop(Long id, Integer status, Long shopId);
boolean deleteUserInShop(Long id, Long shopId);
boolean updateUserAvatar(Long userId, String avatarUrl);
@@ -17,6 +17,7 @@ import com.xiaowang.yuminailcore.mapper.TagMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.CouponVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.TagVO;
@@ -30,6 +31,7 @@ import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
@@ -56,6 +58,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
private final TagMapper tagMapper;
private final ShopMapper shopMapper;
private final UserMapper userMapper;
private final UserShopBindingSupport userShopBindingSupport;
@Override
@Transactional
@@ -108,6 +111,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel());
couponDO.setAutoMatch(couponDTO.getAutoMatch());
updateById(couponDO);
refreshCouponDistributionStatus(id);
// 处理标签关联
handleCouponTags(id, couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds());
@@ -184,9 +188,15 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
if (couponDO.getStatus() != 1) {
return false;
}
if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) {
return false;
}
if (isVipAutoCoupon(couponDO)) {
throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放");
}
if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) {
return false;
}
// 检查是否已经分配
UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper<UserCouponDO>()
@@ -197,6 +207,9 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
if (existing != null) {
return false;
}
if (!hasRemainingDistributionStock(couponDO, 1)) {
return false;
}
// 分配优惠券
UserCouponDO userCouponDO = new UserCouponDO();
@@ -205,6 +218,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
userCouponDO.setStatus(1);
userCouponDO.setObtainTime(LocalDateTime.now());
userCouponMapper.insert(userCouponDO);
refreshCouponDistributionStatus(couponId);
return true;
}
@@ -260,11 +274,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
userCouponMapper.updateById(userCouponDO);
// 更新优惠券使用数量
couponDO.setUsedCount(couponDO.getUsedCount() + 1);
if (couponDO.getUsedCount() >= couponDO.getTotalCount()) {
couponDO.setStatus(3);
}
updateById(couponDO);
incrementCouponUsedCount(couponDO.getId());
return true;
}
@@ -364,32 +374,52 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
}
// 检查优惠券数量是否足够
int totalNeeded = userIds.size() * quantity;
if (couponDO.getUsedCount() + totalNeeded > couponDO.getTotalCount()) {
if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) {
return false;
}
if (userIds == null || userIds.isEmpty() || quantity == null || quantity < 1) {
return false;
}
if (quantity > 1) {
throw new RuntimeException("当前用户券受唯一索引限制,同一用户同一模板只能发放 1 张");
}
List<Long> targetUserIds = userIds.stream()
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (targetUserIds.isEmpty()) {
return false;
}
for (Long userId : targetUserIds) {
if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) {
return false;
}
UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper<UserCouponDO>()
.eq(UserCouponDO::getUserId, userId)
.eq(UserCouponDO::getCouponId, couponId)
.eq(UserCouponDO::getIsDelete, 0));
if (existing != null) {
throw new RuntimeException("用户已持有该优惠券,不能重复发放");
}
}
int totalNeeded = targetUserIds.size() * quantity;
if (!hasRemainingDistributionStock(couponDO, totalNeeded)) {
return false;
}
// 发放优惠券
int distributedCount = 0;
for (Long userId : userIds) {
for (int i = 0; i < quantity; i++) {
// 分配优惠券(不检查是否已存在,允许用户拥有多张相同优惠券)
UserCouponDO userCouponDO = new UserCouponDO();
userCouponDO.setUserId(userId);
userCouponDO.setCouponId(couponId);
userCouponDO.setStatus(1);
userCouponDO.setObtainTime(LocalDateTime.now());
userCouponMapper.insert(userCouponDO);
distributedCount++;
}
LocalDateTime obtainTime = LocalDateTime.now();
for (Long userId : targetUserIds) {
UserCouponDO userCouponDO = new UserCouponDO();
userCouponDO.setUserId(userId);
userCouponDO.setCouponId(couponId);
userCouponDO.setStatus(1);
userCouponDO.setObtainTime(obtainTime);
userCouponMapper.insert(userCouponDO);
}
// 更新优惠券使用数量
couponDO.setUsedCount(couponDO.getUsedCount() + distributedCount);
if (couponDO.getUsedCount() >= couponDO.getTotalCount()) {
couponDO.setStatus(3); // 已用完
}
updateById(couponDO);
refreshCouponDistributionStatus(couponId);
return true;
}
@@ -568,8 +598,8 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
couponVO.setMinAmount(couponDO.getMinAmount());
couponVO.setReduceAmount(couponDO.getReduceAmount());
couponVO.setTotalCount(couponDO.getTotalCount());
couponVO.setUsedCount(couponDO.getUsedCount());
couponVO.setRemainingCount(couponDO.getTotalCount() - couponDO.getUsedCount());
couponVO.setUsedCount(normalizeCount(couponDO.getUsedCount()));
couponVO.setRemainingCount(calculateRemainingDistributionCount(couponDO));
couponVO.setStartTime(couponDO.getStartTime());
couponVO.setEndTime(couponDO.getEndTime());
couponVO.setStatus(couponDO.getStatus());
@@ -715,6 +745,79 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
&& COUPON_SCENE_VIP_AUTO.equals(couponDO.getCouponScene());
}
private boolean hasRemainingDistributionStock(CouponDO couponDO, int requiredCount) {
return calculateRemainingDistributionCount(couponDO) >= requiredCount;
}
private int calculateRemainingDistributionCount(CouponDO couponDO) {
if (couponDO == null || couponDO.getId() == null) {
return 0;
}
int totalCount = normalizeCount(couponDO.getTotalCount());
long issuedCount = userCouponMapper.selectCount(new LambdaQueryWrapper<UserCouponDO>()
.eq(UserCouponDO::getCouponId, couponDO.getId())
.eq(UserCouponDO::getIsDelete, 0));
return Math.max(0, totalCount - (int) issuedCount);
}
private void incrementCouponUsedCount(Long couponId) {
CouponDO couponDO = getById(couponId);
if (couponDO == null) {
return;
}
couponDO.setUsedCount(normalizeCount(couponDO.getUsedCount()) + 1);
updateById(couponDO);
}
private void decrementCouponUsedCount(Long couponId) {
CouponDO couponDO = getById(couponId);
if (couponDO == null) {
return;
}
couponDO.setUsedCount(Math.max(0, normalizeCount(couponDO.getUsedCount()) - 1));
updateById(couponDO);
}
private boolean isUserEligibleForCouponDistribution(Long userId, CouponDO couponDO, Long requestedShopId) {
if (userId == null) {
return false;
}
UserDO userDO = userMapper.selectById(userId);
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return false;
}
if (requestedShopId != null && !userShopBindingSupport.isUserAccessibleInShop(userId, requestedShopId)) {
return false;
}
if (couponDO != null && couponDO.getShopId() != null
&& !userShopBindingSupport.isUserAccessibleInShop(userId, couponDO.getShopId())) {
return false;
}
return true;
}
private void refreshCouponDistributionStatus(Long couponId) {
CouponDO couponDO = getById(couponId);
if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) {
return;
}
if (Integer.valueOf(2).equals(couponDO.getStatus())) {
return;
}
int remainingCount = calculateRemainingDistributionCount(couponDO);
int targetStatus = remainingCount > 0 ? 1 : 3;
if (!Objects.equals(couponDO.getStatus(), targetStatus)) {
couponDO.setStatus(targetStatus);
updateById(couponDO);
}
}
private int normalizeCount(Integer count) {
return count == null ? 0 : count;
}
private BigDecimal calculateDiscountAmount(UserCouponVO couponVO, BigDecimal orderAmount) {
if (couponVO == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
@@ -10,6 +10,8 @@ import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.ShopMapper;
import com.xiaowang.yuminailcore.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -28,6 +30,9 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
@Autowired
private ShopMapper shopMapper;
@Autowired
private UserShopBindingSupport userShopBindingSupport;
@Override
public NailArtistInfoDTO getByUserId(Long userId) {
@@ -60,18 +65,25 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
@Override
public List<NailArtistInfoDTO> getByShopId(Long shopId) {
// 先获取该店铺的所有美甲师用户
List<Long> artistUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (artistUserIds.isEmpty()) {
return new ArrayList<>();
}
LambdaQueryWrapper<UserDO> userQueryWrapper = new LambdaQueryWrapper<>();
userQueryWrapper.eq(UserDO::getShopId, shopId);
userQueryWrapper.eq(UserDO::getType, 3); // 3表示美甲师
userQueryWrapper.in(UserDO::getId, artistUserIds);
userQueryWrapper.eq(UserDO::getType, 3);
userQueryWrapper.eq(UserDO::getIsDelete, 0);
List<UserDO> userDOList = userMapper.selectList(userQueryWrapper);
List<NailArtistInfoDTO> nailArtistInfoDTOList = new ArrayList<>();
ShopDO currentShop = shopMapper.selectById(shopId);
for (UserDO userDO : userDOList) {
NailArtistInfoDTO nailArtistInfoDTO = getByUserId(userDO.getId());
if (nailArtistInfoDTO != null) {
nailArtistInfoDTO.setShopId(shopId);
nailArtistInfoDTO.setShopName(currentShop == null ? null : currentShop.getShopName());
nailArtistInfoDTOList.add(nailArtistInfoDTO);
}
}
@@ -111,13 +123,17 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
UserDO userDO = userMapper.selectById(nailArtistInfoDO.getUserId());
if (userDO != null) {
nailArtistInfoDTO.setNickname(userDO.getNickname());
nailArtistInfoDTO.setShopId(userDO.getShopId());
nailArtistInfoDTO.setSignature(userDO.getSignature()); // 添加用户签名
// 获取店铺信息
if (userDO.getShopId() != null && userDO.getShopId() > 0) {
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(userDO.getId(), false, false);
if (!shopOptions.isEmpty()) {
ShopSimpleVO primaryShop = shopOptions.get(0);
nailArtistInfoDTO.setShopId(primaryShop.getId());
nailArtistInfoDTO.setShopName(primaryShop.getShopName());
} else if (userDO.getShopId() != null && userDO.getShopId() > 0) {
ShopDO shopDO = shopMapper.selectById(userDO.getShopId());
if (shopDO != null) {
nailArtistInfoDTO.setShopId(shopDO.getId());
nailArtistInfoDTO.setShopName(shopDO.getShopName());
}
}
@@ -22,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.service.OrderService;
import com.xiaowang.yuminailcore.service.TagService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.OrderItemVO;
import com.xiaowang.yuminailcore.vo.OrderVO;
import com.xiaowang.yuminailcore.vo.TagVO;
@@ -95,6 +96,9 @@ public class OrderServiceImpl implements OrderService {
@Resource
private TagService tagService;
@Resource
private UserShopBindingSupport userShopBindingSupport;
@Override
@Transactional
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
@@ -471,7 +475,7 @@ public class OrderServiceImpl implements OrderService {
if (!Integer.valueOf(1).equals(artist.getStatus())) {
throw new RuntimeException("美甲师当前不可预约");
}
if (product.getShopId() != null && !product.getShopId().equals(artist.getShopId())) {
if (product.getShopId() != null && !userShopBindingSupport.isUserAccessibleInShop(artistId, product.getShopId())) {
throw new RuntimeException("该美甲师不属于当前商品店铺");
}
@@ -631,6 +635,9 @@ public class OrderServiceImpl implements OrderService {
}
ProductDO product = productMapper.selectById(productId);
if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) {
product = null;
}
productCache.put(productId, product);
return product;
}
@@ -759,6 +766,7 @@ public class OrderServiceImpl implements OrderService {
userCoupon.setStatus(2);
userCoupon.setUseTime(LocalDateTime.now());
userCouponMapper.updateById(userCoupon);
updateCouponUsedCount(userCoupon.getCouponId(), 1);
}
private void restoreUserCoupon(OrderDO order, Long userId) {
@@ -777,6 +785,22 @@ public class OrderServiceImpl implements OrderService {
userCoupon.setStatus(1);
userCoupon.setUseTime(null);
userCouponMapper.updateById(userCoupon);
updateCouponUsedCount(userCoupon.getCouponId(), -1);
}
private void updateCouponUsedCount(Long couponId, int delta) {
if (couponId == null || delta == 0) {
return;
}
CouponDO couponDO = couponMapper.selectById(couponId);
if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) {
return;
}
int currentUsedCount = couponDO.getUsedCount() == null ? 0 : couponDO.getUsedCount();
couponDO.setUsedCount(Math.max(0, currentUsedCount + delta));
couponMapper.updateById(couponDO);
}
private static final class CouponSelection {
@@ -11,23 +11,21 @@ import com.xiaowang.yuminailcore.mapper.PermissionMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.UserPermissionMapper;
import com.xiaowang.yuminailcore.service.PermissionService;
import com.xiaowang.yuminailcore.support.PermissionPolicy;
import com.xiaowang.yuminailcore.support.RequestShopContext;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.PermissionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 系统权限表 Service 实现
* 对应数据库表 t_permission
*
* @author xiaowang
* @date 2026-02-25
*/
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, PermissionDO> implements PermissionService {
@@ -40,6 +38,7 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
private final PermissionMapper permissionMapper;
private final UserPermissionMapper userPermissionMapper;
private final UserMapper userMapper;
private final UserShopBindingSupport userShopBindingSupport;
@Override
public Long createPermission(PermissionDTO permissionDTO) {
@@ -56,7 +55,7 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
@Override
public boolean updatePermission(Long id, PermissionDTO permissionDTO) {
PermissionDO permissionDO = permissionMapper.selectById(id);
if (permissionDO == null) {
if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) {
return false;
}
if (permissionDTO.getPermissionCode() != null) {
@@ -78,17 +77,18 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
@Override
public boolean deletePermission(Long id) {
PermissionDO permissionDO = permissionMapper.selectById(id);
if (permissionDO == null) {
if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) {
return false;
}
permissionDO.setIsDelete(1);
permissionDO.setUpdateTime(LocalDateTime.now());
return permissionMapper.updateById(permissionDO) > 0;
}
@Override
public PermissionVO getPermissionById(Long id) {
PermissionDO permissionDO = permissionMapper.selectById(id);
if (permissionDO == null) {
if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) {
return null;
}
return convertToVO(permissionDO);
@@ -96,23 +96,21 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
@Override
public List<PermissionVO> listAllPermissions() {
List<PermissionDO> permissionDOs = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getIsDelete, 0)
);
return permissionDOs.stream()
return permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getIsDelete, 0)
).stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
public List<PermissionVO> listPermissionsByGroup(String permissionGroup) {
List<PermissionDO> permissionDOs = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getPermissionGroup, permissionGroup)
.eq(PermissionDO::getIsDelete, 0)
);
return permissionDOs.stream()
return permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getPermissionGroup, permissionGroup)
.eq(PermissionDO::getIsDelete, 0)
).stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@@ -124,22 +122,24 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
Wrappers.lambdaQuery(UserPermissionDO.class)
.eq(UserPermissionDO::getUserId, userId)
);
if (userPermissions.isEmpty()) {
return List.of();
}
List<Long> permissionIds = userPermissions.stream()
.map(UserPermissionDO::getPermissionId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (permissionIds.isEmpty()) {
return List.of();
}
List<PermissionDO> permissionDOs = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.in(PermissionDO::getId, permissionIds)
.eq(PermissionDO::getIsDelete, 0)
);
List<PermissionVO> permissionVOs = permissionDOs.stream()
List<PermissionVO> permissionVOs = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.in(PermissionDO::getId, permissionIds)
.eq(PermissionDO::getIsDelete, 0)
).stream()
.map(this::convertToVO)
.collect(Collectors.toList());
@@ -156,48 +156,66 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
@Transactional(rollbackFor = Exception.class)
public boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId) {
Long userId = userPermissionDTO.getUserId();
List<Long> permissionIds = userPermissionDTO.getPermissionIds();
List<Long> permissionIds = userPermissionDTO.getPermissionIds() == null
? Collections.emptyList()
: userPermissionDTO.getPermissionIds().stream()
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
// 获取当前用户信息
UserDO currentUser = userMapper.selectById(currentUserId);
if (currentUser == null) {
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
throw new RuntimeException("当前用户不存在");
}
// 获取被分配权限的用户信息
UserDO targetUser = userMapper.selectById(userId);
if (targetUser == null) {
if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) {
throw new RuntimeException("目标用户不存在");
}
// 检查权限:只有拥有权限分配权限的用户可以给其他用户分配权限
if (!hasPermission(currentUserId, "permission:assign")) {
throw new RuntimeException("权限不足,没有权限分配权限");
throw new RuntimeException("权限不足,无法分配权限");
}
// 如果当前用户是店长,需要进一步检查
if (currentUser.getType() == 2) {
// 店长只能给属于自己店铺的用户分配权限
if (targetUser.getShopId() == null || !targetUser.getShopId().equals(currentUser.getShopId())) {
throw new RuntimeException("权限不足,只能给本店铺的用户分配权限");
boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType());
Long currentShopId = RequestShopContext.getCurrentShopId();
if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) {
throw new RuntimeException("当前角色不能维护该用户的权限");
}
if (!platformAdmin) {
if (currentUserId.equals(userId)) {
throw new RuntimeException("不允许给自己调整权限");
}
if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(userId, currentShopId)) {
throw new RuntimeException("只能给本店铺用户分配权限");
}
}
Set<String> requestedPermissionCodes = resolvePermissionCodes(permissionIds);
Set<String> allowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType());
if (!allowedPermissionCodes.containsAll(requestedPermissionCodes)) {
throw new RuntimeException("目标角色的权限配置超出允许范围");
}
if (!platformAdmin) {
Set<String> operatorPermissionCodes = listPermissionCodesByUserId(currentUserId);
if (!operatorPermissionCodes.containsAll(requestedPermissionCodes)) {
throw new RuntimeException("不能分配超出自己已有的权限");
}
}
// 删除旧的权限分配
userPermissionMapper.delete(
Wrappers.lambdaQuery(UserPermissionDO.class)
.eq(UserPermissionDO::getUserId, userId)
);
// 分配新的权限
if (permissionIds != null && !permissionIds.isEmpty()) {
for (Long permissionId : permissionIds) {
UserPermissionDO userPermissionDO = new UserPermissionDO();
userPermissionDO.setUserId(userId);
userPermissionDO.setPermissionId(permissionId);
userPermissionDO.setCreateBy(currentUserId);
userPermissionMapper.insert(userPermissionDO);
}
for (Long permissionId : permissionIds) {
UserPermissionDO userPermissionDO = new UserPermissionDO();
userPermissionDO.setUserId(userId);
userPermissionDO.setPermissionId(permissionId);
userPermissionDO.setCreateBy(currentUserId);
userPermissionMapper.insert(userPermissionDO);
}
return true;
@@ -210,26 +228,25 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
Wrappers.lambdaQuery(UserPermissionDO.class)
.eq(UserPermissionDO::getUserId, userId)
);
if (userPermissions.isEmpty()) {
return false;
}
List<Long> permissionIds = userPermissions.stream()
.map(UserPermissionDO::getPermissionId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (permissionIds.isEmpty()) {
return false;
}
PermissionDO permissionDO = permissionMapper.selectOne(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getPermissionCode, permissionCode)
.eq(PermissionDO::getIsDelete, 0)
);
if (permissionDO == null) {
return false;
}
if (!permissionIds.contains(permissionDO.getId())) {
if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) {
return false;
}
@@ -240,10 +257,56 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
return true;
}
private Set<String> resolvePermissionCodes(List<Long> permissionIds) {
if (permissionIds == null || permissionIds.isEmpty()) {
return Collections.emptySet();
}
List<PermissionDO> permissionDOs = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.in(PermissionDO::getId, permissionIds)
.eq(PermissionDO::getIsDelete, 0)
);
if (permissionDOs.size() != permissionIds.size()) {
throw new RuntimeException("存在无效的权限配置");
}
return permissionDOs.stream()
.map(PermissionDO::getPermissionCode)
.collect(Collectors.toSet());
}
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();
}
List<Long> permissionIds = userPermissions.stream()
.map(UserPermissionDO::getPermissionId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (permissionIds.isEmpty()) {
return Collections.emptySet();
}
return permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.in(PermissionDO::getId, permissionIds)
.eq(PermissionDO::getIsDelete, 0)
).stream()
.map(PermissionDO::getPermissionCode)
.collect(Collectors.toSet());
}
private boolean isShopBootstrapAdmin(UserDO userDO) {
return userDO != null
&& Integer.valueOf(4).equals(userDO.getType())
&& (userDO.getShopId() == null || userDO.getShopId() <= 0);
&& RequestShopContext.getCurrentShopId() == null;
}
private PermissionVO convertToVO(PermissionDO permissionDO) {
@@ -12,6 +12,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.service.ProductService;
import com.xiaowang.yuminailcore.service.TagService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.ProductVO;
@@ -40,6 +41,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
private final TagService tagService;
private final ObjectStorageFileService objectStorageFileService;
private final UserMapper userMapper;
private final UserShopBindingSupport userShopBindingSupport;
@Override
public Long createProduct(ProductDTO productDTO) {
@@ -80,7 +82,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
@Override
public boolean deleteProduct(Long id) {
return removeById(id);
ProductDO productDO = productMapper.selectById(id);
if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) {
return false;
}
productDO.setIsDelete(1);
return productMapper.updateById(productDO) > 0;
}
@Override
@@ -96,7 +103,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
@Override
public ProductVO getProductById(Long id) {
ProductDO productDO = productMapper.selectById(id);
if (productDO == null) {
if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) {
return null;
}
return convertToVO(productDO);
@@ -104,7 +111,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
@Override
public List<ProductVO> listAllProducts() {
List<ProductDO> productDOs = productMapper.selectList(null);
List<ProductDO> productDOs = productMapper.selectList(
Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0)
);
return productDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
@@ -114,6 +124,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
public List<ProductVO> listProductsByShopId(Long shopId) {
List<ProductDO> productDOs = productMapper.selectList(
Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0)
.eq(ProductDO::getShopId, shopId)
);
return productDOs.stream()
@@ -133,6 +144,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
String tagIdStr = String.valueOf(tagVO.getId());
List<ProductDO> productDOs = productMapper.selectList(
Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0)
.and(wrapper -> wrapper
.eq(ProductDO::getTags, tagIdStr)
.or()
@@ -225,6 +237,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
Page<ProductDO> pageParam = new Page<>(page, size);
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class);
wrapper.eq(ProductDO::getIsDelete, 0);
if (StringUtils.hasText(keyword)) {
wrapper.and(w -> w.like(ProductDO::getTitle, keyword)
.or().like(ProductDO::getDescription, keyword));
@@ -273,7 +286,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
if (!Integer.valueOf(3).equals(artist.getType())) {
throw new RuntimeException("存在非美甲师账号被配置到可预约列表");
}
if (!shopId.equals(artist.getShopId())) {
if (!userShopBindingSupport.isUserAccessibleInShop(artistId, shopId)) {
throw new RuntimeException("不可跨店铺配置可预约美甲师");
}
}
@@ -5,10 +5,21 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.dto.ShopDTO;
import com.xiaowang.yuminailcore.entity.CouponDO;
import com.xiaowang.yuminailcore.entity.CommentDO;
import com.xiaowang.yuminailcore.entity.ProductDO;
import com.xiaowang.yuminailcore.entity.ShopDO;
import com.xiaowang.yuminailcore.entity.TagDO;
import com.xiaowang.yuminailcore.entity.UserCouponDO;
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.ShopService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.ShopVO;
import lombok.RequiredArgsConstructor;
@@ -32,6 +43,12 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
private final ShopMapper shopMapper;
private final CouponService couponService;
private final CouponMapper couponMapper;
private final ProductMapper productMapper;
private final TagMapper tagMapper;
private final CommentMapper commentMapper;
private final UserCouponMapper userCouponMapper;
private final UserShopBindingSupport userShopBindingSupport;
@Override
@Transactional(rollbackFor = Exception.class)
@@ -43,6 +60,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopDO.setBusinessHours(shopDTO.getBusinessHours());
shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId());
shopDO.setImageFileIds(shopDTO.getImageFileIds());
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
shopDO.setIsDelete(0);
shopMapper.insert(shopDO);
couponService.initializeDefaultVipAutoCoupons(shopDO.getId());
@@ -61,22 +79,68 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopDO.setBusinessHours(shopDTO.getBusinessHours());
shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId());
shopDO.setImageFileIds(shopDTO.getImageFileIds());
if (shopDTO.getStatus() != null) {
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
}
return shopMapper.updateById(shopDO) > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteShop(Long id) {
ShopDO shopDO = shopMapper.selectById(id);
if (shopDO == null) {
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
return false;
}
return this.removeById(id);
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);
return shopMapper.updateById(shopDO) > 0;
}
@Override
public boolean updateShopStatus(Long id, Integer status) {
ShopDO shopDO = shopMapper.selectById(id);
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
return false;
}
shopDO.setStatus(normalizeStatus(status));
return shopMapper.updateById(shopDO) > 0;
}
@Override
public ShopVO getShopById(Long id) {
ShopDO shopDO = shopMapper.selectById(id);
if (shopDO == null) {
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
return null;
}
return convertToVO(shopDO);
@@ -87,6 +151,19 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
List<ShopDO> shopDOs = shopMapper.selectList(
Wrappers.lambdaQuery(ShopDO.class)
.eq(ShopDO::getIsDelete, 0)
.eq(ShopDO::getStatus, 1)
);
return shopDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
public List<ShopVO> listAllShopsForAdmin() {
List<ShopDO> shopDOs = shopMapper.selectList(
Wrappers.lambdaQuery(ShopDO.class)
.eq(ShopDO::getIsDelete, 0)
.orderByDesc(ShopDO::getCreateTime)
);
return shopDOs.stream()
.map(this::convertToVO)
@@ -97,6 +174,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
public List<ShopVO> listShopsByShopName(String shopName) {
List<ShopDO> shopDOs = shopMapper.selectList(
Wrappers.lambdaQuery(ShopDO.class)
.eq(ShopDO::getIsDelete, 0)
.eq(ShopDO::getStatus, 1)
.like(ShopDO::getShopName, shopName)
);
return shopDOs.stream()
@@ -148,8 +227,13 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopVO.setCoverImageUrls(new java.util.ArrayList<>());
shopVO.setImageFileIds(shopDO.getImageFileIds());
shopVO.setImageUrls(new java.util.ArrayList<>());
shopVO.setStatus(normalizeStatus(shopDO.getStatus()));
shopVO.setCreateTime(shopDO.getCreateTime());
shopVO.setUpdateTime(shopDO.getUpdateTime());
return shopVO;
}
private Integer normalizeStatus(Integer status) {
return Integer.valueOf(0).equals(status) ? 0 : 1;
}
}
@@ -16,9 +16,14 @@ import com.xiaowang.yuminailcore.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.service.ShopService;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.service.VerificationCodeService;
import com.xiaowang.yuminailcore.support.PermissionPolicy;
import com.xiaowang.yuminailcore.support.RequestShopContext;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.utils.JwtUtil;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
import com.xiaowang.yuminailcore.vo.UserVO;
import com.xiaowang.yuminailcore.vo.ShopVO;
import lombok.RequiredArgsConstructor;
@@ -29,6 +34,7 @@ import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -52,43 +58,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
private static final String DELETED_PHONE_MARKER = "_deleted_";
private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L;
private static final List<String> ADMIN_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
"user:balance:view",
"product:view",
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
"tag:view",
"coupon:view",
"order:view",
"nail_artist:view"
);
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:edit", "shop:staff:manage",
"permission:view", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit"
);
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"user:view", "user:create",
"user:balance:view",
"product:view", "product:create",
"shop:view",
"tag:view", "tag:create",
"coupon:view",
"order:view"
);
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = buildManagedDefaultPermissionCodes();
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes();
private static final Map<String, PermissionSeed> DEFAULT_PERMISSION_SEEDS = buildDefaultPermissionSeeds();
// 注入用户数据访问层、JWT工具类和店铺服务
@@ -100,14 +70,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private final NailArtistInfoService nailArtistInfoService;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private final VerificationCodeService verificationCodeService;
private static Set<String> buildManagedDefaultPermissionCodes() {
LinkedHashSet<String> permissionCodes = new LinkedHashSet<>();
permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES);
return Set.copyOf(permissionCodes);
}
private final UserShopBindingSupport userShopBindingSupport;
private static Map<String, PermissionSeed> buildDefaultPermissionSeeds() {
Map<String, PermissionSeed> seeds = new HashMap<>();
@@ -244,12 +207,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
private List<String> getDefaultPermissionCodes(Integer userType) {
return switch (userType == null ? -1 : userType) {
case 4 -> ADMIN_DEFAULT_PERMISSION_CODES;
case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES;
case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES;
default -> List.of();
};
return PermissionPolicy.getDefaultPermissionCodes(userType);
}
private void assignDefaultPermissions(Long userId, Integer userType) {
@@ -274,8 +232,12 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("账号已存在");
}
Long validatedShopId = validateAndNormalizeShopId(userDTO.getShopId());
List<Long> validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId());
Long validatedShopId = pickPrimaryShopId(validatedShopIds);
String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true);
Integer userType = userDTO.getType();
ensureShopBindingRequirement(userType, validatedShopIds);
// 创建用户实体并设置属性
UserDO userDO = new UserDO();
@@ -286,7 +248,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userDO.setPhone(validatedPhone);
userDO.setSignature(userDTO.getSignature());
userDO.setLevel(userDTO.getLevel());
userDO.setType(userDTO.getType());
userDO.setType(userType);
userDO.setVipId(userDTO.getVipId());
userDO.setIsDelete(0);
userDO.setStatus(1);
@@ -316,6 +278,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
// 分配默认权限
assignDefaultPermissions(userDO.getId(), userDO.getType());
userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds);
// 如果是美甲师,创建对应的美甲师信息记录
if (userDO.getType() == 3) {
@@ -407,8 +370,23 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
if (userDTO.getVipId() != null) {
userDO.setVipId(userDTO.getVipId());
}
Integer targetUserType = userDO.getType();
List<Long> validatedShopIds = null;
boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null;
if (shopBindingChanged) {
validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId());
ensureShopBindingRequirement(targetUserType, validatedShopIds);
userDO.setShopId(pickPrimaryShopId(validatedShopIds));
}
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
boolean updated = userMapper.updateById(userDO) > 0;
if (updated) {
if (shopBindingChanged) {
userShopBindingSupport.syncUserShopBindings(id, validatedShopIds);
}
syncDefaultPermissions(id, targetUserType);
}
return updated;
}
/**
@@ -418,7 +396,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
@Override
public boolean deleteUser(Long id) {
return removeById(id);
UserDO userDO = userMapper.selectById(id);
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return false;
}
userDO.setAccount(buildDeletedAccount(userDO));
userDO.setPhone(buildDeletedPhone(userDO));
userDO.setStatus(0);
userDO.setIsDelete(1);
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
}
/**
@@ -429,7 +417,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
@Override
public UserVO getUserById(Long id) {
UserDO userDO = userMapper.selectById(id);
if (userDO == null) {
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return null;
}
return convertToVO(userDO);
@@ -457,10 +445,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
@Override
public List<UserVO> listUsersByShopId(Long shopId) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
return List.of();
}
List<UserDO> userDOs = userMapper.selectList(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getIsDelete, 0)
.eq(UserDO::getShopId, shopId)
.in(UserDO::getId, userIds)
);
return userDOs.stream()
.map(this::convertToVO)
@@ -494,8 +486,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, account)
.eq(UserDO::getIsDelete, 0)
);
if (userDO == null) {
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return null;
}
return convertToVO(userDO);
@@ -510,13 +503,23 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private UserVO convertToVO(UserDO userDO) {
UserVO userVO = new UserVO();
userVO.setId(userDO.getId());
userVO.setShopId(userDO.getShopId());
if (userDO.getShopId() != null && userDO.getShopId() > 0) {
ShopVO shopVO = shopService.getShopById(userDO.getShopId());
if (shopVO != null) {
userVO.setShopName(shopVO.getShopName());
}
List<ShopSimpleVO> shopOptions = resolveShopOptions(userDO, false, false);
Long scopedShopId = RequestShopContext.getCurrentShopId();
if (scopedShopId != null) {
shopOptions.stream()
.filter(shop -> Objects.equals(shop.getId(), scopedShopId))
.findFirst()
.ifPresent(shop -> {
shopOptions.remove(shop);
shopOptions.add(0, shop);
});
}
Long primaryShopId = !shopOptions.isEmpty() ? shopOptions.get(0).getId() : normalizeShopId(userDO.getShopId());
String primaryShopName = !shopOptions.isEmpty() ? shopOptions.get(0).getShopName() : null;
userVO.setShopId(primaryShopId);
userVO.setShopName(primaryShopName);
userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList()));
userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList()));
userVO.setNickname(userDO.getNickname());
userVO.setAccount(userDO.getAccount());
userVO.setPhone(userDO.getPhone());
@@ -528,10 +531,130 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userVO.setVipId(userDO.getVipId());
userVO.setCreateTime(userDO.getCreateTime());
userVO.setUpdateTime(userDO.getUpdateTime());
userVO.setStatus(userDO.getStatus() != null ? userDO.getStatus() : 1);
Integer scopedStatus = userShopBindingSupport.listBindingsByUserId(userDO.getId(), false).stream()
.filter(binding -> Objects.equals(binding.getShopId(), scopedShopId))
.map(binding -> Integer.valueOf(1).equals(binding.getStatus()) ? 1 : 0)
.findFirst()
.orElse(null);
userVO.setStatus(scopedStatus != null ? scopedStatus : (userDO.getStatus() != null ? userDO.getStatus() : 1));
return userVO;
}
@Override
public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) {
String normalizedAccount = account == null ? "" : account.trim();
if (!StringUtils.hasText(normalizedAccount)) {
return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺");
}
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
if (userDO == null) {
return buildLoginShopSelection(List.of(), false, "该账号未注册");
}
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
}
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
if (!shops.isEmpty()) {
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
}
if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) {
return buildLoginShopSelection(
userShopBindingSupport.listAllActiveShopOptions(),
false,
"该账号首次登录,请先选择店铺"
);
}
return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理");
}
@Override
public LoginShopSelectionVO getLoginShopSelectionByPhone(String phone) {
String normalizedPhone = phone == null ? "" : phone.trim();
if (!StringUtils.hasText(normalizedPhone)) {
return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺");
}
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, normalizedPhone)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
if (userDO == null) {
return buildLoginShopSelection(
userShopBindingSupport.listAllActiveShopOptions(),
false,
"新手机号首次登录需要选择店铺"
);
}
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
}
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
if (!shops.isEmpty()) {
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
}
if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) {
return buildLoginShopSelection(
userShopBindingSupport.listAllActiveShopOptions(),
false,
"该手机号账号首次登录,请先选择店铺"
);
}
return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理");
}
@Override
public LoginShopSelectionVO getAdminLoginShopSelection(String account) {
String normalizedAccount = account == null ? "" : account.trim();
if (!StringUtils.hasText(normalizedAccount)) {
return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺");
}
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
if (userDO == null) {
return buildLoginShopSelection(List.of(), false, "该账号不存在");
}
if (userDO.getType() == null || userDO.getType() < 2) {
return buildLoginShopSelection(List.of(), false, "该账号没有后台管理权限");
}
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
}
if (Integer.valueOf(4).equals(userDO.getType())) {
List<ShopSimpleVO> shops = userShopBindingSupport.listAllActiveShopOptions();
boolean allowShoplessLogin = shops.isEmpty();
String message = allowShoplessLogin
? "当前暂无启用店铺,可直接登录后台创建店铺"
: buildLoginShopMessage(shops);
return buildLoginShopSelection(shops, allowShoplessLogin, message);
}
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
if (!shops.isEmpty()) {
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
}
return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系平台管理员");
}
@Override
public LoginResponseVO login(LoginRequestDTO loginRequestDTO) {
UserDO userDO = userMapper.selectOne(
@@ -550,33 +673,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("密码错误");
}
// 检查是否需要设置店铺
if (userDO.getShopId() == null || userDO.getShopId() == 0) {
if (loginRequestDTO.getShopId() == null || loginRequestDTO.getShopId() == 0) {
throw new RuntimeException("请选择店铺");
}
userDO.setShopId(loginRequestDTO.getShopId());
userDO.setUpdateTime(LocalDateTime.now());
userMapper.updateById(userDO);
}
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
LoginResponseVO responseVO = new LoginResponseVO();
responseVO.setAccessToken(accessToken);
responseVO.setRefreshToken(refreshToken);
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
userInfo.setId(userDO.getId());
userInfo.setAccount(userDO.getAccount());
userInfo.setNickname(userDO.getNickname());
userInfo.setType(userDO.getType());
userInfo.setShopId(userDO.getShopId());
userInfo.setCreateTime(userDO.getCreateTime());
responseVO.setUserInfo(userInfo);
return responseVO;
Long resolvedShopId = resolveUserLoginShopId(userDO, loginRequestDTO.getShopId());
return buildLoginResponse(userDO, resolvedShopId, false);
}
@Override
@@ -598,35 +696,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId());
} else {
assertUserAvailable(userDO);
if (userDO.getShopId() == null || userDO.getShopId() == 0) {
if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) {
throw new RuntimeException("请选择店铺");
}
userDO.setShopId(phoneLoginRequestDTO.getShopId());
userDO.setUpdateTime(LocalDateTime.now());
userMapper.updateById(userDO);
}
}
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
LoginResponseVO responseVO = new LoginResponseVO();
responseVO.setAccessToken(accessToken);
responseVO.setRefreshToken(refreshToken);
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
userInfo.setId(userDO.getId());
userInfo.setAccount(userDO.getAccount());
userInfo.setNickname(userDO.getNickname());
userInfo.setType(userDO.getType());
userInfo.setShopId(userDO.getShopId());
userInfo.setCreateTime(userDO.getCreateTime());
responseVO.setUserInfo(userInfo);
responseVO.setNeedSetPassword(ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
return responseVO;
Long resolvedShopId = resolveUserLoginShopId(userDO, phoneLoginRequestDTO.getShopId());
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
}
// 未设置密码的特殊标识
@@ -634,6 +707,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识
private UserDO registerByPhone(String phone, Long shopId) {
Long validatedShopId = validateAndNormalizeShopId(shopId);
if (validatedShopId == null) {
throw new RuntimeException("首次登录需要选择店铺");
}
UserDO userDO = new UserDO();
userDO.setAccount(phone);
userDO.setPhone(phone);
@@ -642,7 +719,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userDO.setType(0);
userDO.setLevel(VIP_LEVEL_NORMAL);
userDO.setVipId(0L);
userDO.setShopId(shopId);
userDO.setShopId(validatedShopId);
userDO.setIsDelete(0);
userDO.setStatus(1);
userDO.setCreateTime(LocalDateTime.now());
@@ -651,6 +728,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userMapper.insert(userDO);
syncDefaultPermissions(userDO.getId(), userDO.getType());
userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId));
return userDO;
}
@@ -676,30 +754,30 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
syncDefaultPermissions(userDO.getId(), userType);
Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId());
Long currentShopId = normalizeShopId(userDO.getShopId());
if (!Objects.equals(resolvedShopId, currentShopId)) {
userDO.setShopId(resolvedShopId);
userDO.setUpdateTime(LocalDateTime.now());
userMapper.updateById(userDO);
return buildLoginResponse(userDO, resolvedShopId, false);
}
@Override
public LoginResponseVO switchShop(Long userId, Long shopId) {
UserDO userDO = userMapper.selectById(userId);
assertUserAvailable(userDO);
if (userDO.getType() != null && userDO.getType() >= 2) {
throw new RuntimeException("当前账号请使用后台切换店铺");
}
Long resolvedShopId = resolveUserLoginShopId(userDO, shopId);
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
}
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount());
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount());
LoginResponseVO responseVO = new LoginResponseVO();
responseVO.setAccessToken(accessToken);
responseVO.setRefreshToken(refreshToken);
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
userInfo.setId(userDO.getId());
userInfo.setAccount(userDO.getAccount());
userInfo.setNickname(userDO.getNickname());
userInfo.setType(userDO.getType());
userInfo.setShopId(resolvedShopId);
userInfo.setCreateTime(userDO.getCreateTime());
responseVO.setUserInfo(userInfo);
return responseVO;
@Override
public LoginResponseVO switchAdminShop(Long userId, Long shopId) {
UserDO userDO = userMapper.selectById(userId);
assertUserAvailable(userDO);
Integer userType = userDO.getType();
if (userType == null || userType < 2) {
throw new RuntimeException("您没有后台管理权限");
}
Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId);
return buildLoginResponse(userDO, resolvedShopId, false);
}
private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) {
@@ -707,31 +785,36 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return null;
}
if (requestedShopId == null || requestedShopId <= 0) {
throw new RuntimeException("请选择登录店铺");
}
ShopVO shopVO = shopService.getShopById(requestedShopId);
if (shopVO == null) {
throw new RuntimeException("所选店铺不存在或已失效");
}
if (Integer.valueOf(4).equals(userDO.getType())) {
return requestedShopId;
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
if (normalizedRequestedShopId == null) {
throw new RuntimeException("请选择登录店铺");
}
if (!userShopBindingSupport.isShopActive(normalizedRequestedShopId)) {
throw new RuntimeException("所选店铺不存在或已停用");
}
return normalizedRequestedShopId;
}
Long boundShopId = normalizeShopId(userDO.getShopId());
if (boundShopId == null) {
return requestedShopId;
List<Long> activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId());
if (activeShopIds.isEmpty()) {
throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员");
}
if (!boundShopId.equals(requestedShopId)) {
throw new RuntimeException("当前账号只能选择所属店铺登录");
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
if (normalizedRequestedShopId != null) {
if (!activeShopIds.contains(normalizedRequestedShopId)) {
throw new RuntimeException("当前账号无权登录所选店铺");
}
return normalizedRequestedShopId;
}
return boundShopId;
if (activeShopIds.size() == 1) {
return activeShopIds.get(0);
}
throw new RuntimeException("请选择登录店铺");
}
private boolean hasAnyShop() {
return !shopService.listAllShops().isEmpty();
return !userShopBindingSupport.listAllActiveShopOptions().isEmpty();
}
private Long normalizeShopId(Long shopId) {
@@ -767,8 +850,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("该手机号已被注册");
}
Long validatedShopId = validateAndNormalizeShopId(registerRequestDTO.getShopId());
if (validatedShopId == null) {
throw new RuntimeException("请选择店铺");
}
UserDO userDO = new UserDO();
userDO.setShopId(registerRequestDTO.getShopId());
userDO.setShopId(validatedShopId);
userDO.setAccount(registerRequestDTO.getAccount());
userDO.setPassword(passwordEncoder.encode(registerRequestDTO.getPassword()));
userDO.setNickname(registerRequestDTO.getNickname());
@@ -783,6 +871,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userMapper.insert(userDO);
assignDefaultPermissions(userDO.getId(), userDO.getType());
userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId));
return true;
}
@@ -798,27 +887,16 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
Long userId = jwtUtil.getUserIdFromToken(refreshToken);
String account = jwtUtil.getAccountFromToken(refreshToken);
Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken));
UserDO userDO = userMapper.selectById(userId);
assertUserAvailable(userDO);
boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2;
if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) {
throw new RuntimeException("当前登录店铺已失效,请重新登录");
}
String newAccessToken = jwtUtil.generateAccessToken(userId, account);
String newRefreshToken = jwtUtil.generateRefreshToken(userId, account);
LoginResponseVO responseVO = new LoginResponseVO();
responseVO.setAccessToken(newAccessToken);
responseVO.setRefreshToken(newRefreshToken);
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
userInfo.setId(userDO.getId());
userInfo.setAccount(userDO.getAccount());
userInfo.setNickname(userDO.getNickname());
userInfo.setType(userDO.getType());
userInfo.setShopId(userDO.getShopId());
userInfo.setCreateTime(userDO.getCreateTime());
responseVO.setUserInfo(userInfo);
return responseVO;
return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
}
@Override
@@ -928,7 +1006,16 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.or().like(UserDO::getPhone, keyword));
}
if (shopId != null && shopId > 0) {
wrapper.eq(UserDO::getShopId, shopId);
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
PageResultVO<UserVO> emptyResult = new PageResultVO<>();
emptyResult.setList(List.of());
emptyResult.setTotal(0L);
emptyResult.setPage(page);
emptyResult.setSize(size);
return emptyResult;
}
wrapper.in(UserDO::getId, userIds);
}
if (type != null) {
wrapper.eq(UserDO::getType, type);
@@ -949,13 +1036,31 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
@Override
public boolean updateUserStatus(Long id, Integer status) {
UserDO userDO = userMapper.selectById(id);
if (userDO == null) {
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return false;
}
userDO.setStatus(status);
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
}
@Override
public boolean updateUserStatusInShop(Long id, Integer status, Long shopId) {
Long normalizedShopId = normalizeShopId(shopId);
if (normalizedShopId == null) {
throw new RuntimeException("当前操作缺少店铺上下文");
}
return userShopBindingSupport.updateBindingStatus(id, normalizedShopId, status);
}
@Override
public boolean deleteUserInShop(Long id, Long shopId) {
Long normalizedShopId = normalizeShopId(shopId);
if (normalizedShopId == null) {
throw new RuntimeException("当前操作缺少店铺上下文");
}
return userShopBindingSupport.deleteBinding(id, normalizedShopId);
}
@Override
public boolean updateUserAvatar(Long userId, String avatarUrl) {
@@ -1030,6 +1135,25 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return userMapper.updateById(userDO) > 0;
}
private String buildDeletedAccount(UserDO userDO) {
String suffix = userDO.getId() + "_" + System.currentTimeMillis();
String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted";
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
}
private String buildDeletedPhone(UserDO userDO) {
String suffix = userDO.getId() + "_" + System.currentTimeMillis();
String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone";
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
}
private String trimDeletedPlaceholder(String value, int maxLength) {
if (!StringUtils.hasText(value) || value.length() <= maxLength) {
return value;
}
return value.substring(value.length() - maxLength);
}
private void assertUserAvailable(UserDO userDO) {
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
throw new RuntimeException("用户不存在");
@@ -1048,12 +1172,165 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
}
private List<Long> resolveValidatedShopIds(List<Long> shopIds, Long fallbackShopId) {
LinkedHashSet<Long> resolvedShopIds = new LinkedHashSet<>();
if (shopIds != null) {
for (Long shopId : shopIds) {
Long validatedShopId = validateAndNormalizeShopId(shopId);
if (validatedShopId != null) {
resolvedShopIds.add(validatedShopId);
}
}
}
Long validatedFallbackShopId = validateAndNormalizeShopId(fallbackShopId);
if (validatedFallbackShopId != null) {
resolvedShopIds.add(validatedFallbackShopId);
}
return new ArrayList<>(resolvedShopIds);
}
private Long pickPrimaryShopId(List<Long> shopIds) {
return shopIds == null || shopIds.isEmpty() ? null : shopIds.get(0);
}
private void ensureShopBindingRequirement(Integer userType, List<Long> shopIds) {
if (Integer.valueOf(4).equals(userType)) {
return;
}
if (shopIds == null || shopIds.isEmpty()) {
throw new RuntimeException("请至少选择一个所属店铺");
}
}
private LoginShopSelectionVO buildLoginShopSelection(List<ShopSimpleVO> shops, boolean allowShoplessLogin, String message) {
LoginShopSelectionVO selectionVO = new LoginShopSelectionVO();
selectionVO.setAllowShoplessLogin(allowShoplessLogin);
selectionVO.setMessage(message);
selectionVO.setShops(shops == null ? new ArrayList<>() : new ArrayList<>(shops));
return selectionVO;
}
private String buildLoginShopMessage(List<ShopSimpleVO> shops) {
if (shops == null || shops.isEmpty()) {
return "当前暂无可选店铺";
}
if (shops.size() == 1) {
return "已匹配到 1 家可登录店铺";
}
return "该账号已绑定多家店铺,请选择本次登录店铺";
}
private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) {
Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId);
List<Long> activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId());
if (!activeShopIds.isEmpty()) {
if (normalizedRequestedShopId != null) {
if (!activeShopIds.contains(normalizedRequestedShopId)) {
throw new RuntimeException("当前账号无权登录所选店铺");
}
return normalizedRequestedShopId;
}
if (activeShopIds.size() == 1) {
return activeShopIds.get(0);
}
throw new RuntimeException("请选择登录店铺");
}
if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) {
if (normalizedRequestedShopId != null) {
userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), normalizedRequestedShopId);
return normalizedRequestedShopId;
}
Long legacyShopId = normalizeShopId(userDO.getShopId());
if (legacyShopId != null && userShopBindingSupport.isShopActive(legacyShopId)) {
userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), legacyShopId);
return legacyShopId;
}
throw new RuntimeException("请选择店铺");
}
throw new RuntimeException("当前账号没有可登录的店铺,请联系门店处理");
}
private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) {
String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount(), currentShopId);
String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount(), currentShopId);
LoginResponseVO responseVO = new LoginResponseVO();
responseVO.setAccessToken(accessToken);
responseVO.setRefreshToken(refreshToken);
responseVO.setNeedSetPassword(needSetPassword);
responseVO.setUserInfo(buildLoginUserInfo(userDO, currentShopId));
return responseVO;
}
private LoginResponseVO.UserInfo buildLoginUserInfo(UserDO userDO, Long currentShopId) {
List<ShopSimpleVO> activeShopOptions = resolveShopOptions(userDO, true, true);
Long normalizedCurrentShopId = normalizeShopId(currentShopId);
String currentShopName = activeShopOptions.stream()
.filter(shop -> Objects.equals(shop.getId(), normalizedCurrentShopId))
.map(ShopSimpleVO::getShopName)
.findFirst()
.orElseGet(() -> {
if (normalizedCurrentShopId == null) {
return null;
}
ShopVO shopVO = shopService.getShopById(normalizedCurrentShopId);
return shopVO == null ? null : shopVO.getShopName();
});
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
userInfo.setId(userDO.getId());
userInfo.setAccount(userDO.getAccount());
userInfo.setNickname(userDO.getNickname());
userInfo.setAvatar(userDO.getAvatar());
userInfo.setType(userDO.getType());
userInfo.setShopId(normalizedCurrentShopId);
userInfo.setShopName(currentShopName);
userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList()));
userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList()));
userInfo.setCreateTime(userDO.getCreateTime());
return userInfo;
}
private List<ShopSimpleVO> resolveShopOptions(UserDO userDO, boolean onlyActiveBindings, boolean onlyActiveShops) {
if (userDO == null) {
return new ArrayList<>();
}
List<ShopSimpleVO> shopOptions;
if (Integer.valueOf(4).equals(userDO.getType())) {
shopOptions = new ArrayList<>(userShopBindingSupport.listAllActiveShopOptions());
} else {
shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId(
userDO.getId(),
onlyActiveBindings,
onlyActiveShops
));
}
if (!shopOptions.isEmpty()) {
return shopOptions;
}
Long legacyShopId = normalizeShopId(userDO.getShopId());
if (legacyShopId != null) {
ShopVO legacyShop = shopService.getShopById(legacyShopId);
if (legacyShop != null && (!onlyActiveShops || Integer.valueOf(1).equals(legacyShop.getStatus()))) {
shopOptions.add(new ShopSimpleVO(legacyShop.getId(), legacyShop.getShopName()));
}
}
return shopOptions;
}
private Long validateAndNormalizeShopId(Long shopId) {
Long normalizedShopId = normalizeShopId(shopId);
if (normalizedShopId == null) {
return null;
}
if (shopService.getShopById(normalizedShopId) == null) {
if (!userShopBindingSupport.isShopActive(normalizedShopId)) {
throw new RuntimeException("所属店铺不存在或已失效");
}
return normalizedShopId;
@@ -12,6 +12,7 @@ import javax.servlet.http.HttpServletRequest;
public class AdminScopeHelper {
private final UserService userService;
private final UserShopBindingSupport userShopBindingSupport;
public UserDO getCurrentUser(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
@@ -24,6 +25,9 @@ public class AdminScopeHelper {
throw new RuntimeException("当前用户不存在或已失效");
}
Long currentShopId = RequestShopContext.getCurrentShopId(request);
currentUser.setShopId(currentShopId);
return currentUser;
}
@@ -55,6 +59,19 @@ public class AdminScopeHelper {
}
}
public void ensureUserAccessibleInCurrentShop(UserDO currentUser, Long targetUserId, String message) {
if (currentUser == null || targetUserId == null) {
throw new RuntimeException(message);
}
if (isPlatformAdmin(currentUser)) {
return;
}
Long managedShopId = getManagedShopId(currentUser);
if (!userShopBindingSupport.isUserAccessibleInShop(targetUserId, managedShopId)) {
throw new RuntimeException(message);
}
}
public void requirePlatformAdmin(UserDO currentUser, String message) {
if (!isPlatformAdmin(currentUser)) {
throw new RuntimeException(message);
@@ -0,0 +1,88 @@
package com.xiaowang.yuminailcore.support;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* 后台角色默认权限与可分配策略。
*/
public final class PermissionPolicy {
private static final List<String> ADMIN_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
"user:balance:view",
"product:view",
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
"tag:view",
"coupon:view",
"order:view",
"nail_artist:view"
);
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:reset_password", "user:delete",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:edit", "shop:staff:manage",
"permission:view", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit"
);
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"order:view", "order:process",
"nail_artist:view", "nail_artist:edit"
);
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = buildManagedDefaultPermissionCodes();
private PermissionPolicy() {
}
public static List<String> getDefaultPermissionCodes(Integer userType) {
return switch (userType == null ? -1 : userType) {
case 4 -> ADMIN_DEFAULT_PERMISSION_CODES;
case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES;
case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES;
default -> List.of();
};
}
public static Set<String> getDefaultPermissionCodeSet(Integer userType) {
return Set.copyOf(getDefaultPermissionCodes(userType));
}
public static Set<String> getManagedDefaultPermissionCodes() {
return MANAGED_DEFAULT_PERMISSION_CODES;
}
public static boolean canManageUserType(Integer operatorType, Integer targetType) {
if (operatorType == null || targetType == null) {
return false;
}
return switch (operatorType) {
case 4 -> true;
case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType);
case 3 -> Integer.valueOf(0).equals(targetType);
default -> false;
};
}
private static Set<String> buildManagedDefaultPermissionCodes() {
LinkedHashSet<String> permissionCodes = new LinkedHashSet<>();
permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES);
return Set.copyOf(permissionCodes);
}
}
@@ -0,0 +1,51 @@
package com.xiaowang.yuminailcore.support;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 当前请求中的店铺上下文。
*/
public final class RequestShopContext {
public static final String CURRENT_SHOP_ID_ATTRIBUTE = "currentShopId";
private RequestShopContext() {
}
public static Long getCurrentShopId() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return null;
}
return parseShopId(attributes.getRequest().getAttribute(CURRENT_SHOP_ID_ATTRIBUTE));
}
public static Long getCurrentShopId(HttpServletRequest request) {
if (request == null) {
return null;
}
return parseShopId(request.getAttribute(CURRENT_SHOP_ID_ATTRIBUTE));
}
private static Long parseShopId(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number number) {
long shopId = number.longValue();
return shopId > 0 ? shopId : null;
}
if (value instanceof String text) {
try {
long shopId = Long.parseLong(text.trim());
return shopId > 0 ? shopId : null;
} catch (NumberFormatException ignored) {
return null;
}
}
return null;
}
}
@@ -0,0 +1,421 @@
package com.xiaowang.yuminailcore.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.yuminailcore.entity.ShopDO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.entity.UserShopBindingDO;
import com.xiaowang.yuminailcore.mapper.ShopMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.UserShopBindingMapper;
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
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.stream.Collectors;
/**
* 用户-店铺绑定关系支撑类。
*/
@Component
@RequiredArgsConstructor
public class UserShopBindingSupport {
private final UserShopBindingMapper userShopBindingMapper;
private final ShopMapper shopMapper;
private final UserMapper userMapper;
public List<UserShopBindingDO> listBindingsByUserId(Long userId, boolean includeDeleted) {
if (userId == null) {
return List.of();
}
LambdaQueryWrapper<UserShopBindingDO> wrapper = new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, userId)
.orderByAsc(UserShopBindingDO::getCreateTime)
.orderByAsc(UserShopBindingDO::getId);
if (!includeDeleted) {
wrapper.eq(UserShopBindingDO::getIsDelete, 0);
}
return userShopBindingMapper.selectList(wrapper);
}
public boolean hasBindingHistory(Long userId) {
if (userId == null) {
return false;
}
return userShopBindingMapper.selectCount(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, userId)) > 0;
}
public List<UserShopBindingDO> listActiveBindingsByUserId(Long userId) {
return listBindingsByUserId(userId, false).stream()
.filter(binding -> Integer.valueOf(1).equals(binding.getStatus()))
.filter(binding -> isShopActive(binding.getShopId()))
.sorted(Comparator.comparing(UserShopBindingDO::getCreateTime, Comparator.nullsLast(LocalDateTime::compareTo))
.thenComparing(UserShopBindingDO::getId, Comparator.nullsLast(Long::compareTo)))
.collect(Collectors.toList());
}
public List<Long> listActiveShopIdsByUserId(Long userId) {
return listShopIdsByUserId(userId, true, true);
}
public List<ShopSimpleVO> listActiveShopOptionsByUserId(Long userId) {
return listShopOptionsByUserId(userId, true, true);
}
public List<ShopSimpleVO> listAllActiveShopOptions() {
return toShopOptions(fetchAllShopMap(true));
}
public List<Long> listShopIdsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) {
return listShopOptionsByUserId(userId, onlyActiveBindings, onlyActiveShops).stream()
.map(ShopSimpleVO::getId)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
public List<ShopSimpleVO> listShopOptionsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) {
return listShopOptionsByUserIds(List.of(userId), onlyActiveBindings, onlyActiveShops)
.getOrDefault(userId, List.of());
}
public boolean hasActiveBinding(Long userId, Long shopId) {
if (userId == null || shopId == null || shopId <= 0) {
return false;
}
return listActiveBindingsByUserId(userId).stream()
.anyMatch(binding -> shopId.equals(binding.getShopId()));
}
public boolean hasBindingInShop(Long userId, Long shopId) {
if (userId == null || shopId == null || shopId <= 0) {
return false;
}
return userShopBindingMapper.selectCount(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, userId)
.eq(UserShopBindingDO::getShopId, shopId)
.eq(UserShopBindingDO::getIsDelete, 0)) > 0;
}
public boolean isShopActive(Long shopId) {
if (shopId == null || shopId <= 0) {
return false;
}
ShopDO shopDO = shopMapper.selectById(shopId);
return shopDO != null
&& !Integer.valueOf(1).equals(shopDO.getIsDelete())
&& Integer.valueOf(1).equals(normalizeShopStatus(shopDO.getStatus()));
}
public Long pickPrimaryShopId(Long userId) {
return listActiveBindingsByUserId(userId).stream()
.map(UserShopBindingDO::getShopId)
.findFirst()
.orElse(null);
}
public Map<Long, List<ShopSimpleVO>> listActiveShopOptionsByUserIds(Collection<Long> userIds) {
return listShopOptionsByUserIds(userIds, true, true);
}
public Map<Long, List<ShopSimpleVO>> listShopOptionsByUserIds(
Collection<Long> userIds,
boolean onlyActiveBindings,
boolean onlyActiveShops
) {
if (userIds == null || userIds.isEmpty()) {
return Collections.emptyMap();
}
List<Long> normalizedUserIds = userIds.stream()
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (normalizedUserIds.isEmpty()) {
return Collections.emptyMap();
}
List<UserShopBindingDO> bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
.in(UserShopBindingDO::getUserId, normalizedUserIds)
.eq(UserShopBindingDO::getIsDelete, 0)
.orderByAsc(UserShopBindingDO::getCreateTime)
.orderByAsc(UserShopBindingDO::getId));
if (bindings.isEmpty()) {
return Collections.emptyMap();
}
if (onlyActiveBindings) {
bindings = bindings.stream()
.filter(binding -> Integer.valueOf(1).equals(binding.getStatus()))
.collect(Collectors.toList());
if (bindings.isEmpty()) {
return Collections.emptyMap();
}
}
Map<Long, ShopDO> shopMap = fetchShopMap(bindings.stream()
.map(UserShopBindingDO::getShopId)
.collect(Collectors.toSet()), onlyActiveShops);
Map<Long, List<ShopSimpleVO>> result = new LinkedHashMap<>();
for (UserShopBindingDO binding : bindings) {
ShopDO shopDO = shopMap.get(binding.getShopId());
if (shopDO == null) {
continue;
}
result.computeIfAbsent(binding.getUserId(), key -> new java.util.ArrayList<>())
.add(new ShopSimpleVO(shopDO.getId(), shopDO.getShopName()));
}
return result;
}
public List<Long> listUserIdsByShopId(Long shopId, boolean onlyActiveBindings) {
if (shopId == null || shopId <= 0) {
return List.of();
}
LambdaQueryWrapper<UserShopBindingDO> wrapper = new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getShopId, shopId)
.eq(UserShopBindingDO::getIsDelete, 0);
if (onlyActiveBindings) {
wrapper.eq(UserShopBindingDO::getStatus, 1);
}
return userShopBindingMapper.selectList(wrapper).stream()
.map(UserShopBindingDO::getUserId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
}
public long countUsersByShopId(Long shopId, boolean onlyActiveBindings) {
return listUserIdsByShopId(shopId, onlyActiveBindings).size();
}
@Transactional(rollbackFor = Exception.class)
public void ensureUserBoundToShop(Long userId, Long shopId) {
if (userId == null || shopId == null || shopId <= 0) {
throw new RuntimeException("店铺绑定信息不完整");
}
if (!isShopActive(shopId)) {
throw new RuntimeException("所选店铺不存在或已停用");
}
UserShopBindingDO existing = userShopBindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, userId)
.eq(UserShopBindingDO::getShopId, shopId)
.last("limit 1"));
if (existing == null) {
UserShopBindingDO binding = new UserShopBindingDO();
binding.setUserId(userId);
binding.setShopId(shopId);
binding.setStatus(1);
binding.setIsDelete(0);
userShopBindingMapper.insert(binding);
refreshLegacyPrimaryShop(userId);
return;
}
existing.setStatus(1);
existing.setIsDelete(0);
existing.setUpdateTime(LocalDateTime.now());
userShopBindingMapper.updateById(existing);
refreshLegacyPrimaryShop(userId);
}
@Transactional(rollbackFor = Exception.class)
public void syncUserShopBindings(Long userId, Collection<Long> shopIds) {
if (userId == null) {
return;
}
Set<Long> desiredShopIds = normalizeActiveShopIds(shopIds);
List<UserShopBindingDO> existingBindings = listBindingsByUserId(userId, true);
Map<Long, UserShopBindingDO> bindingMap = existingBindings.stream()
.filter(binding -> binding.getShopId() != null)
.collect(Collectors.toMap(UserShopBindingDO::getShopId, binding -> binding, (left, right) -> right, LinkedHashMap::new));
for (Long shopId : desiredShopIds) {
UserShopBindingDO existing = bindingMap.remove(shopId);
if (existing == null) {
UserShopBindingDO binding = new UserShopBindingDO();
binding.setUserId(userId);
binding.setShopId(shopId);
binding.setStatus(1);
binding.setIsDelete(0);
userShopBindingMapper.insert(binding);
continue;
}
existing.setStatus(1);
existing.setIsDelete(0);
existing.setUpdateTime(LocalDateTime.now());
userShopBindingMapper.updateById(existing);
}
for (UserShopBindingDO staleBinding : bindingMap.values()) {
staleBinding.setIsDelete(1);
staleBinding.setUpdateTime(LocalDateTime.now());
userShopBindingMapper.updateById(staleBinding);
}
refreshLegacyPrimaryShop(userId);
}
@Transactional(rollbackFor = Exception.class)
public boolean updateBindingStatus(Long userId, Long shopId, Integer status) {
if (userId == null || shopId == null || shopId <= 0) {
return false;
}
UserShopBindingDO binding = userShopBindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, userId)
.eq(UserShopBindingDO::getShopId, shopId)
.eq(UserShopBindingDO::getIsDelete, 0)
.last("limit 1"));
if (binding == null) {
return false;
}
binding.setStatus(Integer.valueOf(1).equals(status) ? 1 : 0);
binding.setUpdateTime(LocalDateTime.now());
userShopBindingMapper.updateById(binding);
refreshLegacyPrimaryShop(userId);
return true;
}
@Transactional(rollbackFor = Exception.class)
public boolean deleteBinding(Long userId, Long shopId) {
if (userId == null || shopId == null || shopId <= 0) {
return false;
}
UserShopBindingDO binding = userShopBindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, userId)
.eq(UserShopBindingDO::getShopId, shopId)
.eq(UserShopBindingDO::getIsDelete, 0)
.last("limit 1"));
if (binding == null) {
return false;
}
binding.setIsDelete(1);
binding.setUpdateTime(LocalDateTime.now());
userShopBindingMapper.updateById(binding);
refreshLegacyPrimaryShop(userId);
return true;
}
@Transactional(rollbackFor = Exception.class)
public void deleteBindingsByShopId(Long shopId) {
if (shopId == null || shopId <= 0) {
return;
}
List<UserShopBindingDO> bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getShopId, shopId)
.eq(UserShopBindingDO::getIsDelete, 0));
if (bindings.isEmpty()) {
return;
}
Set<Long> affectedUserIds = new LinkedHashSet<>();
for (UserShopBindingDO binding : bindings) {
binding.setIsDelete(1);
binding.setUpdateTime(LocalDateTime.now());
userShopBindingMapper.updateById(binding);
affectedUserIds.add(binding.getUserId());
}
affectedUserIds.forEach(this::refreshLegacyPrimaryShop);
}
public boolean canUserAccessShop(Long userId, Long shopId, boolean adminLogin, Integer userType) {
if (shopId == null || shopId <= 0) {
return Boolean.TRUE.equals(adminLogin)
&& Integer.valueOf(4).equals(userType)
&& listAllActiveShopOptions().isEmpty();
}
if (!isShopActive(shopId)) {
return false;
}
if (Boolean.TRUE.equals(adminLogin) && Integer.valueOf(4).equals(userType)) {
return true;
}
return hasActiveBinding(userId, shopId);
}
public boolean isUserAccessibleInShop(Long userId, Long shopId) {
return hasBindingInShop(userId, shopId);
}
private Set<Long> normalizeActiveShopIds(Collection<Long> shopIds) {
if (shopIds == null || shopIds.isEmpty()) {
return Collections.emptySet();
}
Set<Long> normalizedShopIds = new LinkedHashSet<>();
for (Long shopId : shopIds) {
if (shopId == null || shopId <= 0) {
continue;
}
if (!isShopActive(shopId)) {
throw new RuntimeException("所选店铺不存在或已停用");
}
normalizedShopIds.add(shopId);
}
return normalizedShopIds;
}
private void refreshLegacyPrimaryShop(Long userId) {
if (userId == null) {
return;
}
UserDO userDO = userMapper.selectById(userId);
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return;
}
Long primaryShopId = pickPrimaryShopId(userId);
if (Objects.equals(userDO.getShopId(), primaryShopId)) {
return;
}
userDO.setShopId(primaryShopId);
userDO.setUpdateTime(LocalDateTime.now());
userMapper.updateById(userDO);
}
private Map<Long, ShopDO> fetchAllShopMap(boolean onlyActiveShops) {
LambdaQueryWrapper<ShopDO> wrapper = new LambdaQueryWrapper<ShopDO>()
.eq(ShopDO::getIsDelete, 0);
if (onlyActiveShops) {
wrapper.eq(ShopDO::getStatus, 1);
}
return shopMapper.selectList(wrapper).stream()
.collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new));
}
private Map<Long, ShopDO> fetchShopMap(Collection<Long> shopIds, boolean onlyActiveShops) {
if (shopIds == null || shopIds.isEmpty()) {
return Collections.emptyMap();
}
LambdaQueryWrapper<ShopDO> wrapper = new LambdaQueryWrapper<ShopDO>()
.in(ShopDO::getId, shopIds)
.eq(ShopDO::getIsDelete, 0);
if (onlyActiveShops) {
wrapper.eq(ShopDO::getStatus, 1);
}
return shopMapper.selectList(wrapper)
.stream()
.collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new));
}
private List<ShopSimpleVO> toShopOptions(Map<Long, ShopDO> shopMap) {
return shopMap.values().stream()
.sorted(Comparator.comparing(ShopDO::getShopName, Comparator.nullsLast(String::compareTo))
.thenComparing(ShopDO::getId, Comparator.nullsLast(Long::compareTo)))
.map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName()))
.collect(Collectors.toList());
}
private Integer normalizeShopStatus(Integer status) {
return status == null ? 1 : status;
}
}
@@ -25,19 +25,25 @@ public class JwtUtil {
this.key = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
}
public String generateAccessToken(Long userId, String account) {
public String generateAccessToken(Long userId, String account, Long currentShopId) {
Map<String, Object> claims = new HashMap<>();
claims.put("userId", userId);
claims.put("account", account);
claims.put("type", "access");
if (currentShopId != null && currentShopId > 0) {
claims.put("shopId", currentShopId);
}
return createToken(claims, userId.toString(), ACCESS_TOKEN_EXPIRATION);
}
public String generateRefreshToken(Long userId, String account) {
public String generateRefreshToken(Long userId, String account, Long currentShopId) {
Map<String, Object> claims = new HashMap<>();
claims.put("userId", userId);
claims.put("account", account);
claims.put("type", "refresh");
if (currentShopId != null && currentShopId > 0) {
claims.put("shopId", currentShopId);
}
return createToken(claims, userId.toString(), REFRESH_TOKEN_EXPIRATION);
}
@@ -77,6 +83,28 @@ public class JwtUtil {
return claims.get("type", String.class);
}
public Long getShopIdFromToken(String token) {
Claims claims = parseToken(token);
Object value = claims.get("shopId");
if (value == null) {
return null;
}
if (value instanceof Integer integer) {
return integer.longValue();
}
if (value instanceof Long longValue) {
return longValue;
}
if (value instanceof String text) {
try {
return Long.parseLong(text);
} catch (NumberFormatException ignored) {
return null;
}
}
return null;
}
public boolean isTokenExpired(String token) {
try {
Claims claims = parseToken(token);
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 登录响应 VO
@@ -33,6 +34,10 @@ public class LoginResponseVO {
private Integer type;
@JsonSerialize(using = ToStringSerializer.class)
private Long shopId;
private String shopName;
@JsonSerialize(contentUsing = ToStringSerializer.class)
private List<Long> shopIds;
private List<String> shopNames;
private LocalDateTime createTime;
}
}
@@ -0,0 +1,19 @@
package com.xiaowang.yuminailcore.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 登录页可选店铺结果。
*/
@Data
public class LoginShopSelectionVO {
private boolean allowShoplessLogin;
private String message;
private List<ShopSimpleVO> shops = new ArrayList<>();
}
@@ -63,6 +63,11 @@ public class ShopVO {
*/
private List<String> imageUrls;
/**
* 店铺状态:1-启用,0-停用
*/
private Integer status;
/**
* 创建时间
*/
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 系统用户信息表 VO
@@ -33,6 +34,17 @@ public class UserVO {
*/
private String shopName;
/**
* 绑定店铺ID列表
*/
@JsonSerialize(contentUsing = ToStringSerializer.class)
private List<Long> shopIds;
/**
* 绑定店铺名称列表
*/
private List<String> shopNames;
/**
* 用户昵称
*/
@@ -0,0 +1,165 @@
-- 2026-03-25 多店铺登录 / 店铺状态 / 用户店铺绑定补丁
-- 推荐执行顺序:
-- 1. YumiNail.sql
-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql
-- 3. 2026-03-25_user_shop_binding_and_shop_status_patch.sql
-- 4. 2026-03-20_init_admin_permission_template.sql
--
-- 说明:
-- 1. 本文件不覆盖主建表 SQL,只补结构与历史数据回填。
-- 2. 本补丁会新增 t_user_shop_binding,并把现有 t_user.shop_id 回填为默认绑定关系。
-- 3. t_shop.status 用于店铺启停;停用后不删除绑定,只禁止该店铺登录。
use nailart;
SET NAMES utf8mb4;
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
p_definition
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_columns TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ',
p_columns
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_columns TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
p_columns
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用''');
UPDATE t_shop
SET status = 1
WHERE status IS NULL;
CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)');
CREATE TABLE IF NOT EXISTS `t_user_shop_binding` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID',
`user_id` bigint unsigned NOT NULL COMMENT '用户ID',
`shop_id` bigint unsigned NOT NULL COMMENT '店铺ID',
`status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (`id`)
) COMMENT='用户与店铺绑定关系表';
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用''');
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间''');
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间''');
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删''');
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)');
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)');
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)');
CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)');
INSERT INTO t_user_shop_binding (
user_id,
shop_id,
status,
create_time,
update_time,
is_delete
)
SELECT
u.id,
u.shop_id,
CASE
WHEN COALESCE(u.status, 1) = 1 THEN 1
ELSE 0
END AS binding_status,
COALESCE(u.create_time, NOW()),
COALESCE(u.update_time, NOW()),
0
FROM t_user u
INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0
LEFT JOIN t_user_shop_binding b
ON b.user_id = u.id
AND b.shop_id = u.shop_id
AND COALESCE(b.is_delete, 0) = 0
WHERE COALESCE(u.is_delete, 0) = 0
AND u.shop_id IS NOT NULL
AND u.shop_id > 0
AND b.id IS NULL;
UPDATE t_user_shop_binding b
INNER JOIN t_user u ON u.id = b.user_id
SET b.status = CASE
WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END
ELSE b.status
END,
b.is_delete = COALESCE(b.is_delete, 0),
b.update_time = COALESCE(b.update_time, NOW())
WHERE b.status IS NULL
OR b.is_delete IS NULL
OR b.update_time IS NULL;
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
@@ -1,4 +1,9 @@
create database nailart;
-- YumiNail 首次部署主 SQL
-- 说明:
-- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、VIP 规则、admin01 初始化与默认权限分配。
-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、
-- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。
-- 3. 如果你的数据库名不是 nailart,请先将本文件中的 `use nailart;` 改成实际库名后再执行。
use nailart;
-- auto-generated definition
@@ -551,5 +556,702 @@ create index idx_user_id
on t_wishlist (user_id)
comment '按用户查询收藏的索引';
-- ========================================
-- 首次部署整合区:用户资产 / VIP / 优惠券补丁
-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql
-- ========================================
SET NAMES utf8mb4;
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
p_definition
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_columns TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ',
p_columns
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_columns TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
p_columns
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
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 ''最近一次充值时间''');
UPDATE t_balance
SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00)
WHERE total_recharge_amount IS NULL;
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注''');
UPDATE t_balance_change_detail
SET before_balance = COALESCE(before_balance, current_balance - amount),
after_balance = COALESCE(after_balance, current_balance),
change_scene = COALESCE(NULLIF(change_scene, ''), type)
WHERE before_balance IS NULL
OR after_balance IS NULL
OR change_scene IS NULL
OR change_scene = '';
CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)');
CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)');
CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID''');
CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID''');
CALL sp_add_column_if_not_exists('t_order', 'coupon_source_type', 'varchar(32) NULL COMMENT ''优惠来源类型''');
UPDATE t_order
SET coupon_id = NULL
WHERE coupon_id = 0;
UPDATE t_order o
INNER JOIN (
SELECT oi.order_id, MIN(p.shop_id) AS resolved_shop_id
FROM t_order_item oi
INNER JOIN t_product p ON p.id = oi.product_id
GROUP BY oi.order_id
) detail_shop ON detail_shop.order_id = o.id
SET o.shop_id = detail_shop.resolved_shop_id
WHERE o.shop_id IS NULL;
UPDATE t_order
SET coupon_source_type = 'USER_COUPON'
WHERE coupon_source_type IS NULL
AND coupon_id IS NOT NULL;
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_shop_id', '(`shop_id`)');
CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_coupon_source_type', '(`coupon_source_type`)');
CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间''');
CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)');
CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景''');
CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级''');
CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配''');
UPDATE t_coupon
SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'),
auto_match = COALESCE(auto_match, 0)
WHERE coupon_scene IS NULL
OR coupon_scene = ''
OR auto_match IS NULL;
CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)');
CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)');
CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号''');
CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛''');
CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态''');
UPDATE t_vip_benefit
SET level_rank = CASE required_vip_level
WHEN '普通' THEN 0
WHEN '青铜' THEN 1
WHEN '白银' THEN 2
WHEN '黄金' THEN 3
ELSE level_rank
END,
recharge_threshold = CASE required_vip_level
WHEN '普通' THEN 0.00
WHEN '青铜' THEN 500.00
WHEN '白银' THEN 1000.00
WHEN '黄金' THEN 2000.00
ELSE recharge_threshold
END,
status = COALESCE(status, 1)
WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金');
CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)');
CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID''');
CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级''');
ALTER TABLE t_vip_info
MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间',
MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键';
UPDATE t_vip_info vi
INNER JOIN t_user u ON u.vip_id = vi.id
SET vi.user_id = u.id
WHERE (vi.user_id IS NULL OR vi.user_id = 0)
AND u.vip_id IS NOT NULL
AND u.vip_id <> 0;
UPDATE t_vip_info
SET start_time = COALESCE(start_time, create_time, NOW()),
activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'),
manual_override = COALESCE(manual_override, 0);
CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)');
CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)');
UPDATE t_user u
LEFT JOIN t_vip_info vi ON vi.id = u.vip_id
SET u.level = CASE
WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level
WHEN u.type = 0 THEN '普通'
ELSE u.level
END,
u.vip_id = CASE
WHEN u.type = 0 AND u.vip_id IS NULL THEN 0
ELSE u.vip_id
END,
u.update_time = NOW()
WHERE u.is_delete = 0
AND u.type = 0
AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL);
UPDATE t_vip_benefit
SET benefit_info = '普通用户,无额外VIP折扣',
level_rank = 0,
recharge_threshold = 0.00,
status = 1,
update_time = NOW()
WHERE required_vip_level = '普通';
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW()
WHERE NOT EXISTS (
SELECT 1
FROM t_vip_benefit
WHERE required_vip_level = '普通'
);
UPDATE t_vip_benefit
SET benefit_info = '青铜VIP,系统自动匹配9.5折券',
level_rank = 1,
recharge_threshold = 500.00,
status = 1,
update_time = NOW()
WHERE required_vip_level = '青铜';
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW()
WHERE NOT EXISTS (
SELECT 1
FROM t_vip_benefit
WHERE required_vip_level = '青铜'
);
UPDATE t_vip_benefit
SET benefit_info = '白银VIP,系统自动匹配9.2折券',
level_rank = 2,
recharge_threshold = 1000.00,
status = 1,
update_time = NOW()
WHERE required_vip_level = '白银';
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW()
WHERE NOT EXISTS (
SELECT 1
FROM t_vip_benefit
WHERE required_vip_level = '白银'
);
UPDATE t_vip_benefit
SET benefit_info = '黄金VIP,系统自动匹配9.0折券',
level_rank = 3,
recharge_threshold = 2000.00,
status = 1,
update_time = NOW()
WHERE required_vip_level = '黄金';
INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time)
SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW()
WHERE NOT EXISTS (
SELECT 1
FROM t_vip_benefit
WHERE required_vip_level = '黄金'
);
INSERT INTO t_coupon (
coupon_code,
coupon_name,
coupon_type,
discount_value,
min_amount,
reduce_amount,
total_count,
used_count,
start_time,
end_time,
status,
create_time,
update_time,
is_delete,
shop_id,
coupon_scene,
required_vip_level,
auto_match
)
VALUES
('VIP_AUTO_BRONZE_95', '青铜VIP自动95折券', 1, 9.50, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '青铜', 1),
('VIP_AUTO_SILVER_92', '白银VIP自动92折券', 1, 9.20, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '白银', 1),
('VIP_AUTO_GOLD_90', '黄金VIP自动90折券', 1, 9.00, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '黄金', 1)
ON DUPLICATE KEY UPDATE
coupon_name = VALUES(coupon_name),
coupon_type = VALUES(coupon_type),
discount_value = VALUES(discount_value),
min_amount = VALUES(min_amount),
reduce_amount = VALUES(reduce_amount),
total_count = VALUES(total_count),
status = VALUES(status),
is_delete = VALUES(is_delete),
shop_id = VALUES(shop_id),
coupon_scene = VALUES(coupon_scene),
required_vip_level = VALUES(required_vip_level),
auto_match = VALUES(auto_match),
update_time = NOW();
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
-- ========================================
-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁
-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql
-- ========================================
SET NAMES utf8mb4;
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_column_name VARCHAR(64),
IN p_definition TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND COLUMN_NAME = p_column_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ',
p_definition
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_columns TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ',
p_columns
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE sp_add_unique_index_if_not_exists(
IN p_table_name VARCHAR(64),
IN p_index_name VARCHAR(64),
IN p_columns TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table_name
AND INDEX_NAME = p_index_name
) THEN
SET @sql = CONCAT(
'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ',
p_columns
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用''');
UPDATE t_shop
SET status = 1
WHERE status IS NULL;
CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)');
CREATE TABLE IF NOT EXISTS `t_user_shop_binding` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID',
`user_id` bigint unsigned NOT NULL COMMENT '用户ID',
`shop_id` bigint unsigned NOT NULL COMMENT '店铺ID',
`status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删',
PRIMARY KEY (`id`)
) COMMENT='用户与店铺绑定关系表';
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用''');
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间''');
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间''');
CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删''');
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)');
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)');
CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)');
CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)');
INSERT INTO t_user_shop_binding (
user_id,
shop_id,
status,
create_time,
update_time,
is_delete
)
SELECT
u.id,
u.shop_id,
CASE
WHEN COALESCE(u.status, 1) = 1 THEN 1
ELSE 0
END AS binding_status,
COALESCE(u.create_time, NOW()),
COALESCE(u.update_time, NOW()),
0
FROM t_user u
INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0
LEFT JOIN t_user_shop_binding b
ON b.user_id = u.id
AND b.shop_id = u.shop_id
AND COALESCE(b.is_delete, 0) = 0
WHERE COALESCE(u.is_delete, 0) = 0
AND u.shop_id IS NOT NULL
AND u.shop_id > 0
AND b.id IS NULL;
UPDATE t_user_shop_binding b
INNER JOIN t_user u ON u.id = b.user_id
SET b.status = CASE
WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END
ELSE b.status
END,
b.is_delete = COALESCE(b.is_delete, 0),
b.update_time = COALESCE(b.update_time, NOW())
WHERE b.status IS NULL
OR b.is_delete IS NULL
OR b.update_time IS NULL;
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
-- ========================================
-- 首次部署整合区:权限种子 / admin01 初始化 / 默认权限分配
-- 来源:2026-03-20_init_admin_permission_template.sql
-- ========================================
SET NAMES utf8mb4;
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
VALUES
('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0),
('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0),
('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0),
('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0),
('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0),
('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0),
('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0),
('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0),
('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0),
('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0),
('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0),
('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0),
('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0),
('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0),
('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0),
('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0),
('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0),
('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0),
('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0),
('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0),
('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0),
('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0),
('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0),
('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0),
('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0),
('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0),
('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0),
('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0),
('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0),
('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0),
('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0),
('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0),
('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0),
('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0),
('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0),
('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0),
('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0),
('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0),
('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0),
('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0),
('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0),
('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', 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,
account,
phone_verified,
email_verified,
password,
signature,
level,
type,
vip_id,
create_time,
update_time,
is_delete,
status
)
SELECT
0,
'系统管理员',
'admin01',
0,
0,
'$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W',
'',
'管理员',
4,
0,
NOW(),
NOW(),
0,
1
WHERE NOT EXISTS (
SELECT 1
FROM t_user
WHERE account = 'admin01'
);
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
AND p.permission_code IN (
'home:view',
'dashboard:view',
'user:view',
'user:create',
'user:edit',
'user:disable',
'user:reset_password',
'user:delete',
'user:balance:view',
'product:view',
'shop:view',
'shop:create',
'shop:edit',
'shop:delete',
'shop:staff:manage',
'permission:view',
'permission:create',
'permission:edit',
'permission:delete',
'permission:assign',
'tag:view',
'coupon:view',
'order:view',
'nail_artist:view'
)
WHERE u.is_delete = 0
AND u.type = 4
AND NOT EXISTS (
SELECT 1
FROM t_user_permission up
WHERE up.user_id = u.id
AND up.permission_id = p.id
);
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
AND p.permission_code IN (
'home:view',
'dashboard:view',
'user:view',
'user:create',
'user:edit',
'user:disable',
'user:reset_password',
'user:delete',
'user:balance:view',
'user:balance:manage',
'user:vip:manage',
'product:view',
'product:create',
'product:edit',
'product:delete',
'product:category:manage',
'shop:view',
'shop:edit',
'shop:staff:manage',
'permission:view',
'permission:assign',
'tag:view',
'tag:create',
'tag:edit',
'tag:delete',
'tag:assign',
'coupon:view',
'coupon:create',
'coupon:edit',
'coupon:delete',
'coupon:assign',
'order:view',
'order:process',
'order:edit',
'order:delete',
'nail_artist:view',
'nail_artist:edit'
)
WHERE u.is_delete = 0
AND u.type = 2
AND NOT EXISTS (
SELECT 1
FROM t_user_permission up
WHERE up.user_id = u.id
AND up.permission_id = p.id
);
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
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',
'order:view'
)
WHERE u.is_delete = 0
AND u.type = 3
AND NOT EXISTS (
SELECT 1
FROM t_user_permission up
WHERE up.user_id = u.id
AND up.permission_id = p.id
);