From b8327146cb8ebd7108b1ed808ae44a1d31360a47 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Mon, 26 Oct 2026 01:19:23 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84Salon=E5=90=8E=E5=8F=B0?= =?UTF-8?q?=E5=8D=95=E7=AE=A1=E7=90=86=E5=91=98=E4=B8=8E=E7=BB=8F=E8=90=A5?= =?UTF-8?q?=E9=A9=BE=E9=A9=B6=E8=88=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../salon/core/aspect/PermissionAspect.java | 9 + .../salon/core/config/AuthInterceptor.java | 28 +- .../salon/core/config/WebMvcConfig.java | 1 - .../controller/front/DashboardController.java | 164 +++ .../mapper/SalonDashboardMapper.java | 42 + .../vo/SalonDashboardOverviewVO.java | 72 + .../controller/admin/AdminAuthController.java | 50 +- .../dto/AdminPasswordChangeRequestDTO.java | 20 + .../admin/AdminAccountSecurityService.java | 57 + .../modules/user/service/UserService.java | 9 + .../user/service/impl/UserServiceImpl.java | 33 +- JC-Salon-Frontend/src/api/admin.ts | 130 +- JC-Salon-Frontend/src/api/auth-free-paths.ts | 2 - .../src/config/admin-navigation.test.ts | 11 +- .../src/config/admin-navigation.ts | 22 +- JC-Salon-Frontend/src/router/index.ts | 13 +- .../src/utils/admin-auth-bootstrap.test.ts | 45 + .../src/utils/admin-auth-bootstrap.ts | 135 +- JC-Salon-Frontend/src/utils/admin-session.ts | 23 +- .../src/utils/permission.test.ts | 29 + JC-Salon-Frontend/src/utils/permission.ts | 27 +- .../src/views/admin/AdminLayout.vue | 1224 +---------------- .../src/views/admin/AdminLoginView.vue | 528 +------ .../src/views/admin/DashboardView.vue | 1088 --------------- .../src/views/admin/HomeView.vue | 488 ------- .../src/views/admin/ManageView.vue | 396 ------ .../src/views/admin/ProfileView.vue | 184 ++- .../src/views/admin/SalonDashboardView.vue | 214 +++ .../src/views/admin/SystemSettingsView.vue | 83 +- .../src/views/admin/admin-helpers.ts | 45 - .../tests/api/auth-free-paths.test.ts | 2 +- .../tests/api/vnext-api-contracts.test.ts | 7 +- ...25-salon后台单管理员与经营驾驶舱-design.md | 31 + docs/后台残留清理记录.md | 23 + docs/项目变更记录.md | 10 + 35 files changed, 1087 insertions(+), 4158 deletions(-) create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java create mode 100644 JC-Salon-Frontend/src/utils/admin-auth-bootstrap.test.ts create mode 100644 JC-Salon-Frontend/src/utils/permission.test.ts delete mode 100644 JC-Salon-Frontend/src/views/admin/DashboardView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/HomeView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/ManageView.vue create mode 100644 JC-Salon-Frontend/src/views/admin/SalonDashboardView.vue delete mode 100644 JC-Salon-Frontend/src/views/admin/admin-helpers.ts create mode 100644 docs/superpowers/specs/2026-10-25-salon后台单管理员与经营驾驶舱-design.md create mode 100644 docs/后台残留清理记录.md diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java index 47955e0f..fd9885f8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java @@ -79,6 +79,15 @@ public class PermissionAspect { return Result.error(404, "用户不存在"); } + // Salon 后台只有平台管理员,登录后台后的数据范围统一为全平台。 + // 权限表继续保留给小程序和兼容接口使用,但不再阻断管理员后台请求。 + String requestPath = request.getRequestURI(); + boolean adminPath = requestPath != null + && (requestPath.startsWith("/admin/") || requestPath.startsWith("/order/admin/")); + if (adminPath && Integer.valueOf(4).equals(userDO.getType())) { + return joinPoint.proceed(); + } + String permissionCode = requirePermission.value(); Long currentShopId = parseShopId(request.getAttribute("currentShopId")); if (Integer.valueOf(4).equals(userDO.getType()) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java index a5c15828..4fb2635a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java @@ -117,10 +117,13 @@ public class AuthInterceptor implements HandlerInterceptor { } boolean adminPath = isAdminPath(path); - if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限"); + if (adminPath && !Integer.valueOf(4).equals(currentUser.getType())) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "仅平台管理员可以访问后台管理系统"); return false; } + if (adminPath && Integer.valueOf(4).equals(currentUser.getType())) { + currentShopId = null; + } boolean canAccessShop = userShopBindingSupport.canUserAccessShop( userId, @@ -139,14 +142,6 @@ public class AuthInterceptor implements HandlerInterceptor { return false; } - if (adminPath - && !Integer.valueOf(4).equals(currentUser.getType()) - && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) - && !isExpiredAdminAllowedPath(path)) { - writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员"); - return false; - } - if (requiresSignature(request)) { try { requestSignatureService.validateRequest(request, token, userId); @@ -205,19 +200,6 @@ public class AuthInterceptor implements HandlerInterceptor { return path.startsWith("/admin/") || path.startsWith("/order/admin/"); } - /** - * Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - private boolean isExpiredAdminAllowedPath(String path) { - return path.startsWith("/admin/auth/") - || path.equals("/admin/user/info") - || path.equals("/permission/list/user/current") - || path.equals("/api/permission/list/user/current") - || path.startsWith("/admin/planning/") - || path.startsWith("/admin/shops/"); - } - /** * Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java index f2cd1642..64d4bb98 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java @@ -73,7 +73,6 @@ public class WebMvcConfig implements WebMvcConfigurer { "/tag/list/filter-options", "/file/get-signed-url/**", "/admin/auth/login", - "/admin/auth/login-shops/**", "/admin/auth/refresh", "/error", "/health/**" diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java index 1c15872b..7912bae6 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java @@ -15,6 +15,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.analytics.service.OperationsAnalyticsService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; @@ -25,16 +26,35 @@ import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.DashboardStatsVO; import com.xiaowang.jayucloud.salon.core.modules.product.vo.HotProductVO; import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.OperationsAnalyticsVO; import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.RecentActivityVO; +import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.SalonDashboardOverviewVO; +import com.xiaowang.jayucloud.salon.core.modules.analytics.mapper.SalonDashboardMapper; +import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus; +import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.AfterSaleDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistChangeRequestDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.AfterSaleMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistChangeRequestMapper; +import com.xiaowang.jayucloud.salon.core.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.salon.core.modules.inventory.entity.InventoryItemDO; +import com.xiaowang.jayucloud.salon.core.modules.inventory.mapper.InventoryItemMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.time.Duration; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -44,6 +64,7 @@ import java.util.stream.Collectors; @RestController @RequestMapping("/admin/dashboard") @RequiredArgsConstructor +@Slf4j /** * DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. @@ -90,6 +111,149 @@ public class DashboardController { */ private final AppCacheProperties appCacheProperties; private final OperationsAnalyticsService operationsAnalyticsService; + private final WorkbenchRegistrationApplicationMapper registrationMapper; + private final ContentModerationRecordMapper contentModerationRecordMapper; + private final AfterSaleMapper afterSaleMapper; + private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + private final AppointmentReservationMapper appointmentReservationMapper; + private final InventoryItemMapper inventoryItemMapper; + private final SalonDashboardMapper salonDashboardMapper; + + /** + * Salon 平台管理员专用驾驶舱。旧 stats/analytics 接口保留兼容,但首页只使用本接口。 + */ + @GetMapping("/overview") + public Result getOverview( + @RequestParam(required = false) String date, + @RequestParam(required = false, defaultValue = "7") Integer days) { + LocalDate targetDate = parseOverviewDate(date); + int rangeDays = days != null && days == 30 ? 30 : 7; + try { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard(); + String cacheKey = "cache:salon-dashboard:overview:" + targetDate + ":" + rangeDays; + return Result.success(multiLevelCacheService.getOrLoad( + cacheKey, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { }, + () -> buildSalonOverview(targetDate, rangeDays) + )); + } catch (Exception exception) { + log.warn("Salon 驾驶舱统计失败,返回空数据: date={}, days={}", targetDate, rangeDays, exception); + SalonDashboardOverviewVO empty = emptySalonOverview(targetDate, rangeDays); + empty.setDegraded(true); + empty.setDegradedMessage("部分经营数据暂时不可用,刷新后重试"); + return Result.success(empty); + } + } + + private LocalDate parseOverviewDate(String value) { + if (value == null || value.isBlank()) return LocalDate.now(); + try { + return LocalDate.parse(value); + } catch (DateTimeParseException exception) { + return LocalDate.now(); + } + } + + private SalonDashboardOverviewVO emptySalonOverview(LocalDate date, int days) { + SalonDashboardOverviewVO overview = new SalonDashboardOverviewVO(); + overview.setDate(date.toString()); + for (int index = days - 1; index >= 0; index--) { + SalonDashboardOverviewVO.TrendItem item = new SalonDashboardOverviewVO.TrendItem(); + item.setDate(date.minusDays(index).toString()); + overview.getTrend().add(item); + } + return overview; + } + + private SalonDashboardOverviewVO buildSalonOverview(LocalDate date, int days) { + SalonDashboardOverviewVO overview = emptySalonOverview(date, days); + SalonDashboardOverviewVO.Platform platform = overview.getPlatform(); + platform.setActiveShopCount(shopMapper.selectCount(new LambdaQueryWrapper() + .eq(ShopDO::getStatus, 1).eq(ShopDO::getIsDelete, 0))); + platform.setActiveManagerCount(countUsersByType(2)); + platform.setActiveStaffCount(countUsersByType(3)); + platform.setCustomerCount(countUsersByType(0)); + platform.setStyleCount(productMapper.selectCount(new LambdaQueryWrapper() + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, 1) + .eq(ProductDO::getModerationStatus, "APPROVED"))); + + LocalDate rangeStart = date.minusDays(days - 1); + List> trendRows = salonDashboardMapper.selectOrderTrend(rangeStart, date); + Map trendByDate = overview.getTrend().stream() + .collect(Collectors.toMap(SalonDashboardOverviewVO.TrendItem::getDate, item -> item, (left, right) -> left, LinkedHashMap::new)); + for (Map row : trendRows) { + String rowDate = stringValue(row, "date"); + SalonDashboardOverviewVO.TrendItem item = trendByDate.get(rowDate); + if (item == null) continue; + item.setAppointmentCount(longValue(row, "appointmentCount")); + item.setCompletedCount(longValue(row, "completedCount")); + item.setAmount(decimalValue(row, "amount")); + if (date.equals(LocalDate.parse(rowDate))) { + overview.getToday().setServiceInProgressCount(longValue(row, "serviceInProgressCount")); + overview.getToday().setPendingOrderCount(longValue(row, "pendingOrderCount")); + overview.getToday().setCompletedServiceCount(longValue(row, "completedCount")); + overview.getToday().setOrderAmount(decimalValue(row, "amount")); + overview.getToday().setAppointmentCount(longValue(row, "appointmentCount")); + } + } + List ranking = new ArrayList<>(); + for (Map row : salonDashboardMapper.selectShopRanking(rangeStart, date)) { + SalonDashboardOverviewVO.ShopRankingItem item = new SalonDashboardOverviewVO.ShopRankingItem(); + item.setShopId(numberValue(row, "shopId")); + item.setShopName(stringValue(row, "shopName")); + item.setAppointmentCount(longValue(row, "appointmentCount")); + item.setCompletedCount(longValue(row, "completedCount")); + item.setAmount(decimalValue(row, "amount")); + ranking.add(item); + } + overview.setShopRanking(ranking); + + overview.getAttention().setRegistrationReviewCount(registrationMapper.selectCount(new LambdaQueryWrapper() + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .in(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN, WorkbenchRegistrationStatus.PENDING_MANAGER))); + overview.getAttention().setContentReviewCount(contentModerationRecordMapper.selectCount(new LambdaQueryWrapper() + .in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY"))); + overview.getAttention().setAfterSaleCount(afterSaleMapper.selectCount(new LambdaQueryWrapper() + .eq(AfterSaleDO::getIsDelete, 0).eq(AfterSaleDO::getStatus, "PENDING"))); + overview.getAttention().setArtistChangeCount(orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper() + .eq(OrderArtistChangeRequestDO::getIsDelete, 0).eq(OrderArtistChangeRequestDO::getStatus, "PENDING"))); + overview.getAttention().setLowStockCount(inventoryItemMapper.selectCount(new LambdaQueryWrapper() + .eq(InventoryItemDO::getIsDelete, 0) + .apply("stock_quantity <= warning_threshold"))); + return overview; + } + + private String stringValue(Map row, String key) { + Object value = row.get(key); + return value == null ? "" : value.toString(); + } + + private long longValue(Map row, String key) { + Object value = row.get(key); + return value instanceof Number ? ((Number) value).longValue() : 0L; + } + + private Long numberValue(Map row, String key) { + Object value = row.get(key); + return value instanceof Number ? ((Number) value).longValue() : null; + } + + private BigDecimal decimalValue(Map row, String key) { + Object value = row.get(key); + if (value instanceof BigDecimal) return (BigDecimal) value; + if (value instanceof Number) return BigDecimal.valueOf(((Number) value).doubleValue()); + return BigDecimal.ZERO; + } + + private long countUsersByType(int type) { + return userMapper.selectCount(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getType, type) + .eq(UserDO::getStatus, 1)); + } @GetMapping("/stats") @RequirePermission("dashboard:view") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java new file mode 100644 index 00000000..83647b03 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java @@ -0,0 +1,42 @@ +package com.xiaowang.jayucloud.salon.core.modules.analytics.mapper; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +/** Salon 驾驶舱趋势和门店排行聚合查询。 */ +@Mapper +public interface SalonDashboardMapper { + + String BUSINESS_ORDERS = "(SELECT o.id, o.shop_id, o.status, o.order_source, " + + "CASE WHEN o.order_source = 'HISTORICAL_BACKFILL' " + + "THEN COALESCE(item.service_date, DATE(o.create_time)) " + + "ELSE COALESCE(DATE(item.appointment_time), DATE(o.create_time)) END AS business_date, " + + "item.appointment_time, COALESCE(o.actual_amount, o.total_amount, 0) AS amount " + + "FROM t_order o LEFT JOIN (SELECT order_id, MIN(appointment_time) AS appointment_time, " + + "MIN(service_date) AS service_date FROM t_order_item WHERE is_delete = 0 GROUP BY order_id) item " + + "ON item.order_id = o.id WHERE o.is_delete = 0 AND o.status <> 3)"; + + @Select("SELECT DATE_FORMAT(business_date, '%Y-%m-%d') AS date, " + + "SUM(CASE WHEN order_source <> 'HISTORICAL_BACKFILL' AND appointment_time IS NOT NULL AND status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, " + + "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS completedCount, " + + "SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS serviceInProgressCount, " + + "SUM(CASE WHEN status IN (0, 1) THEN 1 ELSE 0 END) AS pendingOrderCount, " + + "SUM(amount) AS amount FROM " + BUSINESS_ORDERS + " business_orders" + + " WHERE business_date BETWEEN #{startDate} AND #{endDate} GROUP BY business_date ORDER BY business_date") + List> selectOrderTrend(@Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + @Select("SELECT s.id AS shopId, s.shop_name AS shopName, " + + "SUM(CASE WHEN o.order_source <> 'HISTORICAL_BACKFILL' AND o.appointment_time IS NOT NULL AND o.status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, " + + "SUM(CASE WHEN o.status = 2 THEN 1 ELSE 0 END) AS completedCount, SUM(o.amount) AS amount " + + "FROM " + BUSINESS_ORDERS + " o JOIN t_shop s ON s.id = o.shop_id AND s.is_delete = 0 " + + "WHERE o.business_date BETWEEN #{startDate} AND #{endDate} " + + "GROUP BY s.id, s.shop_name ORDER BY amount DESC LIMIT 10") + List> selectShopRanking(@Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java new file mode 100644 index 00000000..ebecd94d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java @@ -0,0 +1,72 @@ +package com.xiaowang.jayucloud.salon.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * Salon 平台管理员驾驶舱数据。 + * 该 VO 只包含 Salon 经营口径,不复用 ArtList 的流量和电商指标。 + */ +@Data +public class SalonDashboardOverviewVO { + private String date; + private boolean degraded; + private String degradedMessage; + private Platform platform = new Platform(); + private Today today = new Today(); + private Attention attention = new Attention(); + private List trend = new ArrayList<>(); + private List shopRanking = new ArrayList<>(); + + @Data + public static class Platform { + private long activeShopCount; + private long activeManagerCount; + private long activeStaffCount; + private long customerCount; + private long styleCount; + } + + @Data + public static class Today { + private long appointmentCount; + private long serviceInProgressCount; + private long completedServiceCount; + private BigDecimal orderAmount = BigDecimal.ZERO; + private long pendingOrderCount; + } + + @Data + public static class Attention { + private long registrationReviewCount; + private long contentReviewCount; + private long afterSaleCount; + private long artistChangeCount; + private long lowStockCount; + + public long total() { + return registrationReviewCount + contentReviewCount + afterSaleCount + + artistChangeCount + lowStockCount; + } + } + + @Data + public static class TrendItem { + private String date; + private long appointmentCount; + private long completedCount; + private BigDecimal amount = BigDecimal.ZERO; + } + + @Data + public static class ShopRankingItem { + private Long shopId; + private String shopName; + private long appointmentCount; + private long completedCount; + private BigDecimal amount = BigDecimal.ZERO; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/controller/admin/AdminAuthController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/controller/admin/AdminAuthController.java index 6bc9c6c8..78a6ee18 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/controller/admin/AdminAuthController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/controller/admin/AdminAuthController.java @@ -3,15 +3,13 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.auth.dto.LoginRequestDTO; -import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningManagerRegisterDTO; import com.xiaowang.jayucloud.salon.core.modules.auth.dto.RefreshTokenRequestDTO; -import com.xiaowang.jayucloud.salon.core.modules.auth.dto.SwitchShopRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.auth.service.admin.AdminAccountSecurityService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy; -import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils; -import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @@ -40,6 +38,7 @@ public class AdminAuthController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final SecurityAuditLogService securityAuditLogService; + private final AdminAccountSecurityService adminAccountSecurityService; @PostMapping("/login") @OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") @@ -64,37 +63,6 @@ public class AdminAuthController { } } - @PostMapping("/register") - @OperationGuard(action = "admin-planning-register", ttlSeconds = 10, message = "注册处理中,请勿重复提交") - public Result register(@RequestBody PlanningManagerRegisterDTO registerDTO) { - return Result.success(userService.registerPlanningManager(registerDTO)); - } - - @GetMapping("/login-shops/{account}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getLoginShops(@PathVariable String account) { - return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account))); - } - - @PostMapping("/switch-shop") - @OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") - /** - * Run business method `switchShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); - } - @PostMapping("/logout") @OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) /** @@ -115,10 +83,9 @@ public class AdminAuthController { * @return Result result consumed by the caller or returned to the frontend */ public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { - LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); + LoginResponseVO loginResponseVO = userService.adminRefreshToken(refreshTokenRequestDTO.getRefreshToken()); if (loginResponseVO.getUserInfo() == null - || loginResponseVO.getUserInfo().getType() == null - || loginResponseVO.getUserInfo().getType() < 2) { + || !Integer.valueOf(4).equals(loginResponseVO.getUserInfo().getType())) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -128,4 +95,11 @@ public class AdminAuthController { } return Result.success(loginResponseVO); } + + @PostMapping("/password") + public Result changePassword(HttpServletRequest request, + @Valid @RequestBody AdminPasswordChangeRequestDTO passwordChangeRequest) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(adminAccountSecurityService.changePassword(userId, passwordChangeRequest)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java new file mode 100644 index 00000000..1b9a7ebf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.auth.dto; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Getter +@Setter +public class AdminPasswordChangeRequestDTO { + + @NotBlank(message = "当前密码不能为空") + @Size(max = 128, message = "当前密码长度不能超过 128 位") + private String currentPassword; + + @NotBlank(message = "新密码不能为空") + @Size(max = 128, message = "新密码长度不能超过 128 位") + private String newPassword; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java new file mode 100644 index 00000000..84ed1de5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java @@ -0,0 +1,57 @@ +package com.xiaowang.jayucloud.salon.core.modules.auth.service.admin; + +import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +@Service +@RequiredArgsConstructor +public class AdminAccountSecurityService { + + private final UserMapper userMapper; + private final UserSessionService userSessionService; + private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + + @Transactional(rollbackFor = Exception.class) + public boolean changePassword(Long userId, AdminPasswordChangeRequestDTO request) { + if (userId == null || request == null) { + throw new RuntimeException("管理员账号信息无效"); + } + + UserDO admin = userMapper.selectById(userId); + if (admin == null || Integer.valueOf(1).equals(admin.getIsDelete())) { + throw new RuntimeException("管理员账号不存在或已失效"); + } + if (!Integer.valueOf(4).equals(admin.getType())) { + throw new RuntimeException("仅平台管理员可以修改后台密码"); + } + if (!Integer.valueOf(1).equals(admin.getStatus())) { + throw new RuntimeException("管理员账号已被禁用"); + } + if (!StringUtils.hasText(request.getCurrentPassword()) + || !passwordEncoder.matches(request.getCurrentPassword(), admin.getPassword())) { + throw new RuntimeException("当前密码不正确"); + } + + String newPassword = request.getNewPassword(); + AdminDefaultPasswordSupport.validatePasswordStrength(newPassword); + if (passwordEncoder.matches(newPassword, admin.getPassword())) { + throw new RuntimeException("新密码不能与当前密码相同"); + } + + admin.setPassword(passwordEncoder.encode(newPassword)); + if (userMapper.updateById(admin) <= 0) { + throw new RuntimeException("密码保存失败,请重试"); + } + + userSessionService.revokeAllUserSessions(userId); + return true; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java index dae79625..18ae6605 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java @@ -208,6 +208,15 @@ public interface UserService extends IService { */ LoginResponseVO refreshToken(String refreshToken); + /** + * Refresh a token for the platform administrator console. + * + *

This is deliberately separate from the user-facing refresh flow so + * the admin controller cannot accidentally change the rules used by the + * mini-program and front-end sessions.

+ */ + LoginResponseVO adminRefreshToken(String refreshToken); + /** * Run business method `logout`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index ffe5a56d..fb870c3d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -1365,6 +1365,10 @@ public class UserServiceImpl extends ServiceImpl implements */ assertLoginAccountAvailable(userDO); + if (!Integer.valueOf(4).equals(userDO.getType())) { + throw new RuntimeException("仅平台管理员可以登录后台管理系统"); + } + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { /** * Run business method `handleLoginPasswordFailure`. @@ -1375,17 +1379,6 @@ public class UserServiceImpl extends ServiceImpl implements handleLoginPasswordFailure(userDO); } - Integer userType = userDO.getType(); - if (userType == null || userType < 2) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号不是后台管理账号"); - } - - Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); clearLoginFailureCount(userDO.getAccount()); /** * Run business method `buildLoginResponse`. @@ -1395,7 +1388,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param false parameter `false` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + return buildLoginResponse(userDO, null, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); } @Override @@ -1693,6 +1686,15 @@ public class UserServiceImpl extends ServiceImpl implements * @return LoginResponseVO result consumed by the caller or returned to the frontend */ public LoginResponseVO refreshToken(String refreshToken) { + return refreshTokenInternal(refreshToken, false); + } + + @Override + public LoginResponseVO adminRefreshToken(String refreshToken) { + return refreshTokenInternal(refreshToken, true); + } + + private LoginResponseVO refreshTokenInternal(String refreshToken, boolean adminOnly) { if (!jwtUtil.validateToken(refreshToken)) { /** * Run business method `RuntimeException`. @@ -1715,7 +1717,7 @@ public class UserServiceImpl extends ServiceImpl implements Long userId = jwtUtil.getUserIdFromToken(refreshToken); String account = jwtUtil.getAccountFromToken(refreshToken); - Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); + Long currentShopId = adminOnly ? null : normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); String refreshJti = jwtUtil.getJtiFromToken(refreshToken); if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { @@ -1735,7 +1737,10 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ assertUserAvailable(userDO); - boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + if (adminOnly && !Integer.valueOf(4).equals(userDO.getType())) { + throw new RuntimeException("仅平台管理员可以刷新后台登录态"); + } + boolean adminLogin = adminOnly || (userDO.getType() != null && userDO.getType() >= 2); if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { /** * Run business method `RuntimeException`. diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 513a1297..18764bd0 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -247,7 +247,6 @@ adminApi.interceptors.response.use( export interface AdminLoginRequest { account: string password: string - shopId?: IdType } /** @@ -260,19 +259,15 @@ export interface AdminLoginResponse { userInfo: any } +export interface AdminPasswordChangeRequest { + currentPassword: string + newPassword: string +} + /** * Purpose: LoginShopSelectionResponse supports admin.ts by holding or executing the login shop selection response page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ -export interface LoginShopSelectionResponse { - allowShoplessLogin: boolean - message: string - shops: Array<{ - id: IdType - shopName: string - }> -} - /** * Purpose: LegalAgreementAdminVO supports admin.ts by holding or executing the legal agreement admin vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -315,14 +310,6 @@ export const adminAuthApi = { login: (data: AdminLoginRequest) => { return adminApi.post('/auth/login', data) }, - /** - * `getLoginShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param account: string caller-supplied value for `account: string` - */ - getLoginShops: (account: string) => { - return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) - }, /** * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -330,14 +317,6 @@ export const adminAuthApi = { logout: () => { return adminApi.post('/auth/logout') }, - /** - * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - switchShop: (shopId?: IdType) => { - return adminApi.post('/auth/switch-shop', { shopId }) - }, /** * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -345,6 +324,9 @@ export const adminAuthApi = { */ refreshToken: (refreshToken: string) => { return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }) + }, + changePassword: (data: AdminPasswordChangeRequest) => { + return adminApi.post('/auth/password', data) } } @@ -1115,16 +1097,33 @@ export interface CampaignRequest { sortOrder?: number } -export interface OperationsAnalyticsVO { - viewCount?: number - favoriteCount?: number - cartCount?: number - orderCount?: number - paidOrderCount?: number - completedOrderCount?: number - reviewCount?: number - rebookCount?: number - totalAmount?: number +export interface SalonDashboardOverviewVO { + date: string + degraded?: boolean + degradedMessage?: string + platform: { + activeShopCount: number + activeManagerCount: number + activeStaffCount: number + customerCount: number + styleCount: number + } + today: { + appointmentCount: number + serviceInProgressCount: number + completedServiceCount: number + orderAmount: number + pendingOrderCount: number + } + attention: { + registrationReviewCount: number + contentReviewCount: number + afterSaleCount: number + artistChangeCount: number + lowStockCount: number + } + trend: Array<{ date: string; appointmentCount: number; completedCount: number; amount: number }> + shopRanking: Array<{ shopId: IdType; shopName: string; appointmentCount: number; completedCount: number; amount: number }> } export const adminArtistScheduleApi = { @@ -1482,68 +1481,13 @@ export const adminOrderApi = { } } -/** - * Purpose: HotProductVO supports admin.ts by holding or executing the hot product vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface HotProductVO { - id: IdType - title: string - price: number - likeCount: number - collectCount: number -} - -/** - * Purpose: RecentActivityVO supports admin.ts by holding or executing the recent activity vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface RecentActivityVO { - id: IdType - type: string - title?: string - description: string - time: string - color?: string -} - -/** - * Purpose: DashboardStats supports admin.ts by holding or executing the dashboard stats page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface DashboardStats { - totalUsers: number - totalProducts: number - totalShops: number - todayOrders: number - totalOrderAmount?: number - todayOrderAmount?: number - weekOrderAmount?: number - totalCustomers?: number - totalArtists?: number - newCustomersToday?: number - newCustomers7Days?: number - newOrders7Days?: number - pendingOrders?: number - completedOrders?: number - hotProducts: HotProductVO[] - recentActivities: RecentActivityVO[] -} - /** * adminDashboardApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. */ export const adminDashboardApi = { - /** - * `getStats` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - getStats: () => { - return adminApi.get('/dashboard/stats') - }, - getAnalytics: () => { - return adminApi.get('/dashboard/analytics') as unknown as Promise + getOverview: (params?: { date?: string; days?: 7 | 30 }) => { + return adminApi.get('/dashboard/overview', { params }) as unknown as Promise } } diff --git a/JC-Salon-Frontend/src/api/auth-free-paths.ts b/JC-Salon-Frontend/src/api/auth-free-paths.ts index 6bee7e67..8b45d59c 100644 --- a/JC-Salon-Frontend/src/api/auth-free-paths.ts +++ b/JC-Salon-Frontend/src/api/auth-free-paths.ts @@ -26,7 +26,6 @@ export const WEB_API_AUTH_FREE_PATHS = [ '/tag/list/filter-options', '/file/get-signed-url/', '/admin/auth/login', - '/admin/auth/login-shops/', '/admin/auth/refresh' ] as const @@ -36,7 +35,6 @@ export const WEB_API_AUTH_FREE_PATHS = [ */ export const ADMIN_API_AUTH_FREE_PATHS = [ '/auth/login', - '/auth/login-shops/', '/auth/refresh' ] as const diff --git a/JC-Salon-Frontend/src/config/admin-navigation.test.ts b/JC-Salon-Frontend/src/config/admin-navigation.test.ts index db26d732..0c32588c 100644 --- a/JC-Salon-Frontend/src/config/admin-navigation.test.ts +++ b/JC-Salon-Frontend/src/config/admin-navigation.test.ts @@ -1,12 +1,15 @@ import { describe, expect, it } from 'vitest' -import { adminNavigationItems, adminPermissionRouteMap, findAdminNavigationItemByPath, ADMIN_DASHBOARD_PATH } from './admin-navigation' +import { adminNavigationItems, findAdminNavigationItemByPath, ADMIN_DASHBOARD_PATH } from './admin-navigation' describe('admin-navigation', () => { - it('keeps dashboard landing and permission routes aligned', () => { + it('exposes a fixed Salon management menu without permission-based filtering', () => { expect(ADMIN_DASHBOARD_PATH).toBe('/admin') - expect(findAdminNavigationItemByPath('/admin/shops')?.label).toBe('店铺管理') + expect(findAdminNavigationItemByPath('/admin/shops')?.label).toBe('门店管理') expect(findAdminNavigationItemByPath('/admin/products')).toBeUndefined() - expect(adminPermissionRouteMap.some(item => item.code === 'shop:view' && item.path === '/admin/shops')).toBe(true) expect(adminNavigationItems[0]?.path).toBe('/admin') + expect(adminNavigationItems.map(item => item.label)).toEqual([ + '首页', '账号管理', '注册审核', '隐私与内容复核', '门店管理', '系统设置', '个人设置' + ]) + expect(adminNavigationItems.every(item => !('permissionCode' in item))).toBe(true) }) }) diff --git a/JC-Salon-Frontend/src/config/admin-navigation.ts b/JC-Salon-Frontend/src/config/admin-navigation.ts index af03c423..ad62f4c7 100644 --- a/JC-Salon-Frontend/src/config/admin-navigation.ts +++ b/JC-Salon-Frontend/src/config/admin-navigation.ts @@ -16,28 +16,20 @@ export interface AdminNavigationItem { path: string iconKey: AdminNavIconKey label: string - permissionCode: string } export const ADMIN_HOME_PATH = '/admin' export const ADMIN_DASHBOARD_PATH = ADMIN_HOME_PATH export const adminNavigationItems: AdminNavigationItem[] = [ - { path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' }, - { path: '/admin/users', iconKey: 'user', label: '店长账号', permissionCode: 'user:view' }, - { path: '/admin/registrations', iconKey: 'team', label: '注册审核', permissionCode: 'user:view' }, - { path: '/admin/privacy', iconKey: 'security', label: '隐私与内容复核', permissionCode: 'legal_agreement:manage' }, - { path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' }, - { path: '/admin/settings', iconKey: 'tool', label: '系统设置', permissionCode: 'messagehub:config:manage' }, - { path: '/admin/profile', iconKey: 'user', label: '个人设置', permissionCode: '' } + { path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页' }, + { path: '/admin/users', iconKey: 'user', label: '账号管理' }, + { path: '/admin/registrations', iconKey: 'team', label: '注册审核' }, + { path: '/admin/privacy', iconKey: 'security', label: '隐私与内容复核' }, + { path: '/admin/shops', iconKey: 'home', label: '门店管理' }, + { path: '/admin/settings', iconKey: 'tool', label: '系统设置' }, + { path: '/admin/profile', iconKey: 'user', label: '个人设置' } ] -export const adminPermissionRouteMap = adminNavigationItems - .filter(item => item.permissionCode) - .map(item => ({ - code: item.permissionCode, - path: item.path - })) - export const findAdminNavigationItemByPath = (path: string) => adminNavigationItems.find(item => item.path === path) diff --git a/JC-Salon-Frontend/src/router/index.ts b/JC-Salon-Frontend/src/router/index.ts index e94e2a83..cd906ef7 100644 --- a/JC-Salon-Frontend/src/router/index.ts +++ b/JC-Salon-Frontend/src/router/index.ts @@ -8,9 +8,10 @@ import { } from '@/utils/admin-auth-bootstrap' const pageNames = [ - ['', 'HomeView', 'admin', undefined], - ['users', 'UsersView', 'admin-users', 'user:view'], ['registrations', 'WorkbenchRegistrationView', 'admin-registrations', 'user:view'], ['privacy', 'PrivacyComplianceView', 'admin-privacy', 'legal_agreement:manage'], ['shops', 'ShopsView', 'admin-shops', 'shop:view'], - ['profile', 'ProfileView', 'admin-profile', undefined], ['settings', 'SystemSettingsView', 'admin-settings', 'messagehub:config:manage'] + ['', 'SalonDashboardView', 'admin'], + ['users', 'UsersView', 'admin-users'], ['registrations', 'WorkbenchRegistrationView', 'admin-registrations'], ['privacy', 'PrivacyComplianceView', 'admin-privacy'], ['shops', 'ShopsView', 'admin-shops'], + ['profile', 'ProfileView', 'admin-profile'], ['settings', 'SystemSettingsView', 'admin-settings'], + ['orders', 'OrdersView', 'admin-orders'], ['after-sales', 'AfterSalesView', 'admin-after-sales'], ['inventory', 'InventoryView', 'admin-inventory'] ] as const const routes = [ @@ -18,8 +19,8 @@ const routes = [ { path: '/admin/login', name: 'admin-login', component: () => import('../views/admin/AdminLoginView.vue'), meta: { requiresAuth: false, isAdmin: true, hideNav: true } }, { path: '/admin', component: () => import('../views/admin/AdminLayout.vue'), meta: { requiresAuth: true, isAdmin: true, hideNav: true }, - children: pageNames.map(([path, view, name, permissionCode]) => ({ - path, name, component: () => import(`../views/admin/${view}.vue`), meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode } + children: pageNames.map(([path, view, name]) => ({ + path, name, component: () => import(`../views/admin/${view}.vue`), meta: { requiresAuth: true, isAdmin: true, hideNav: true } })) }, { path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('../views/NotFoundView.vue'), meta: { requiresAuth: false, isAdmin: false, hideNav: true } } @@ -43,7 +44,7 @@ router.beforeEach(async to => { return '/admin/login' } if (await ensureAdminAuthBootstrap() !== 'ready') return '/admin/login' - return canAccessAdminRoute(to.path, to.meta.permissionCode as string | undefined) ? true : resolveAdminLandingPath() + return canAccessAdminRoute(to.path) ? true : resolveAdminLandingPath() }) export default router diff --git a/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.test.ts b/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.test.ts new file mode 100644 index 00000000..98628684 --- /dev/null +++ b/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.test.ts @@ -0,0 +1,45 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { + canAccessAdminRoute, + clearAdminBootstrapSession, + ensureAdminAuthBootstrap, + getAdminBootstrapSnapshot, + resolveAdminLandingPath +} from './admin-auth-bootstrap' + +describe('admin-auth-bootstrap', () => { + beforeEach(() => { + localStorage.clear() + sessionStorage.clear() + }) + + it('lets a platform administrator enter any admin route without permission data', async () => { + localStorage.setItem('adminAccessToken', 'admin-token') + localStorage.setItem('adminUserInfo', JSON.stringify({ id: 1, type: 4 })) + + expect(getAdminBootstrapSnapshot().permissions).toEqual([]) + expect(await ensureAdminAuthBootstrap()).toBe('ready') + expect(canAccessAdminRoute('/admin/inventory')).toBe(true) + expect(canAccessAdminRoute('/admin-elsewhere')).toBe(false) + expect(resolveAdminLandingPath()).toBe('/admin') + }) + + it('clears a non-admin session instead of allowing backend access', async () => { + localStorage.setItem('adminAccessToken', 'shop-token') + localStorage.setItem('adminUserInfo', JSON.stringify({ id: 2, type: 2 })) + + expect(await ensureAdminAuthBootstrap()).toBe('invalid') + expect(canAccessAdminRoute('/admin')).toBe(false) + expect(localStorage.getItem('adminAccessToken')).toBeNull() + }) + + it('clears the current administrator session on logout', () => { + localStorage.setItem('adminAccessToken', 'admin-token') + localStorage.setItem('adminUserInfo', JSON.stringify({ id: 1, type: 4 })) + + clearAdminBootstrapSession() + + expect(getAdminBootstrapSnapshot().token).toBeNull() + expect(getAdminBootstrapSnapshot().userInfo).toBeNull() + }) +}) diff --git a/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.ts b/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.ts index 524b832d..409e8773 100644 --- a/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.ts +++ b/JC-Salon-Frontend/src/utils/admin-auth-bootstrap.ts @@ -2,165 +2,48 @@ import { computed, ref } from 'vue' import { clearAdminSessionStorage, getAdminAccessToken, - isBootstrapAdminUser, loadCachedAdminUserInfo, } from '@/utils/admin-session' -import { ADMIN_DASHBOARD_PATH, adminPermissionRouteMap } from '@/config/admin-navigation' -import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions' -import { - clearStoredPermissions, - fetchUserPermissionsStrict, - getStoredUserPermissions, -} from '@/utils/permission' - -/** - * Purpose: AuthBootstrapState supports admin-auth-bootstrap.ts by holding or executing the auth bootstrap state page or API role. - * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. - */ export type AuthBootstrapState = 'pending' | 'ready' | 'invalid' -/** - * Purpose: adminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the admin bootstrap state page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ const adminBootstrapState = ref('pending') -let bootstrapPromise: Promise | null = null - -/** - * Purpose: useAdminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the use admin bootstrap state page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ export const useAdminBootstrapState = () => computed(() => adminBootstrapState.value) -/** - * Purpose: invalidateAdminBootstrap supports admin-auth-bootstrap.ts by holding or executing the invalidate admin bootstrap page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ export const invalidateAdminBootstrap = () => { adminBootstrapState.value = 'pending' - bootstrapPromise = null } -/** - * Purpose: clearAdminBootstrapSession supports admin-auth-bootstrap.ts by holding or executing the clear admin bootstrap session page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ export const clearAdminBootstrapSession = () => { clearAdminSessionStorage() - clearStoredPermissions() adminBootstrapState.value = 'invalid' - bootstrapPromise = null } -/** - * Purpose: getAdminBootstrapSnapshot supports admin-auth-bootstrap.ts by holding or executing the get admin bootstrap snapshot page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ export const getAdminBootstrapSnapshot = () => { const userInfo = loadCachedAdminUserInfo() return { token: getAdminAccessToken(), userInfo, - isBootstrapAdmin: isBootstrapAdminUser(userInfo), isPlatformAdmin: Number(userInfo?.type) === 4, - permissions: getStoredUserPermissions() || [], + isBootstrapAdmin: Number(userInfo?.type) === 4, + permissions: [] as string[], } } -/** - * Purpose: hasAdminPermission supports admin-auth-bootstrap.ts by holding or executing the has admin permission page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -export const hasAdminPermission = (permissionCode?: string) => { - if (!permissionCode) { - return true - } +export const resolveAdminLandingPath = () => '/admin' +export const canAccessAdminRoute = (path: string) => { const snapshot = getAdminBootstrapSnapshot() - if (snapshot.isBootstrapAdmin || (snapshot.isPlatformAdmin && isAllowedForShoplessPlatformAdmin(permissionCode))) { - return isAllowedForShoplessPlatformAdmin(permissionCode) - } - - return snapshot.permissions.includes(permissionCode) + return Boolean(snapshot.token && snapshot.isPlatformAdmin && (path === '/admin' || path.startsWith('/admin/'))) } -/** - * Purpose: resolveAdminLandingPath supports admin-auth-bootstrap.ts by holding or executing the resolve admin landing path page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -export const resolveAdminLandingPath = () => { +export const ensureAdminAuthBootstrap = async (): Promise => { const snapshot = getAdminBootstrapSnapshot() - if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) { - return '/admin' - } - if (snapshot.isBootstrapAdmin) { - return ADMIN_DASHBOARD_PATH - } - - const matchedRoute = adminPermissionRouteMap.find(item => snapshot.permissions.includes(item.code)) - return matchedRoute?.path || '/admin' -} - -/** - * Purpose: canAccessAdminRoute supports admin-auth-bootstrap.ts by holding or executing the can access admin route page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -export const canAccessAdminRoute = (path: string, permissionCode?: string) => { - const snapshot = getAdminBootstrapSnapshot() - if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) { - return path === '/admin' || path === '/admin/profile' - } - if (snapshot.isBootstrapAdmin) { - return hasAdminPermission(permissionCode) - } - - return hasAdminPermission(permissionCode) -} - -/** - * Purpose: ensureAdminAuthBootstrap supports admin-auth-bootstrap.ts by holding or executing the ensure admin auth bootstrap page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -export const ensureAdminAuthBootstrap = async (force = false): Promise => { - const snapshot = getAdminBootstrapSnapshot() - if (!snapshot.token || !snapshot.userInfo) { + if (!snapshot.token || !snapshot.isPlatformAdmin) { clearAdminBootstrapSession() return 'invalid' } - - if (snapshot.isBootstrapAdmin) { - clearStoredPermissions() - adminBootstrapState.value = 'ready' - bootstrapPromise = null - return 'ready' - } - - const cachedPermissions = getStoredUserPermissions() - if (!force && cachedPermissions) { - adminBootstrapState.value = 'ready' - return 'ready' - } - - if (!force && bootstrapPromise) { - return bootstrapPromise - } - - adminBootstrapState.value = 'pending' - bootstrapPromise = (async () => { - try { - await fetchUserPermissionsStrict() - adminBootstrapState.value = 'ready' - return 'ready' as AuthBootstrapState - } catch (error) { - console.error('Failed to bootstrap admin permissions:', error) - clearAdminBootstrapSession() - return 'invalid' as AuthBootstrapState - } finally { - bootstrapPromise = null - } - })() - - return bootstrapPromise + adminBootstrapState.value = 'ready' + return 'ready' } diff --git a/JC-Salon-Frontend/src/utils/admin-session.ts b/JC-Salon-Frontend/src/utils/admin-session.ts index 58b7285a..3a701c43 100644 --- a/JC-Salon-Frontend/src/utils/admin-session.ts +++ b/JC-Salon-Frontend/src/utils/admin-session.ts @@ -1,21 +1,13 @@ -import type { IdType } from '@/utils/id' - /** * Purpose: AdminCachedUserInfo supports admin-session.ts by holding or executing the admin cached user info page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface AdminCachedUserInfo { - id?: IdType + id?: string | number type?: number account?: string nickname?: string avatar?: string - shopId?: IdType - shopName?: string - shopAuthorizationExpireTime?: string - shopAuthorizationExpired?: boolean - shopIds?: IdType[] - shopNames?: string[] } /** @@ -51,19 +43,6 @@ export const loadCachedAdminUserInfo = (): AdminCachedUserInfo | null => { } } -/** - * Purpose: isBootstrapAdminUser supports admin-session.ts by holding or executing the is bootstrap admin user page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -export const isBootstrapAdminUser = (userInfo?: AdminCachedUserInfo | null) => - userInfo?.type === 4 && !userInfo?.shopId - -/** - * Purpose: isPlatformOverviewAdminUser supports admin-session.ts by holding or executing the is platform overview admin user page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -export const isPlatformOverviewAdminUser = isBootstrapAdminUser - /** * Purpose: clearAdminSessionStorage supports admin-session.ts by holding or executing the clear admin session storage page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. diff --git a/JC-Salon-Frontend/src/utils/permission.test.ts b/JC-Salon-Frontend/src/utils/permission.test.ts new file mode 100644 index 00000000..5fbdd863 --- /dev/null +++ b/JC-Salon-Frontend/src/utils/permission.test.ts @@ -0,0 +1,29 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { permissionApi } from '@/api/permission' +import { fetchUserPermissionsStrict, setStoredUserPermissions, usePermission } from './permission' + +describe('admin permission compatibility', () => { + beforeEach(() => { + localStorage.clear() + sessionStorage.clear() + }) + + it('allows platform administrators without loading or storing permission records', async () => { + localStorage.setItem('adminUserInfo', JSON.stringify({ id: 1, type: 4 })) + const loadPermissions = vi.spyOn(permissionApi, 'getUserPermissions') + + expect(usePermission().hasPermission('any:unconfigured:permission')).toBe(true) + expect(await fetchUserPermissionsStrict()).toEqual([]) + expect(loadPermissions).not.toHaveBeenCalled() + expect(localStorage.getItem('userPermissions')).toBe('[]') + }) + + it('keeps permission checks for non-administrator users', () => { + localStorage.setItem('adminUserInfo', JSON.stringify({ id: 2, type: 2 })) + setStoredUserPermissions(['shop:view']) + + const permissions = usePermission() + expect(permissions.hasPermission('shop:view')).toBe(true) + expect(permissions.hasPermission('shop:delete')).toBe(false) + }) +}) diff --git a/JC-Salon-Frontend/src/utils/permission.ts b/JC-Salon-Frontend/src/utils/permission.ts index afdc5b26..948b7476 100644 --- a/JC-Salon-Frontend/src/utils/permission.ts +++ b/JC-Salon-Frontend/src/utils/permission.ts @@ -1,7 +1,6 @@ import { permissionApi } from '@/api/permission' import { computed, ref } from 'vue' -import { isBootstrapAdminUser, loadCachedAdminUserInfo } from '@/utils/admin-session' -import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions' +import { loadCachedAdminUserInfo } from '@/utils/admin-session' /** * Purpose: USER_PERMISSIONS_STORAGE_KEY supports permission.ts by holding or executing the user permissions storage key page or API role. @@ -76,6 +75,9 @@ export const clearStoredPermissions = () => { * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ export const fetchUserPermissionsStrict = async () => { + if (isPlatformAdminUser()) { + return setStoredUserPermissions([]) + } loadingPermissions.value = true try { const permissions = await permissionApi.getUserPermissions() @@ -95,32 +97,17 @@ export const fetchUserPermissionsStrict = async () => { */ export const usePermission = () => { const hasPermission = (permissionCode: string) => { - if (isBootstrapAdminUser(loadCachedAdminUserInfo())) { - return isAllowedForShoplessPlatformAdmin(permissionCode) - } - if (isPlatformAdminUser() && isAllowedForShoplessPlatformAdmin(permissionCode)) { - return isAllowedForShoplessPlatformAdmin(permissionCode) - } + if (isPlatformAdminUser()) return true return userPermissions.value.includes(permissionCode) } const hasAnyPermission = (permissionCodes: string[]) => { - if (isBootstrapAdminUser(loadCachedAdminUserInfo())) { - return permissionCodes.some(isAllowedForShoplessPlatformAdmin) - } - if (isPlatformAdminUser() && permissionCodes.some(isAllowedForShoplessPlatformAdmin)) { - return permissionCodes.some(isAllowedForShoplessPlatformAdmin) - } + if (isPlatformAdminUser()) return true return permissionCodes.some(code => userPermissions.value.includes(code)) } const hasAllPermissions = (permissionCodes: string[]) => { - if (isBootstrapAdminUser(loadCachedAdminUserInfo())) { - return permissionCodes.every(isAllowedForShoplessPlatformAdmin) - } - if (isPlatformAdminUser() && permissionCodes.every(isAllowedForShoplessPlatformAdmin)) { - return permissionCodes.every(isAllowedForShoplessPlatformAdmin) - } + if (isPlatformAdminUser()) return true return permissionCodes.every(code => userPermissions.value.includes(code)) } diff --git a/JC-Salon-Frontend/src/views/admin/AdminLayout.vue b/JC-Salon-Frontend/src/views/admin/AdminLayout.vue index e1da87ef..84c67520 100644 --- a/JC-Salon-Frontend/src/views/admin/AdminLayout.vue +++ b/JC-Salon-Frontend/src/views/admin/AdminLayout.vue @@ -1,1178 +1,104 @@