重构Salon后台单管理员与经营驾驶舱

This commit is contained in:
2026-10-26 01:19:23 +08:00
parent 17cf16db36
commit b8327146cb
35 changed files with 1087 additions and 4158 deletions
@@ -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())
@@ -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.
@@ -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/**"
@@ -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<SalonDashboardOverviewVO> 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<SalonDashboardOverviewVO>() { },
() -> 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<ShopDO>()
.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<ProductDO>()
.eq(ProductDO::getIsDelete, 0)
.eq(ProductDO::getFrontVisible, 1)
.eq(ProductDO::getModerationStatus, "APPROVED")));
LocalDate rangeStart = date.minusDays(days - 1);
List<Map<String, Object>> trendRows = salonDashboardMapper.selectOrderTrend(rangeStart, date);
Map<String, SalonDashboardOverviewVO.TrendItem> trendByDate = overview.getTrend().stream()
.collect(Collectors.toMap(SalonDashboardOverviewVO.TrendItem::getDate, item -> item, (left, right) -> left, LinkedHashMap::new));
for (Map<String, Object> 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<SalonDashboardOverviewVO.ShopRankingItem> ranking = new ArrayList<>();
for (Map<String, Object> 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<WorkbenchRegistrationApplicationDO>()
.eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0)
.in(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN, WorkbenchRegistrationStatus.PENDING_MANAGER)));
overview.getAttention().setContentReviewCount(contentModerationRecordMapper.selectCount(new LambdaQueryWrapper<ContentModerationRecordDO>()
.in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY")));
overview.getAttention().setAfterSaleCount(afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
.eq(AfterSaleDO::getIsDelete, 0).eq(AfterSaleDO::getStatus, "PENDING")));
overview.getAttention().setArtistChangeCount(orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
.eq(OrderArtistChangeRequestDO::getIsDelete, 0).eq(OrderArtistChangeRequestDO::getStatus, "PENDING")));
overview.getAttention().setLowStockCount(inventoryItemMapper.selectCount(new LambdaQueryWrapper<InventoryItemDO>()
.eq(InventoryItemDO::getIsDelete, 0)
.apply("stock_quantity <= warning_threshold")));
return overview;
}
private String stringValue(Map<String, Object> row, String key) {
Object value = row.get(key);
return value == null ? "" : value.toString();
}
private long longValue(Map<String, Object> row, String key) {
Object value = row.get(key);
return value instanceof Number ? ((Number) value).longValue() : 0L;
}
private Long numberValue(Map<String, Object> row, String key) {
Object value = row.get(key);
return value instanceof Number ? ((Number) value).longValue() : null;
}
private BigDecimal decimalValue(Map<String, Object> 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<UserDO>()
.eq(UserDO::getIsDelete, 0)
.eq(UserDO::getType, type)
.eq(UserDO::getStatus, 1));
}
@GetMapping("/stats")
@RequirePermission("dashboard:view")
@@ -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<Map<String, Object>> 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<Map<String, Object>> selectShopRanking(@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
}
@@ -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<TrendItem> trend = new ArrayList<>();
private List<ShopRankingItem> 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;
}
}
@@ -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<LoginResponseVO> 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<LoginShopSelectionVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginShopSelectionVO> 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<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> 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<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> 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<Boolean> changePassword(HttpServletRequest request,
@Valid @RequestBody AdminPasswordChangeRequestDTO passwordChangeRequest) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(adminAccountSecurityService.changePassword(userId, passwordChangeRequest));
}
}
@@ -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;
}
@@ -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;
}
}
@@ -208,6 +208,15 @@ public interface UserService extends IService<UserDO> {
*/
LoginResponseVO refreshToken(String refreshToken);
/**
* Refresh a token for the platform administrator console.
*
* <p>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.</p>
*/
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.
@@ -1365,6 +1365,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> 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<UserMapper, UserDO> 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<UserMapper, UserDO> 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<UserMapper, UserDO> 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<UserMapper, UserDO> 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<UserMapper, UserDO> 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`.
+37 -93
View File
@@ -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<AdminLoginResponse>('/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<LoginShopSelectionResponse>(`/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<boolean>('/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<AdminLoginResponse>('/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<boolean>('/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<DashboardStats>('/dashboard/stats')
},
getAnalytics: () => {
return adminApi.get<OperationsAnalyticsVO>('/dashboard/analytics') as unknown as Promise<OperationsAnalyticsVO>
getOverview: (params?: { date?: string; days?: 7 | 30 }) => {
return adminApi.get<SalonDashboardOverviewVO>('/dashboard/overview', { params }) as unknown as Promise<SalonDashboardOverviewVO>
}
}
@@ -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
@@ -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)
})
})
@@ -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)
+7 -6
View File
@@ -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
@@ -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()
})
})
@@ -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<AuthBootstrapState>('pending')
let bootstrapPromise: Promise<AuthBootstrapState> | 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<AuthBootstrapState> => {
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<AuthBootstrapState> => {
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'
}
+1 -22
View File
@@ -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.
@@ -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)
})
})
+7 -20
View File
@@ -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))
}
File diff suppressed because it is too large Load Diff
@@ -1,514 +1,78 @@
<template>
<div class="admin-login">
<div class="login-container">
<div class="login-header">
<h1>后台管理系统</h1>
<p>欢迎回来,请登录您的账户</p>
</div>
<main class="salon-admin-login">
<section class="login-panel">
<div class="brand-mark">S</div>
<p class="eyebrow">SALON PLATFORM</p>
<h1>Salon 管理驾驶舱</h1>
<p class="intro">平台管理员专用入口,统一查看门店经营与运营事项。</p>
<a-card class="login-card">
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleLogin"
>
<a-alert
v-if="loginShopMessage"
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
show-icon
:message="loginShopMessage"
style="margin-bottom: 16px"
/>
<a-form :model="formState" :rules="formRules" layout="vertical" @finish="handleLogin">
<a-form-item label="管理员账号" name="account">
<a-input v-model:value="formState.account" size="large" autocomplete="username" placeholder="请输入管理员账号" />
</a-form-item>
<a-form-item label="登录密码" name="password">
<a-input-password v-model:value="formState.password" size="large" autocomplete="current-password" placeholder="请输入登录密码" />
</a-form-item>
<a-button type="primary" size="large" html-type="submit" block :loading="loading">进入管理后台</a-button>
</a-form>
<a-form-item label="用户名" name="account">
<a-input
v-model:value="formState.account"
size="large"
placeholder="请输入用户名"
:prefix-icon="UserOutlined"
@input="handleAccountInput"
/>
</a-form-item>
<a-form-item label="密码" name="password">
<a-input-password
v-model:value="formState.password"
size="large"
placeholder="请输入密码"
:prefix-icon="LockOutlined"
@pressEnter="handleLogin"
/>
</a-form-item>
<a-form-item v-if="hasAvailableShops || !allowShoplessLogin" label="登录店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
size="large"
:placeholder="shopPlaceholder"
:loading="shopLoading"
:options="shopOptions"
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
show-search
:filter-option="filterShopOption"
/>
</a-form-item>
<a-form-item>
<a-button
type="primary"
size="large"
html-type="submit"
:loading="loading"
block
>
登录
</a-button>
</a-form-item>
</a-form>
<div class="login-footer">
<a @click="goToFrontend">返回前台</a>
</div>
</a-card>
</div>
</div>
</section>
</main>
</template>
<script setup lang="ts">
/**
* AdminLoginView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
/**
* Purpose: LoginShopSelectionResponse supports AdminLoginView.vue by holding or executing the login shop selection response 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.
*/
import { adminAuthApi, type LoginShopSelectionResponse } from '@/api/admin'
import { adminAuthApi } from '@/api/admin'
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
import type { IdType } from '@/utils/id'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { resolveAdminLandingPath } from '@/utils/admin-auth-bootstrap'
/**
* Purpose: router supports AdminLoginView.vue by holding or executing the router 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 router = useRouter()
/**
* Purpose: formRef supports AdminLoginView.vue by holding or executing the form ref 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 formRef = ref<FormInstance>()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** shopLoading is a reactive state variable used by the template and event handlers. */
const shopLoading = ref(false)
/**
* Purpose: shops supports AdminLoginView.vue by holding or executing the shops 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 shops = ref<Array<{ id: IdType; shopName: string }>>([])
/** allowShoplessLogin is a reactive state variable used by the template and event handlers. */
const allowShoplessLogin = ref(false)
/** loginShopMessage is a reactive state variable used by the template and event handlers. */
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
/**
* Purpose: formState supports AdminLoginView.vue by holding or executing the form 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 formState = reactive({
account: '',
password: '',
shopId: undefined as string | undefined
})
let loginShopTimer: number | undefined
/** handleAccountInput is a local helper used by this page script. */
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
formState.account = normalized
}
}
/** getShopIdValue is a local helper used by this page script. */
const getShopIdValue = (shop: { id: IdType; shopName: string }) => String(shop.id ?? '')
/** getShopLabel is a local helper used by this page script. */
const getShopLabel = (shop: { id: IdType; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
/** shopOptions is a reactive state variable used by the template and event handlers. */
const shopOptions = computed(() =>
shops.value.map(shop => ({
label: getShopLabel(shop),
value: getShopIdValue(shop)
}))
)
/** hasAvailableShops is a reactive state variable used by the template and event handlers. */
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
/** shouldRequireShop is a reactive state variable used by the template and event handlers. */
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
/** shopPlaceholder is a reactive state variable used by the template and event handlers. */
const shopPlaceholder = computed(() => {
if (shopLoading.value) {
return '正在加载可登录店铺'
}
if (hasAvailableShops.value) {
return allowShoplessLogin.value ? '可选择本次登录店铺,留空进入平台总览' : '请选择登录店铺'
}
if (allowShoplessLogin.value) {
return '当前无需选择店铺'
}
return '请先输入账号'
})
/**
* Purpose: formRules supports AdminLoginView.vue by holding or executing the form rules 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 formRules = {
const formState = reactive({ account: '', password: '' })
const formRules: any = {
account: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ required: true, message: '请输入管理员账号', trigger: 'blur' },
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
shopId: [{
validator: async () => {
if (!shouldRequireShop.value || formState.shopId) {
return Promise.resolve()
}
return Promise.reject(new Error('请选择登录店铺'))
},
trigger: 'change'
}]
} as any
/** filterShopOption is a local helper used by this page script. */
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
/** isLoginShopPrefetchUnsupported is a local helper used by this page script. */
const isLoginShopPrefetchUnsupported = (error: unknown) => {
const status = (error as any)?.response?.status
return status === 404
password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
}
/** resetLoginShopTimer is a local helper used by this page script. */
const resetLoginShopTimer = () => {
if (loginShopTimer !== undefined) {
window.clearTimeout(loginShopTimer)
loginShopTimer = undefined
}
}
/** restoreLoginShop is a local helper used by this page script. */
const restoreLoginShop = () => {
const cached = localStorage.getItem('adminUserInfo')
if (!cached) {
return
}
try {
const parsed = JSON.parse(cached)
if (parsed?.type === 4) {
return
}
if (parsed?.shopId) {
formState.shopId = String(parsed.shopId)
}
} catch (error) {
console.error('恢复后台登录店铺失败:', error)
}
}
/** applyLoginShopSelection is a local helper used by this page script. */
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
shops.value = selection?.shops || []
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
loginShopMessage.value = selection?.message || ''
if (!shops.value.length) {
formState.shopId = undefined
return
}
const matchedShop = shops.value.find(shop => getShopIdValue(shop) === formState.shopId)
if (matchedShop) {
return
}
if (!allowShoplessLogin.value && shops.value.length === 1) {
formState.shopId = getShopIdValue(shops.value[0]!)
return
}
formState.shopId = undefined
}
/** loadLoginShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadLoginShops = async (account = formState.account) => {
const trimmedAccount = account.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
shopLoading.value = true
try {
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
if (formState.account.trim() === trimmedAccount) {
applyLoginShopSelection(selection)
}
} catch (error) {
if (formState.account.trim() === trimmedAccount) {
if (isLoginShopPrefetchUnsupported(error)) {
applyLoginShopSelection({
allowShoplessLogin: true,
message: '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。',
shops: []
})
} else {
applyLoginShopSelection(null)
loginShopMessage.value = '登录店铺加载失败,请稍后重试'
}
}
if (!isLoginShopPrefetchUnsupported(error)) {
console.error('获取登录店铺列表失败:', error)
}
} finally {
shopLoading.value = false
}
}
/** handleLogin is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleLogin = async () => {
formState.account = sanitizeAccountInput(formState.account)
loading.value = true
try {
await formRef.value?.validate()
loading.value = true
const res = await runWithGlobalLoading(() => adminAuthApi.login({
const response = await runWithGlobalLoading(() => adminAuthApi.login({
account: formState.account,
password: formState.password,
shopId: formState.shopId
}))
const { accessToken, refreshToken, userInfo } = res as any
localStorage.setItem('adminAccessToken', accessToken)
localStorage.setItem('adminRefreshToken', refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(userInfo))
sessionStorage.setItem('adminAccessToken', accessToken)
sessionStorage.setItem('adminRefreshToken', refreshToken)
message.success('登录成功')
await runWithGlobalLoading(() => loadUserPermissions())
const landingPath = resolveAdminLandingPath()
router.push(landingPath).catch(err => {
console.error('跳转到后台默认页面失败:', err)
window.location.href = landingPath
})
password: formState.password
})) as any
localStorage.setItem('adminAccessToken', response.accessToken)
localStorage.setItem('adminRefreshToken', response.refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(response.userInfo))
sessionStorage.setItem('adminAccessToken', response.accessToken)
sessionStorage.setItem('adminRefreshToken', response.refreshToken)
message.success('管理员登录成功')
await router.push(resolveAdminLandingPath())
} catch (error: any) {
console.error('登录失败:', error)
message.error(error.message || '登录失败,请检查用户名和密码')
message.error(error?.message || '登录失败,请检查管理员账号和密码')
} finally {
loading.value = false
}
}
onMounted(() => {
restoreLoginShop()
})
watch(
() => formState.account,
value => {
resetLoginShopTimer()
const trimmedAccount = value.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
loginShopTimer = window.setTimeout(() => {
loginShopTimer = undefined
void loadLoginShops(trimmedAccount)
}, 400)
}
)
onBeforeUnmount(() => {
resetLoginShopTimer()
})
/** goToFrontend is a local helper used by this page script. */
const goToFrontend = () => {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
sessionStorage.removeItem('adminRefreshToken')
setTimeout(() => {
window.location.href = '/'
}, 100)
}
</script>
<style scoped>
.admin-login {
min-height: 100dvh;
background:
linear-gradient(color-mix(in srgb, var(--theme-page-bg) 74%, transparent), color-mix(in srgb, var(--theme-page-bg) 90%, transparent)),
var(--theme-background-image),
linear-gradient(
160deg,
var(--theme-primary) 0%,
var(--theme-accent) 58%,
color-mix(in srgb, var(--theme-accent) 78%, var(--text-primary)) 100%
);
background-size: cover, cover, auto;
background-position: center top;
display: flex;
align-items: center;
justify-content: center;
padding: max(24px, env(safe-area-inset-top)) 24px max(24px, env(safe-area-inset-bottom));
}
.login-container {
width: 100%;
max-width: 440px;
}
.login-header {
text-align: center;
margin-bottom: 28px;
color: var(--text-primary);
}
.login-header h1 {
font-size: clamp(23px, 3.2vw, 28px);
font-weight: 700;
margin: 0 0 8px 0;
}
.login-header p {
font-size: 14px;
line-height: 1.7;
opacity: 0.82;
margin: 0;
}
.login-card {
border-radius: 24px;
border: 1px solid var(--theme-border);
box-shadow: var(--theme-button-shadow);
overflow: hidden;
}
.login-footer {
text-align: center;
margin-top: 18px;
}
.login-footer a {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 36px;
padding: 0 14px;
border-radius: 999px;
color: var(--theme-primary);
background: var(--theme-primary-soft);
text-decoration: none;
font-size: 14px;
font-weight: 700;
box-shadow: 0 8px 20px color-mix(in srgb, var(--theme-primary) 18%, transparent);
}
.login-footer a:hover {
color: var(--theme-accent);
background: var(--theme-card-bg);
}
.login-card :deep(.ant-card-body) {
background: var(--theme-card-bg);
}
.login-card :deep(.ant-btn-primary) {
border-color: transparent;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.login-card :deep(.ant-btn-primary:hover),
.login-card :deep(.ant-btn-primary:focus) {
border-color: transparent;
background: linear-gradient(135deg, var(--theme-accent) 0%, var(--theme-secondary) 100%);
}
.login-card :deep(.ant-input:hover),
.login-card :deep(.ant-input-affix-wrapper:hover),
.login-card :deep(.ant-select:not(.ant-select-disabled):hover .ant-select-selector) {
border-color: var(--theme-primary);
}
.login-card :deep(.ant-input:focus),
.login-card :deep(.ant-input-affix-wrapper-focused),
.login-card :deep(.ant-select-focused .ant-select-selector) {
border-color: var(--theme-primary);
box-shadow: var(--theme-focus-shadow);
}
@media (max-width: 960px) {
.admin-login {
align-items: flex-start;
justify-content: stretch;
padding: calc(22px + env(safe-area-inset-top)) 14px calc(18px + env(safe-area-inset-bottom));
}
.login-container {
max-width: none;
}
.login-header {
text-align: left;
margin-bottom: 18px;
padding: 0 4px;
}
.login-header h1 {
max-width: 8em;
}
.login-card {
border-radius: 26px;
}
.login-card :deep(.ant-card-body) {
padding: 20px 18px 18px;
}
.login-card :deep(.ant-form-item) {
margin-bottom: 18px;
}
.login-card :deep(.ant-btn-lg),
.login-card :deep(.ant-input-affix-wrapper-lg),
.login-card :deep(.ant-input-lg),
.login-card :deep(.ant-select-single.ant-select-lg .ant-select-selector) {
min-height: 48px;
}
}
.salon-admin-login { display: grid; place-items: center; min-height: 100dvh; padding: 32px 20px; background: var(--theme-gradient); color: var(--theme-neutral); }
.login-panel { position: relative; width: min(100%, 420px); padding: 42px 42px 34px; border: 1px solid rgba(59, 147, 132, .2); border-radius: 24px; background: var(--theme-card-bg); box-shadow: 0 28px 80px rgba(25, 83, 72, .15); backdrop-filter: blur(16px); }
.brand-mark { display: grid; place-items: center; width: 44px; height: 44px; border-radius: 14px; background: #2d9d87; color: #fff; font-size: 23px; font-weight: 800; box-shadow: 0 10px 24px rgba(45, 157, 135, .28); }
.eyebrow { margin: 22px 0 8px; color: #2d9d87; font-size: 11px; font-weight: 800; letter-spacing: .16em; }
h1 { margin: 0; font-size: 29px; letter-spacing: -.03em; }
.intro { margin: 10px 0 30px; color: #6a8580; font-size: 13px; line-height: 1.7; }
:deep(.ant-form-item-label > label) { color: #476a64; font-size: 12px; font-weight: 700; }
:deep(.ant-input), :deep(.ant-input-affix-wrapper) { border-color: #dcebe6; border-radius: 10px; background: #fbfefd; }
:deep(.ant-btn-primary) { height: 46px; border: 0; border-radius: 11px; background: #2d9d87; box-shadow: 0 10px 22px rgba(45, 157, 135, .2); }
@media (max-width: 520px) { .login-panel { padding: 32px 24px 26px; border-radius: 20px; } h1 { font-size: 25px; } }
</style>
File diff suppressed because it is too large Load Diff
@@ -1,488 +0,0 @@
<template>
<div class="home">
<template v-if="!isMobile">
<a-page-header title="欢迎使用后台管理系统" :sub-title="welcomeMessage" />
<a-alert
v-if="isBootstrapAdmin"
class="bootstrap-alert"
type="info"
show-icon
message="当前处于平台总览模式"
description="当前后台仅面向平台管理员,负责维护店铺、用户账号、角色归属和平台运行状态。"
/>
<a-alert
v-if="isShopAuthorizationExpired"
class="bootstrap-alert"
type="error"
show-icon
message="授权已到期,请联系管理员"
description="当前店铺已超过授权有效期,后台业务功能已暂时禁用。"
/>
<a-card class="time-card">
<a-statistic title="当前时间" :value="currentTime" />
</a-card>
<a-card class="info-card">
<a-descriptions bordered>
<a-descriptions-item label="用户信息">
<div class="user-info">
<a-avatar :size="64" :src="userInfo?.avatar || DEFAULT_AVATAR" />
<div class="user-details">
<h3>{{ userInfo?.nickname || '管理员' }}</h3>
<p>{{ getUserTypeText(userInfo?.type) }}</p>
<p v-if="userInfo?.shopName">所属店铺:{{ userInfo?.shopName }}</p>
</div>
</div>
</a-descriptions-item>
</a-descriptions>
</a-card>
<a-card class="permissions-card">
<template #title>
<div class="card-title">
<SafetyCertificateOutlined class="title-icon" />
<span>我的权限</span>
</div>
</template>
<div class="permissions-content" v-if="userPermissions.length > 0">
<div v-for="(group, groupName) in groupedPermissions" :key="groupName" class="permission-group">
<div class="group-title">{{ groupName }}</div>
<div class="permission-tags">
<a-tag v-for="permission in group" :key="permission.id" color="blue" class="permission-tag">
{{ permission.permissionName }}
</a-tag>
</div>
</div>
</div>
<div class="no-permissions" v-else>暂无权限信息</div>
</a-card>
<a-card class="quick-actions">
<template #title>
快捷操作
</template>
<a-row :gutter="[16, 16]">
<a-col v-for="item in quickActions" :key="item.key" :span="8">
<a-card hoverable @click="navigateTo(item.path, item.permissionCode)">
<template #cover>
<div class="action-icon">
<component :is="item.icon" />
</div>
</template>
<template #title>
{{ item.title }}
</template>
</a-card>
</a-col>
</a-row>
</a-card>
</template>
<template v-else>
<section class="admin-page-intro">
<span class="admin-page-intro__eyebrow">{{ userInfo?.nickname || userInfo?.account || '后台账号' }}</span>
<h1 class="admin-page-intro__title">{{ userInfo?.shopName || (isBootstrapAdmin ? '平台总览模式' : '游客模式') }}</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">{{ currentTime }}</span>
<span class="admin-page-chip">{{ getUserTypeText(userInfo?.type) }}</span>
<span v-if="isBootstrapAdmin" class="admin-page-chip">平台总览</span>
</div>
</section>
<section v-if="isBootstrapAdmin" class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">平台总览模式</div>
<a-button type="primary" size="large" block @click="navigateTo('/admin/shops', 'shop:view')">进入店铺管理</a-button>
</section>
<div class="admin-mobile-grid admin-mobile-grid--two">
<section class="admin-mobile-stat">
<div class="admin-mobile-stat__label">权限数量</div>
<div class="admin-mobile-stat__value">{{ userPermissions.length }}</div>
</section>
<section class="admin-mobile-stat">
<div class="admin-mobile-stat__label">快捷入口</div>
<div class="admin-mobile-stat__value">{{ quickActions.length }}</div>
</section>
</div>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">快捷入口</div>
<div class="mobile-actions">
<button
v-for="item in quickActions"
:key="item.key"
class="mobile-action"
type="button"
@click="navigateTo(item.path, item.permissionCode)"
>
<div class="mobile-action__icon">
<component :is="item.icon" />
</div>
<div class="mobile-action__body">
<div class="mobile-action__title">{{ item.title }}</div>
</div>
</button>
</div>
</section>
<section class="admin-mobile-section-card">
<div class="admin-mobile-section-card__title">权限分组</div>
<div v-if="userPermissions.length > 0" class="mobile-permission-groups">
<div v-for="(group, groupName) in groupedPermissions" :key="groupName" class="mobile-permission-group">
<div class="mobile-permission-group__title">{{ groupName }}</div>
<div class="permission-tags">
<a-tag v-for="permission in group" :key="permission.id" color="blue" class="permission-tag">
{{ permission.permissionName }}
</a-tag>
</div>
</div>
</div>
<a-empty v-else description="暂无权限信息" />
</section>
</template>
</div>
</template>
<script setup lang="ts">
/**
* HomeView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
HomeOutlined,
SafetyCertificateOutlined,
UserOutlined
} from '@ant-design/icons-vue'
/**
* Purpose: UserVO supports HomeView.vue by holding or executing the user vo 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.
*/
import { userApi, type UserVO } from '@/api/admin'
/**
* Purpose: PermissionVO supports HomeView.vue by holding or executing the permission vo 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.
*/
import { permissionApi, type PermissionVO } from '@/api/permission'
import { DEFAULT_AVATAR } from '@/constants'
import { message } from 'ant-design-vue'
import { useAdminViewport } from '@/composables/useAdminViewport'
import { isBootstrapAdminUser } from './admin-helpers'
import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions'
/**
* Purpose: router supports HomeView.vue by holding or executing the router 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 router = useRouter()
const { isMobile } = useAdminViewport()
/** currentTime is a reactive state variable used by the template and event handlers. */
const currentTime = ref('')
/**
* Purpose: userInfo supports HomeView.vue by holding or executing the user info 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 userInfo = ref<UserVO | null>(null)
/**
* Purpose: userPermissions supports HomeView.vue by holding or executing the user permissions 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 userPermissions = ref<PermissionVO[]>([])
let timer: number | null = null
/** welcomeMessage is a reactive state variable used by the template and event handlers. */
const welcomeMessage = computed(() => {
const hour = new Date().getHours()
if (hour < 12) {
return '早上好!'
} else if (hour < 18) {
return '下午好!'
} else {
return '晚上好!'
}
})
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** isShopAuthorizationExpired is a reactive state variable used by the template and event handlers. */
const isShopAuthorizationExpired = computed(() => Boolean(userInfo.value?.shopAuthorizationExpired) && userInfo.value?.type !== 4)
/** groupedPermissions is a reactive state variable used by the template and event handlers. */
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
userPermissions.value.forEach(permission => {
const groupName = permission.permissionGroup
if (!groups[groupName]) {
groups[groupName] = []
}
groups[groupName]!.push(permission)
})
return groups
})
/** quickActions is a reactive state variable used by the template and event handlers. */
const quickActions = computed(() => {
if (isShopAuthorizationExpired.value) {
return []
}
const actions = [
{
key: 'users',
title: '店长账号',
path: '/admin/users',
icon: UserOutlined,
permissionCode: 'user:view'
},
{
key: 'shops',
title: '店铺管理',
path: '/admin/shops',
icon: HomeOutlined,
permissionCode: 'shop:view'
}
]
const grantedPermissions = new Set(userPermissions.value.map(permission => permission.permissionCode))
if (isBootstrapAdmin.value) {
return actions.filter(item => isAllowedForShoplessPlatformAdmin(item.permissionCode))
}
return actions.filter(item => grantedPermissions.has(item.permissionCode))
})
/** getUserTypeText is a local helper used by this page script. */
const getUserTypeText = (type: number | undefined) => {
switch (type) {
case 4:
return '平台管理员'
case 2:
return '店长'
case 3:
return '美甲师'
default:
return '后台账号'
}
}
/** updateCurrentTime is a local helper used by this page script. */
const updateCurrentTime = () => {
const now = new Date()
currentTime.value = now.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
if (adminUserInfoStr) {
userInfo.value = JSON.parse(adminUserInfoStr)
} else {
const res = await userApi.getUserInfo()
userInfo.value = res as unknown as UserVO
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
}
/** fetchUserPermissions is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserPermissions = async () => {
try {
const res = await permissionApi.getUserPermissions()
userPermissions.value = res as unknown as PermissionVO[]
} catch (error) {
console.error('获取用户权限失败:', error)
}
}
/** navigateTo is a local helper used by this page script. */
const navigateTo = (path: string, permissionCode?: string) => {
if (permissionCode) {
if (isBootstrapAdmin.value && isAllowedForShoplessPlatformAdmin(permissionCode)) {
router.push(path)
return
}
const hasPermission = userPermissions.value.some(p => p.permissionCode === permissionCode)
if (!hasPermission) {
message.warning('您没有该操作的权限')
return
}
}
router.push(path)
}
onMounted(() => {
updateCurrentTime()
timer = window.setInterval(updateCurrentTime, 1000)
void fetchUserInfo()
void fetchUserPermissions()
})
onBeforeUnmount(() => {
if (timer !== null) {
window.clearInterval(timer)
}
})
</script>
<style scoped>
.home {
padding: 0;
}
.time-card,
.bootstrap-alert,
.info-card,
.permissions-card {
margin-bottom: 24px;
}
.user-info {
display: flex;
align-items: center;
gap: 16px;
}
.user-details {
flex: 1;
}
.user-details h3 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.user-details p {
margin: 4px 0;
color: var(--text-secondary);
}
.card-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 16px;
font-weight: 600;
color: var(--admin-mobile-ink);
}
.title-icon {
font-size: 20px;
color: var(--admin-mobile-accent);
}
.permissions-content,
.mobile-permission-groups {
display: flex;
flex-direction: column;
gap: 16px;
}
.permission-group,
.mobile-permission-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.group-title,
.mobile-permission-group__title {
font-size: 14px;
font-weight: 600;
color: var(--theme-primary);
margin-bottom: 4px;
}
.permission-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.permission-tag {
font-size: 13px;
padding: 4px 12px;
border-radius: 12px;
margin: 0;
}
.no-permissions {
text-align: center;
padding: 20px;
color: var(--text-secondary);
}
.quick-actions {
margin-top: 24px;
}
.action-icon {
display: flex;
align-items: center;
justify-content: center;
height: 80px;
font-size: 32px;
color: var(--theme-primary);
background: var(--admin-mobile-accent-soft);
}
.mobile-actions {
display: grid;
gap: 12px;
margin-top: 14px;
}
.mobile-action {
display: flex;
align-items: center;
gap: 14px;
padding: 14px 0;
border: 0;
border-bottom: 1px solid var(--admin-mobile-border);
background: transparent;
text-align: left;
}
.mobile-action:last-child {
border-bottom: 0;
}
.mobile-action__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
border-radius: 14px;
background: var(--admin-mobile-accent-soft);
color: var(--theme-primary);
}
.mobile-action__body {
flex: 1;
min-width: 0;
}
.mobile-action__title {
font-size: 15px;
font-weight: 600;
color: var(--admin-mobile-ink);
}
.mobile-action__meta {
margin-top: 4px;
color: var(--text-secondary);
font-size: 12px;
}
</style>
@@ -1,396 +0,0 @@
<template>
<div class="admin-manage">
<section class="admin-page-intro admin-manage__intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">{{ currentShopName }}</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">{{ roleLabel }}</span>
<span class="admin-page-chip">可见模块 {{ visibleModules.length }}</span>
<span v-if="isBootstrapAdmin" class="admin-page-chip">平台总览</span>
</div>
</section>
<div class="module-grid">
<button
v-for="module in visibleModules"
:key="module.key"
class="module-card"
:class="{ 'is-disabled': !module.allowed }"
type="button"
@click="openModule(module)"
>
<div class="module-card__icon">
<component :is="module.icon" />
</div>
<div class="module-card__body">
<div class="module-card__head">
<div class="module-card__title">{{ module.title }}</div>
<span class="module-card__badge">
{{ module.readonly ? '仅查看' : (module.allowed ? '进入' : '受限') }}
</span>
</div>
<div class="module-card__subtitle">{{ module.description }}</div>
<div v-if="!module.allowed && module.disabledReason" class="module-card__hint">
{{ module.disabledReason }}
</div>
</div>
</button>
</div>
</div>
</template>
<script setup lang="ts">
/**
* ManageView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
DashboardOutlined,
FileProtectOutlined,
GiftOutlined,
HomeOutlined,
MessageOutlined,
SafetyCertificateOutlined,
ShopOutlined,
SettingOutlined,
TagOutlined,
TeamOutlined,
UserOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { usePermission } from '@/utils/permission'
import {
getAdminCurrentShopName,
getAdminRoleLabel,
isBootstrapAdminUser,
loadCachedAdminUserInfo
} from './admin-helpers'
/**
* Purpose: router supports ManageView.vue by holding or executing the router 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 router = useRouter()
const { hasPermission, loadUserPermissions } = usePermission()
/** userInfo is a reactive state variable used by the template and event handlers. */
const userInfo = computed(() => loadCachedAdminUserInfo())
/** currentShopName is a reactive state variable used by the template and event handlers. */
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
/** roleLabel is a reactive state variable used by the template and event handlers. */
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value))
/** visibleModules is a reactive state variable used by the template and event handlers. */
const visibleModules = computed(() => {
const definitions = [
{
key: 'dashboard',
title: '仪表盘',
description: '查看经营概览、近期动态和重点提醒。',
path: '/admin',
icon: DashboardOutlined,
permissionCode: 'dashboard:view'
},
{
key: 'users',
title: '用户管理',
description: '处理账号、资产、VIP 和店铺关系。',
path: '/admin/users',
icon: UserOutlined,
permissionCode: 'user:view',
requireShopContext: true,
allowPlatformOverviewManage: true
},
{
key: 'products',
title: '作品管理',
description: '维护作品、标签、可预约员工和优惠券。',
path: '/admin/products',
icon: ShopOutlined,
permissionCode: 'product:view',
requireShopContext: true
},
{
key: 'coupons',
title: '优惠券',
description: '管理券模板、场景和批量发放入口。',
path: '/admin/coupons',
icon: GiftOutlined,
permissionCode: 'coupon:view',
requireShopContext: true
},
{
key: 'tags',
title: '标签管理',
description: '维护作品标签及颜色风格。',
path: '/admin/tags',
icon: TagOutlined,
permissionCode: 'tag:view',
requireShopContext: true
},
{
key: 'artists',
title: '员工',
description: '查看员工状态、技能与排班关系。',
path: '/admin/nail-artists',
icon: TeamOutlined,
permissionCode: 'nail_artist:view',
requireShopContext: true
},
{
key: 'shops',
title: '店铺管理',
description: '创建门店、调整营业信息与图片素材。',
path: '/admin/shops',
icon: HomeOutlined,
permissionCode: 'shop:view'
},
{
key: 'permissions',
title: '权限管理',
description: '查看权限列表并给后台账号分配权限。',
path: '/admin/permissions',
icon: SafetyCertificateOutlined,
permissionCode: 'permission:view'
},
{
key: 'messages',
title: '消息发布',
description: '发布站内消息,可面向全平台或指定范围。',
path: '/admin/messages',
icon: MessageOutlined,
permissionCode: 'message:view'
},
{
key: 'announcements',
title: '公告管理',
description: '维护首页滚动公告,支持平台和门店范围。',
path: '/admin/announcements',
icon: MessageOutlined,
permissionCode: 'announcement:view'
},
{
key: 'parameters',
title: '参数管理',
description: '维护短信验证码场景的 MessageHub 模板、队列和通道。',
path: '/admin/messagehub-push-configs',
icon: SettingOutlined,
permissionCode: 'messagehub:config:manage'
},
{
key: 'agreements',
title: '协议管理',
description: '维护用户协议和隐私政策版本。',
path: '/admin/legal-agreements',
icon: FileProtectOutlined,
permissionCode: 'legal_agreement:manage'
}
]
return definitions
.filter(module => !module.permissionCode || hasPermission(module.permissionCode))
.map(module => {
if (module.requireShopContext && isBootstrapAdmin.value && !module.allowPlatformOverviewManage) {
return {
...module,
allowed: true,
readonly: true,
disabledReason: '平台总览模式下该模块仅可查看,编辑操作已关闭。'
}
}
return {
...module,
allowed: true,
readonly: false,
disabledReason: ''
}
})
})
/** openModule is a local helper used by this page script. */
const openModule = (module: any) => {
if (!module.allowed) {
message.warning(module.disabledReason || '当前无法进入该模块')
return
}
router.push(module.path)
}
onMounted(() => {
void loadUserPermissions()
})
</script>
<style scoped>
.admin-manage {
display: grid;
gap: 18px;
}
.module-grid {
display: grid;
gap: 14px;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.module-card {
display: flex;
align-items: flex-start;
gap: 14px;
padding: 18px;
border: 1px solid var(--admin-mobile-border);
border-radius: 24px;
background: var(--admin-mobile-card);
text-align: left;
box-shadow: 0 12px 30px rgba(23, 33, 31, 0.08);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.module-card:hover {
transform: translateY(-2px);
box-shadow: 0 18px 36px rgba(23, 33, 31, 0.12);
}
.module-card.is-disabled {
opacity: 0.78;
}
.module-card__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 52px;
height: 52px;
border-radius: 18px;
background: var(--admin-mobile-accent-soft);
color: var(--theme-primary);
flex-shrink: 0;
font-size: 20px;
}
.module-card__body {
flex: 1;
min-width: 0;
}
.module-card__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.module-card__title {
font-size: 17px;
font-weight: 700;
color: var(--admin-mobile-ink);
}
.module-card__badge {
display: inline-flex;
align-items: center;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 12px;
font-weight: 600;
}
.module-card__subtitle {
margin-top: 8px;
line-height: 1.6;
color: var(--text-secondary);
}
.module-card__hint {
margin-top: 10px;
padding: 10px 12px;
border-radius: 14px;
background: var(--theme-primary-soft);
color: var(--text-secondary);
line-height: 1.55;
}
@media (max-width: 960px) {
.admin-manage {
gap: 12px;
}
.admin-manage__intro {
display: none;
}
.module-grid {
grid-template-columns: 1fr;
gap: 10px;
}
.module-card {
gap: 12px;
padding: 14px 16px;
border-radius: 18px;
box-shadow: 0 8px 20px rgba(23, 33, 31, 0.07);
}
.module-card:hover {
transform: none;
box-shadow: 0 8px 20px rgba(23, 33, 31, 0.07);
}
.module-card__icon {
width: 44px;
height: 44px;
border-radius: 14px;
font-size: 18px;
}
.module-card__head {
align-items: flex-start;
}
.module-card__title {
font-size: 16px;
line-height: 1.25;
}
.module-card__badge {
min-height: 24px;
padding: 0 8px;
font-size: 11px;
}
.module-card__subtitle {
margin-top: 5px;
font-size: 13px;
line-height: 1.45;
}
.module-card__hint {
margin-top: 8px;
padding: 8px 10px;
border-radius: 12px;
font-size: 13px;
}
}
@media (max-width: 420px) {
.module-card {
padding: 12px 14px;
}
.module-card__icon {
width: 40px;
height: 40px;
}
.module-card__head {
gap: 8px;
}
}
</style>
+115 -69
View File
@@ -1,47 +1,52 @@
<template>
<div class="admin-profile">
<section class="profile-head">
<header class="profile-head">
<div>
<span class="profile-eyebrow">后台账号</span>
<h1>{{ userInfo?.nickname || '未设置昵称' }}</h1>
<p>{{ userInfo?.account || '当前登录账号' }} · {{ roleLabel }}</p>
<span class="profile-eyebrow">管理员账号</span>
<h1>{{ userInfo?.nickname || '平台管理员' }}</h1>
<p>{{ userInfo?.account || '当前登录账号' }}</p>
</div>
<a-avatar :size="58" :src="userInfo?.avatar || DEFAULT_AVATAR" />
</header>
<section class="profile-section">
<div class="profile-section__head">
<div><h2>账号资料</h2><p>该后台只服务平台管理员,数据范围为 Salon 全平台。</p></div>
</div>
<div class="profile-rows">
<div class="profile-row"><span>登录账号</span><strong>{{ userInfo?.account || '--' }}</strong></div>
<div class="profile-row"><span>显示昵称</span><strong>{{ userInfo?.nickname || '未设置昵称' }}</strong></div>
<div class="profile-row"><span>账号类型</span><strong>平台管理员</strong></div>
<div class="profile-row"><span>平台范围</span><strong>全平台门店与经营数据</strong></div>
</div>
<span class="profile-chip">{{ isPlatformOverview ? '平台总览' : currentShopName }}</span>
</section>
<section class="profile-section">
<div class="profile-section__head">
<div>
<h2>账号与门店</h2>
<p>账号资料、权限范围和门店切换已集中到系统设置。</p>
<div><h2>安全设置</h2><p>修改管理员密码后,所有后台会话都会失效,需要重新登录。</p></div>
</div>
<a-form class="password-form" :model="passwordForm" :rules="passwordRules" layout="vertical" @finish="handleChangePassword">
<div class="password-form__grid">
<a-form-item label="当前密码" name="currentPassword">
<a-input-password v-model:value="passwordForm.currentPassword" autocomplete="current-password" placeholder="请输入当前密码" />
</a-form-item>
<a-form-item label="新密码" name="newPassword">
<a-input-password v-model:value="passwordForm.newPassword" autocomplete="new-password" placeholder="8-32 位,至少包含 3 类字符" />
</a-form-item>
<a-form-item label="确认新密码" name="confirmPassword">
<a-input-password v-model:value="passwordForm.confirmPassword" autocomplete="new-password" placeholder="请再次输入新密码" />
</a-form-item>
</div>
</div>
<button class="profile-link" type="button" @click="router.push({ path: '/admin/settings', query: { section: 'account' } })">
<span class="profile-link__icon">◎</span>
<span class="profile-link__body"><strong>打开当前账号设置</strong><small>查看后台账号、权限范围和可用门店</small></span>
<span class="profile-link__arrow">›</span>
</button>
</section>
<section class="profile-section">
<div class="profile-section__head">
<div>
<h2>常用入口</h2>
<p>继续处理日常经营工作。</p>
<div class="password-form__actions">
<span>保存后当前设备和其他设备的后台登录都会退出。</span>
<a-button type="primary" html-type="submit" :loading="changingPassword">保存新密码</a-button>
</div>
</div>
<div class="profile-actions">
<a-button type="default" size="large" @click="router.push('/admin/orders')">查看订单</a-button>
<a-button type="default" size="large" @click="router.push('/admin/manage')">进入经营模块</a-button>
</div>
</a-form>
</section>
<section class="profile-section profile-section--logout">
<div class="profile-section__head">
<div>
<h2>退出登录</h2>
<p>退出后需要重新登录后台。</p>
</div>
<div><h2>退出登录</h2><p>退出后需要重新登录后台。</p></div>
</div>
<a-button danger size="large" block @click="handleLogout">退出当前账号</a-button>
</section>
@@ -49,57 +54,98 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { DEFAULT_AVATAR } from '@/constants'
import { adminAuthApi } from '@/api/admin'
import { clearAdminBootstrapSession } from '@/utils/admin-auth-bootstrap'
import { completeAdminLogout } from '@/utils/admin-logout'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { getAdminCurrentShopName, getAdminRoleLabel, isBootstrapAdminUser, loadCachedAdminUserInfo } from './admin-helpers'
import { loadCachedAdminUserInfo } from '@/utils/admin-session'
const router = useRouter()
const userInfo = ref(loadCachedAdminUserInfo())
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
const isPlatformOverview = computed(() => isBootstrapAdminUser(userInfo.value))
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
await completeAdminLogout(router)
message.success('已退出登录')
})
const changingPassword = ref(false)
const passwordForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' })
const passwordRules: Record<string, Rule[]> = {
currentPassword: [{ required: true, message: '请输入当前密码' }],
newPassword: [
{ required: true, message: '请输入新密码' },
{ min: 8, max: 32, message: '密码长度需为 8-32 位' },
{
validator: async (_rule, value) => {
const password = String(value || '')
const categoryCount = [/[0-9]/, /[a-z]/, /[A-Z]/, /[^A-Za-z0-9]/].filter(pattern => pattern.test(password)).length
if (password && categoryCount < 3) throw new Error('密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类')
}
}
})
],
confirmPassword: [
{ required: true, message: '请再次输入新密码' },
{
validator: async (_rule, value) => {
if (value && value !== passwordForm.newPassword) throw new Error('两次输入的新密码不一致')
}
}
]
}
const handleChangePassword = async () => {
changingPassword.value = true
try {
await adminAuthApi.changePassword({ currentPassword: passwordForm.currentPassword, newPassword: passwordForm.newPassword })
clearAdminBootstrapSession()
message.success('密码已更新,请使用新密码重新登录')
await router.replace('/admin/login')
} catch (error: any) {
message.error(error?.message || '密码修改失败,请重试')
} finally {
changingPassword.value = false
}
}
const handleLogout = () => Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
await completeAdminLogout(router)
message.success('已退出登录')
})
}
})
</script>
<style scoped>
.admin-profile { display: grid; gap: 18px; color: var(--admin-mobile-ink); }
.profile-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 18px; padding-bottom: 16px; border-bottom: 1px solid var(--admin-mobile-border); }
.profile-eyebrow { color: var(--theme-primary-action); font-size: 11px; font-weight: 800; letter-spacing: .12em; }
.profile-head h1 { margin: 7px 0 4px; font-size: 27px; }
.profile-head { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 8px 0 18px; border-bottom: 1px solid var(--admin-mobile-border); }
.profile-eyebrow { color: var(--theme-primary-action); font-size: 11px; font-weight: 800; letter-spacing: .14em; }
.profile-head h1 { margin: 7px 0 4px; font-size: 28px; }
.profile-head p, .profile-section__head p { margin: 0; color: var(--admin-mobile-muted); font-size: 13px; }
.profile-chip { padding: 7px 10px; border-radius: 999px; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 12px; font-weight: 700; white-space: nowrap; }
.profile-section { padding-top: 16px; border-top: 1px solid var(--admin-mobile-border); }
.profile-section__head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.profile-section__head h2 { margin: 0 0 4px; font-size: 15px; }
.profile-link { display: flex; width: 100%; align-items: center; gap: 12px; padding: 14px 2px; border: 0; border-bottom: 1px solid var(--admin-mobile-border); background: transparent; color: inherit; text-align: left; cursor: pointer; }
.profile-link:hover { color: var(--theme-primary-action); }
.profile-link__icon { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 12px; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 20px; }
.profile-link__body { display: grid; flex: 1; gap: 3px; min-width: 0; }
.profile-link__body strong { font-size: 14px; }
.profile-link__body small { color: var(--admin-mobile-muted); font-size: 12px; }
.profile-link__arrow { color: var(--admin-mobile-muted); font-size: 24px; line-height: 1; }
.profile-actions { display: flex; flex-wrap: wrap; gap: 10px; }
.profile-actions .ant-btn { flex: 1 1 180px; }
.profile-section--logout .ant-btn { max-width: 240px; }
@media (max-width: 560px) {
.profile-head { align-items: flex-start; flex-direction: column; }
.profile-section--logout .ant-btn { max-width: none; }
}
.profile-section { padding-top: 4px; border-top: 1px solid var(--admin-mobile-border); }
.profile-section__head { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 13px 0; }
.profile-section__head h2 { margin: 0 0 4px; font-size: 17px; }
.profile-rows { border-top: 1px solid var(--admin-mobile-border); }
.profile-row { display: grid; grid-template-columns: 160px 1fr; align-items: center; gap: 18px; min-height: 58px; padding: 10px 14px; border-bottom: 1px solid color-mix(in srgb, var(--admin-mobile-border) 70%, transparent); background: color-mix(in srgb, var(--theme-card-bg) 82%, transparent); }
.profile-row span { color: var(--admin-mobile-muted); font-size: 12px; }
.profile-row strong { color: var(--admin-mobile-ink); font-size: 13px; }
.profile-link { display: flex; width: 100%; align-items: center; gap: 12px; padding: 14px; border: 1px solid var(--admin-mobile-border); background: var(--theme-card-bg); color: inherit; text-align: left; cursor: pointer; }
.profile-link:hover { border-color: var(--theme-primary); background: var(--admin-mobile-accent-soft); }
.profile-link__icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 50%; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 800; }
.profile-link__body { display: grid; flex: 1; gap: 3px; }
.profile-link__body small { color: var(--admin-mobile-muted); font-size: 11px; }
.profile-link__arrow { color: var(--theme-primary-action); font-size: 24px; }
.profile-section--logout { padding-bottom: 12px; }
.password-form { padding: 15px 14px 14px; border: 1px solid var(--admin-mobile-border); background: color-mix(in srgb, var(--theme-card-bg) 82%, transparent); }
.password-form__grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
.password-form :deep(.ant-form-item) { margin-bottom: 12px; }
.password-form :deep(.ant-form-item-label) { padding-bottom: 4px; }
.password-form__actions { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding-top: 2px; color: var(--admin-mobile-muted); font-size: 11px; }
.password-form__actions .ant-btn { flex: 0 0 auto; }
@media (max-width: 760px) { .password-form__grid { grid-template-columns: 1fr; gap: 0; } .password-form__actions { align-items: flex-start; flex-direction: column; } .password-form__actions .ant-btn { width: 100%; } }
@media (max-width: 640px) { .profile-row { grid-template-columns: 1fr; gap: 4px; } }
</style>
@@ -0,0 +1,214 @@
<template>
<main class="salon-dashboard">
<header class="dashboard-head">
<div>
<span class="dashboard-eyebrow">SALON PLATFORM</span>
<h1>Salon 管理驾驶舱</h1>
<p>用门店、员工、客户和服务数据掌握平台经营状态。</p>
<div class="dashboard-freshness"><span>系统日期 {{ currentDateLabel }}</span><span>最近刷新 {{ lastRefreshedAt || '尚未刷新' }}</span></div>
</div>
<div class="dashboard-tools">
<label class="date-control"><span>统计日期</span><input v-model="date" type="date" @change="loadOverview" /></label>
<div class="range-control" role="group" aria-label="趋势范围">
<button v-for="item in ranges" :key="item.value" type="button" :class="{ active: days === item.value }" @click="changeRange(item.value)">{{ item.label }}</button>
</div>
<button class="refresh-button" type="button" :disabled="loading" @click="loadOverview"><ReloadOutlined :spin="loading" /> 刷新</button>
</div>
</header>
<a-alert v-if="overview.degraded" class="dashboard-alert" type="warning" show-icon :message="overview.degradedMessage || '经营数据暂时不可用'" description="当前页面已保留空数据展示,稍后可重新刷新。" />
<section class="kpi-strip" aria-label="今日经营指标">
<div class="kpi-item kpi-item--primary"><span class="kpi-label">{{ selectedToday ? '今日预约' : '当日预约' }}</span><strong>{{ overview.today.appointmentCount }}</strong><small>含已排期服务</small></div>
<div class="kpi-item"><span class="kpi-label">服务中</span><strong>{{ overview.today.serviceInProgressCount }}</strong><small>当前进行中的服务</small></div>
<div class="kpi-item"><span class="kpi-label">{{ selectedToday ? '今日完成' : '当日完成' }}</span><strong>{{ overview.today.completedServiceCount }}</strong><small>已完成服务</small></div>
<div class="kpi-item"><span class="kpi-label">{{ selectedToday ? '今日营业额' : '当日营业额' }}</span><strong>¥{{ money(overview.today.orderAmount) }}</strong><small>订单与历史补单</small></div>
<div class="kpi-item kpi-item--attention"><span class="kpi-label">待处理事项</span><strong>{{ attentionTotal }}</strong><small>需要管理员关注</small></div>
</section>
<div class="dashboard-grid">
<section class="dashboard-panel trend-panel">
<div class="panel-head"><div><h2>经营趋势</h2><p>最近 {{ days }} 天预约、完成和营业额</p></div><span class="panel-date">截至 {{ overview.date }}</span></div>
<div class="trend-chart" :class="{ 'trend-chart--empty': !hasTrend }">
<div v-for="item in overview.trend" :key="item.date" class="trend-column">
<div class="trend-bars">
<span class="trend-bar trend-bar--appointment" :style="{ height: `${barHeight(item.appointmentCount, maxTrendCount)}%` }" :title="`预约 ${item.appointmentCount}`" />
<span class="trend-bar trend-bar--completed" :style="{ height: `${barHeight(item.completedCount, maxTrendCount)}%` }" :title="`完成 ${item.completedCount}`" />
</div>
<strong>{{ shortDate(item.date) }}</strong>
<small>¥{{ money(item.amount) }}</small>
</div>
<div v-if="!hasTrend" class="empty-state">暂无趋势数据</div>
</div>
<div class="chart-legend"><span><i class="legend-dot legend-dot--appointment" />预约</span><span><i class="legend-dot legend-dot--completed" />完成</span><span class="legend-note">柱高按数量,金额显示在日期下方</span></div>
</section>
<section class="dashboard-panel attention-panel">
<div class="panel-head"><div><h2>待处理事项</h2><p>需要管理员进一步处理的业务</p></div><span class="attention-total">{{ attentionTotal }}</span></div>
<div class="attention-list">
<button v-for="item in attentionItems" :key="item.key" type="button" class="attention-row" @click="go(item.path)">
<span class="attention-icon" :class="`attention-icon--${item.tone}`"><component :is="item.icon" /></span>
<span class="attention-copy"><strong>{{ item.label }}</strong><small>{{ item.hint }}</small></span>
<b>{{ item.count }}</b><span class="attention-arrow">›</span>
</button>
<div v-if="attentionTotal === 0" class="empty-state empty-state--inline">当前没有待处理事项</div>
</div>
</section>
</div>
<div class="dashboard-grid dashboard-grid--lower">
<section class="dashboard-panel ranking-panel">
<div class="panel-head"><div><h2>门店经营排行</h2><p>按统计范围内的营业额排序</p></div><span class="panel-date">Top 10</span></div>
<div v-if="overview.shopRanking.length" class="ranking-list">
<div v-for="(shop, index) in overview.shopRanking" :key="String(shop.shopId)" class="ranking-row">
<span class="ranking-index">{{ String(index + 1).padStart(2, '0') }}</span>
<span class="ranking-copy"><strong>{{ shop.shopName || '未命名门店' }}</strong><small>{{ shop.appointmentCount }} 次预约 · {{ shop.completedCount }} 次完成</small></span>
<strong class="ranking-amount">¥{{ money(shop.amount) }}</strong>
</div>
</div>
<div v-else class="empty-state">暂无门店经营数据</div>
</section>
<section class="dashboard-panel assets-panel">
<div class="panel-head"><div><h2>平台资产规模</h2><p>当前启用的 Salon 业务资源</p></div></div>
<div class="asset-list">
<div class="asset-row"><span><i class="asset-mark asset-mark--shop" />门店</span><strong>{{ overview.platform.activeShopCount }}</strong><small>启用中</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--manager" />店长</span><strong>{{ overview.platform.activeManagerCount }}</strong><small>有效账号</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--staff" />员工</span><strong>{{ overview.platform.activeStaffCount }}</strong><small>有效账号</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--customer" />客户</span><strong>{{ overview.platform.customerCount }}</strong><small>业务资料</small></div>
<div class="asset-row"><span><i class="asset-mark asset-mark--style" />款式</span><strong>{{ overview.platform.styleCount }}</strong><small>已公开</small></div>
</div>
</section>
</div>
</main>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ReloadOutlined, AuditOutlined, SafetyCertificateOutlined, ShoppingOutlined, TeamOutlined, WarningOutlined } from '@ant-design/icons-vue'
import { adminDashboardApi, type SalonDashboardOverviewVO } from '@/api/admin'
const router = useRouter()
const localDate = () => {
const now = new Date()
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
}
const date = ref(localDate())
const days = ref<7 | 30>(7)
const loading = ref(false)
const lastRefreshedAt = ref('')
const overview = ref<SalonDashboardOverviewVO>(emptyOverview(date.value, days.value))
const ranges = [{ label: '7 天', value: 7 as const }, { label: '30 天', value: 30 as const }]
const currentDateLabel = computed(() => localDate())
function emptyOverview(targetDate: string, range: number): SalonDashboardOverviewVO {
return {
date: targetDate,
degraded: false,
platform: { activeShopCount: 0, activeManagerCount: 0, activeStaffCount: 0, customerCount: 0, styleCount: 0 },
today: { appointmentCount: 0, serviceInProgressCount: 0, completedServiceCount: 0, orderAmount: 0, pendingOrderCount: 0 },
attention: { registrationReviewCount: 0, contentReviewCount: 0, afterSaleCount: 0, artistChangeCount: 0, lowStockCount: 0 },
trend: Array.from({ length: range }, (_, index) => ({ date: new Date(Date.parse(targetDate) - (range - index - 1) * 86400000).toISOString().slice(0, 10), appointmentCount: 0, completedCount: 0, amount: 0 })),
shopRanking: []
}
}
const attentionTotal = computed(() => Object.values(overview.value.attention).reduce((sum, value) => sum + Number(value || 0), 0))
const selectedToday = computed(() => date.value === localDate())
const attentionItems = computed(() => [
{ key: 'registration', label: '注册审核', hint: '员工与店长申请', count: overview.value.attention.registrationReviewCount, path: '/admin/registrations', tone: 'mint', icon: AuditOutlined },
{ key: 'content', label: '内容复核', hint: '文字与图片审核', count: overview.value.attention.contentReviewCount, path: '/admin/privacy', tone: 'blue', icon: SafetyCertificateOutlined },
{ key: 'afterSale', label: '售后处理', hint: '等待管理员处理', count: overview.value.attention.afterSaleCount, path: '/admin/after-sales', tone: 'amber', icon: ShoppingOutlined },
{ key: 'artistChange', label: '改派申请', hint: '等待重新分配员工', count: overview.value.attention.artistChangeCount, path: '/admin/orders', tone: 'violet', icon: TeamOutlined },
{ key: 'stock', label: '库存异常', hint: '低于库存预警线', count: overview.value.attention.lowStockCount, path: '/admin/inventory', tone: 'red', icon: WarningOutlined }
].filter(item => item.count > 0))
const hasTrend = computed(() => overview.value.trend.some(item => item.appointmentCount || item.completedCount || item.amount))
const maxTrendCount = computed(() => Math.max(1, ...overview.value.trend.flatMap(item => [item.appointmentCount, item.completedCount])))
const money = (value: number | undefined) => Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
const shortDate = (value: string) => value.slice(5).replace('-', '/')
const barHeight = (value: number, max: number) => value ? Math.max(9, Math.round(value / max * 100)) : 3
const go = (path: string) => router.push(path)
const loadOverview = async () => {
loading.value = true
try {
const result = await adminDashboardApi.getOverview({ date: date.value, days: days.value })
overview.value = result || emptyOverview(date.value, days.value)
} catch (error: any) {
overview.value = { ...emptyOverview(date.value, days.value), degraded: true, degradedMessage: error?.message || '经营数据加载失败' }
} finally {
lastRefreshedAt.value = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
loading.value = false
}
}
const changeRange = (range: 7 | 30) => {
days.value = range
void loadOverview()
}
onMounted(() => { void loadOverview() })
</script>
<style scoped>
.salon-dashboard { display: grid; gap: 22px; color: var(--admin-mobile-ink); }
.dashboard-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px; padding-bottom: 5px; }
.dashboard-eyebrow { color: var(--theme-primary-action); font-size: 11px; font-weight: 800; letter-spacing: .16em; }
.dashboard-head h1 { margin: 7px 0 5px; font-size: 32px; }
.dashboard-head p { margin: 0; color: var(--admin-mobile-muted); font-size: 13px; }
.dashboard-freshness { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 8px; color: var(--admin-mobile-muted); font-size: 11px; }
.dashboard-tools { display: flex; align-items: flex-end; gap: 9px; flex-wrap: wrap; justify-content: flex-end; }
.date-control { display: grid; gap: 5px; color: var(--admin-mobile-muted); font-size: 11px; }
.date-control input { height: 34px; padding: 0 9px; border: 1px solid var(--admin-mobile-border); border-radius: 8px; background: var(--theme-card-bg); color: var(--admin-mobile-ink); font: inherit; }
.range-control { display: flex; height: 34px; padding: 3px; border: 1px solid var(--admin-mobile-border); border-radius: 8px; background: var(--theme-card-bg); }
.range-control button, .refresh-button { border: 0; border-radius: 6px; background: transparent; color: var(--admin-mobile-muted); font: inherit; font-size: 12px; cursor: pointer; }
.range-control button { padding: 0 11px; }
.range-control button.active { background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 700; }
.refresh-button { display: inline-flex; height: 34px; align-items: center; gap: 5px; padding: 0 11px; border: 1px solid var(--admin-mobile-border); background: var(--theme-card-bg); }
.refresh-button:disabled { cursor: wait; opacity: .6; }
.dashboard-alert { margin: -4px 0 0; }
.kpi-strip { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); border-top: 1px solid var(--admin-mobile-border); border-bottom: 1px solid var(--admin-mobile-border); background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent); }
.kpi-item { display: grid; gap: 6px; min-height: 128px; padding: 20px 18px; border-right: 1px solid var(--admin-mobile-border); }
.kpi-item:last-child { border-right: 0; }
.kpi-label { color: var(--admin-mobile-muted); font-size: 12px; }
.kpi-item strong { color: var(--admin-mobile-ink); font-size: 29px; }
.kpi-item small { color: var(--admin-mobile-muted); font-size: 11px; }
.kpi-item--primary strong { color: var(--theme-primary-action); }
.kpi-item--attention strong { color: #be7951; }
.dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.65fr) minmax(300px, .95fr); gap: 18px; }
.dashboard-grid--lower { grid-template-columns: minmax(0, 1.2fr) minmax(320px, .8fr); }
.dashboard-panel { min-width: 0; border-top: 2px solid var(--theme-primary); background: color-mix(in srgb, var(--theme-card-bg) 78%, transparent); }
.panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; padding: 17px 0 13px; border-bottom: 1px solid var(--admin-mobile-border); }
.panel-head h2 { margin: 0 0 4px; font-size: 16px; }
.panel-head p, .panel-date { margin: 0; color: var(--admin-mobile-muted); font-size: 11px; }
.panel-date { white-space: nowrap; }
.trend-chart { display: grid; grid-template-columns: repeat(auto-fit, minmax(34px, 1fr)); align-items: end; gap: 9px; min-height: 230px; padding: 22px 4px 9px; border-bottom: 1px solid var(--admin-mobile-border); }
.trend-column { display: grid; min-width: 0; gap: 6px; align-items: end; text-align: center; }
.trend-bars { display: flex; height: 150px; align-items: end; justify-content: center; gap: 3px; border-bottom: 1px solid var(--admin-mobile-border); }
.trend-bar { display: block; width: 9px; min-height: 3px; border-radius: 3px 3px 0 0; transition: height .25s ease; }
.trend-bar--appointment { background: #55bfa4; }
.trend-bar--completed { background: #275f58; }
.trend-column strong { color: var(--admin-mobile-ink); font-size: 10px; font-weight: 700; }
.trend-column small { overflow: hidden; color: var(--admin-mobile-muted); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
.chart-legend { display: flex; align-items: center; gap: 15px; padding-top: 12px; color: var(--admin-mobile-muted); font-size: 11px; }
.chart-legend span { display: inline-flex; align-items: center; gap: 5px; }
.legend-dot { width: 7px; height: 7px; border-radius: 50%; }
.legend-dot--appointment { background: #55bfa4; }.legend-dot--completed { background: #275f58; }.legend-note { margin-left: auto; }
.attention-total { display: grid; place-items: center; min-width: 27px; height: 27px; border-radius: 50%; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 12px; font-weight: 800; }
.attention-list { display: grid; }
.attention-row { display: flex; align-items: center; gap: 10px; min-height: 60px; padding: 9px 0; border: 0; border-bottom: 1px solid var(--admin-mobile-border); background: transparent; color: inherit; text-align: left; cursor: pointer; }
.attention-row:hover { background: var(--admin-mobile-accent-soft); }
.attention-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; font-size: 14px; }
.attention-icon--mint { background: #e2f5ee; color: #2a9a7f; }.attention-icon--blue { background: #e5f0fa; color: #397ba8; }.attention-icon--amber { background: #fff2d9; color: #b77a27; }.attention-icon--violet { background: #eee8fa; color: #7559a5; }.attention-icon--red { background: #fde8e4; color: #bd665d; }
.attention-copy { display: grid; flex: 1; gap: 2px; min-width: 0; }.attention-copy strong { font-size: 12px; }.attention-copy small { color: var(--admin-mobile-muted); font-size: 10px; }.attention-row b { color: var(--admin-mobile-ink); font-size: 14px; }.attention-arrow { color: var(--admin-mobile-muted); font-size: 20px; }
.ranking-list, .asset-list { display: grid; }
.ranking-row { display: flex; align-items: center; gap: 12px; min-height: 61px; border-bottom: 1px solid var(--admin-mobile-border); }
.ranking-index { width: 26px; color: var(--theme-primary-action); font-size: 11px; font-weight: 800; }.ranking-copy { display: grid; flex: 1; gap: 3px; min-width: 0; }.ranking-copy strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.ranking-copy small { color: var(--admin-mobile-muted); font-size: 10px; }.ranking-amount { font-size: 12px; white-space: nowrap; }
.asset-row { display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 12px; min-height: 50px; border-bottom: 1px solid var(--admin-mobile-border); }.asset-row span { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; }.asset-row strong { font-size: 16px; }.asset-row small { width: 46px; color: var(--admin-mobile-muted); font-size: 10px; text-align: right; }.asset-mark { width: 7px; height: 7px; border-radius: 50%; background: var(--theme-primary); }.asset-mark--manager { background: #6f9fd1; }.asset-mark--staff { background: #a887d1; }.asset-mark--customer { background: #d89b64; }.asset-mark--style { background: #78a8a1; }
.empty-state { display: grid; place-items: center; min-height: 160px; color: var(--admin-mobile-muted); font-size: 12px; }.empty-state--inline { min-height: 180px; }.trend-chart--empty { opacity: .8; }
@media (max-width: 1000px) { .dashboard-head { align-items: flex-start; flex-direction: column; }.dashboard-tools { justify-content: flex-start; }.dashboard-grid, .dashboard-grid--lower { grid-template-columns: 1fr; } }
@media (max-width: 680px) { .dashboard-head h1 { font-size: 27px; } }
@media (max-width: 680px) { .dashboard-head h1 { font-size: 27px; }.kpi-strip { grid-template-columns: repeat(2, 1fr); }.kpi-item { min-height: 100px; padding: 15px 13px; }.kpi-item:nth-child(2n) { border-right: 0; }.kpi-item:nth-child(-n+3) { border-bottom: 1px solid var(--admin-mobile-border); }.kpi-item strong { font-size: 24px; }.trend-chart { gap: 3px; }.trend-bar { width: 6px; }.chart-legend { flex-wrap: wrap; }.legend-note { width: 100%; margin-left: 0; }.dashboard-tools { width: 100%; }.date-control { flex: 1; }.date-control input { width: 100%; }.range-control button { padding: 0 8px; } }
</style>
@@ -110,8 +110,8 @@
<section v-else class="settings-section-panel">
<div class="pane-head">
<div>
<h2>当前账号</h2>
<p>查看后台账号、权限范围和当前门店,不与小程序账号设置混用。</p>
<h2>管理员账号</h2>
<p>查看后台登录账号与当前会话状态。</p>
</div>
<span class="account-status"><i />会话正常</span>
</div>
@@ -128,27 +128,10 @@
<div class="setting-value">{{ userInfo?.nickname || '未设置昵称' }}</div>
<span class="control-note">只读</span>
</div>
<div class="setting-row">
<div class="setting-copy"><strong>角色</strong><span>当前后台角色与平台管理范围。</span></div>
<div class="setting-value">{{ roleLabel }}</div>
<span v-if="isPlatformOverview" class="status-pill">平台总览</span>
<span v-else class="control-note">只读</span>
</div>
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>权限范围</strong><span>当前账号可访问的功能权限数量。</span></div>
<div class="setting-value">{{ permissionCount }} 项权限</div>
<span class="control-note">{{ shopScopeText }}</span>
</div>
</div>
<div class="setting-group">
<div class="setting-group__head"><strong>{{ isPlatformOverview ? '管理范围' : '当前门店' }}</strong><span>SHOP</span></div>
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>{{ isPlatformOverview ? '平台总览模式' : '门店上下文' }}</strong><span>{{ isPlatformOverview ? '平台管理员可查看全平台数据。' : '切换后会刷新权限和业务数据上下文。' }}</span></div>
<div v-if="isPlatformOverview" class="setting-value">平台总览模式</div>
<a-select v-else-if="shopOptions.length > 1" v-model:value="selectedShopId" class="account-shop-select" :options="shopSelectOptions" :loading="shopSwitchLoading" @change="handleShopChange" />
<div v-else class="setting-value">{{ currentShopName }}</div>
<span class="control-note">{{ shopOptions.length > 1 ? `${shopOptions.length} 家可用门店` : '当前会话' }}</span>
<div class="setting-copy"><strong>后台会话</strong><span>后台请求使用管理员身份校验,退出登录后当前会话立即失效。</span></div>
<div class="setting-value">{{ userInfo?.id ? '已登录' : '状态未知' }}</div>
<span class="status-pill" :class="{ 'is-muted': !userInfo?.id }">{{ userInfo?.id ? '正常' : '待验证' }}</span>
</div>
</div>
</section>
@@ -158,15 +141,12 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { ApiOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { adminAuthApi, adminSystemParameterConfigApi, type SystemParameterConfigVO } from '@/api/admin'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { notifyShopThemeChanged } from '@/utils/shop-theme'
import { getAdminCurrentShopName, getAdminRoleLabel, getAdminShopOptions, isBootstrapAdminUser, loadCachedAdminUserInfo } from './admin-helpers'
import { adminSystemParameterConfigApi, type SystemParameterConfigVO } from '@/api/admin'
import { loadCachedAdminUserInfo } from '@/utils/admin-session'
type SettingsSection = 'runtime' | 'services' | 'account'
type MapKey = 'tencentWeb' | 'amapWeb' | 'amapMini'
@@ -178,7 +158,6 @@ const savingDefaultPassword = ref(false)
const savingReviewNotice = ref(false)
const savingMap = ref(false)
const savingSmsProvider = ref(false)
const shopSwitchLoading = ref(false)
const defaultPasswordEnabled = ref(true)
const reviewNoticeEnabled = ref(true)
const mapEnabled = ref(true)
@@ -221,27 +200,6 @@ const mapForms = reactive<Record<MapKey | 'provider', SystemParameterConfigVO>>(
})
const userInfo = ref(loadCachedAdminUserInfo())
const selectedShopId = ref(userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined)
const { userPermissions, loadUserPermissions } = usePermission()
const currentShopName = computed(() => getAdminCurrentShopName(userInfo.value))
const isPlatformOverview = computed(() => isBootstrapAdminUser(userInfo.value))
const roleLabel = computed(() => getAdminRoleLabel(userInfo.value?.type))
const shopOptions = computed(() => getAdminShopOptions(userInfo.value))
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
const permissionCount = computed(() => userPermissions.value.length)
const shopScopeText = computed(() => shopOptions.value.length ? shopOptions.value.map(item => item.name).join(' / ') : (isPlatformOverview.value ? '平台总览模式' : '游客模式'))
const persistAdminSession = (payload: any) => {
localStorage.setItem('adminAccessToken', payload.accessToken)
localStorage.setItem('adminRefreshToken', payload.refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(payload.userInfo))
sessionStorage.setItem('adminAccessToken', payload.accessToken)
}
const refreshLocalUserInfo = () => {
userInfo.value = loadCachedAdminUserInfo()
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
}
const load = async () => {
loading.value = true
@@ -271,8 +229,7 @@ const load = async () => {
if (mapByKey.AMAP_MINI_KEY) Object.assign(mapForms.amapMini, mapByKey.AMAP_MINI_KEY)
mapForms.provider.configValue = mapForms.provider.configValue === 'AMAP' ? 'AMAP' : 'TENCENT'
mapEnabled.value = mapForms.provider.enabled === 1
refreshLocalUserInfo()
await loadUserPermissions()
userInfo.value = loadCachedAdminUserInfo()
} catch (error) {
message.error(error instanceof Error ? error.message : '系统设置加载失败')
} finally {
@@ -348,27 +305,6 @@ const saveSmsProvider = async () => {
}
}
const handleShopChange = async (shopId: unknown) => {
if ((typeof shopId !== 'string' && typeof shopId !== 'number') || !String(shopId) || String(shopId) === String(userInfo.value?.shopId || '')) return
shopSwitchLoading.value = true
try {
await runWithGlobalLoading(async () => {
const response = await adminAuthApi.switchShop(String(shopId))
persistAdminSession(response as any)
refreshLocalUserInfo()
await loadUserPermissions()
notifyShopThemeChanged()
})
message.success('门店切换成功')
window.location.reload()
} catch (error: any) {
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
message.error(error?.message || '切换门店失败')
} finally {
shopSwitchLoading.value = false
}
}
onMounted(() => {
void load()
})
@@ -418,7 +354,6 @@ onMounted(() => {
.warning-note { display: inline-flex; align-items: center; gap: 5px; color: #a66d22; font-size: 11px; white-space: nowrap; }
.warning-note::before { content: '!'; display: inline-flex; align-items: center; justify-content: center; width: 14px; height: 14px; border-radius: 50%; background: #fff3d9; font-size: 10px; font-weight: 800; }
.section-footnote { margin: 12px 2px 0; color: var(--admin-mobile-muted); font-size: 11px; }
.account-shop-select { width: 100%; min-width: 0; }
@media (max-width: 760px) {
.settings-header { align-items: flex-start; }
.settings-health, .account-status { display: none; }
@@ -1,45 +0,0 @@
/**
* Purpose: AdminCachedUserInfo supports admin-helpers.ts by holding or executing the admin cached user info 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.
*/
import { loadCachedAdminUserInfo, isBootstrapAdminUser, type AdminCachedUserInfo } from '@/utils/admin-session'
export { loadCachedAdminUserInfo, isBootstrapAdminUser }
export type { AdminCachedUserInfo }
/**
* Purpose: getAdminRoleLabel supports admin-helpers.ts by holding or executing the get admin role label 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 getAdminRoleLabel = (type?: number) => {
switch (type) {
case 4:
return '平台管理员'
case 2:
return '店长'
case 3:
return '店员'
default:
return '后台账号'
}
}
/**
* Purpose: getAdminShopOptions supports admin-helpers.ts by holding or executing the get admin shop options 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 getAdminShopOptions = (userInfo?: AdminCachedUserInfo | null) => {
const ids = userInfo?.shopIds || []
const names = userInfo?.shopNames || []
return ids.map((id, index) => ({
id: String(id),
name: names[index] || `门店 ${id}`
}))
}
/**
* Purpose: getAdminCurrentShopName supports admin-helpers.ts by holding or executing the get admin current shop name 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 getAdminCurrentShopName = (userInfo?: AdminCachedUserInfo | null) =>
userInfo?.shopName || (isBootstrapAdminUser(userInfo) ? '平台总览模式' : '游客模式')
@@ -5,7 +5,7 @@ describe('auth-free API contract', () => {
it('covers public paths and rejects protected business APIs', () => {
expect(isApiAuthFreePath('/comment/list/product/1')).toBe(true)
expect(isApiAuthFreePath('/user/wechat-mini/auto-login')).toBe(true)
expect(isApiAuthFreePath('/admin/auth/login-shops/1')).toBe(true)
expect(isApiAuthFreePath('/admin/auth/login-shops/1')).toBe(false)
expect(isApiAuthFreePath('/nail-artist/profile/1')).toBe(true)
expect(isApiAuthFreePath('/nail-artist/1/availability')).toBe(true)
expect(isApiAuthFreePath('/nail-artist/1/reviews')).toBe(true)
@@ -14,6 +14,7 @@ vi.mock('ant-design-vue', () => ({
import adminApi, {
adminAfterSaleApi,
adminArtistScheduleApi,
adminAuthApi,
adminCampaignApi,
adminDashboardApi,
adminInventoryApi,
@@ -90,7 +91,8 @@ describe('vNext API contracts', () => {
await adminInventoryApi.saveItem({ itemName: 'Base Gel', category: 'gel', unit: 'bottle', stockQuantity: 12 })
await adminInventoryApi.adjustStock(7, { changeType: 'IN', changeQuantity: 3, remark: 'restock' })
await adminCampaignApi.saveCampaign({ title: 'Summer Set', scene: 'HOME', status: 1 })
await adminDashboardApi.getAnalytics()
await adminDashboardApi.getOverview({ date: '2026-10-25', days: 7 })
await adminAuthApi.changePassword({ currentPassword: 'OldPass1!', newPassword: 'FreshPass2!' })
await adminWorkbenchRegistrationApi.list()
await adminWorkbenchRegistrationApi.approve(12)
await adminWorkbenchRegistrationApi.reject(12, '资料不完整')
@@ -104,7 +106,8 @@ describe('vNext API contracts', () => {
{ method: 'post', url: '/inventory/save', params: undefined, data: { itemName: 'Base Gel', category: 'gel', unit: 'bottle', stockQuantity: 12 } },
{ method: 'post', url: '/inventory/7/adjust', params: undefined, data: { changeType: 'IN', changeQuantity: 3, remark: 'restock' } },
{ method: 'post', url: '/campaign/save', params: undefined, data: { title: 'Summer Set', scene: 'HOME', status: 1 } },
{ method: 'get', url: '/dashboard/analytics', params: undefined, data: undefined },
{ method: 'get', url: '/dashboard/overview', params: { date: '2026-10-25', days: 7 }, data: undefined },
{ method: 'post', url: '/auth/password', params: undefined, data: { currentPassword: 'OldPass1!', newPassword: 'FreshPass2!' } },
{ method: 'get', url: '/user/workbench/registration/list', params: undefined, data: undefined },
{ method: 'post', url: '/user/workbench/registration/12/approve', params: undefined, data: undefined },
{ method: 'post', url: '/user/workbench/registration/12/reject', params: undefined, data: { reason: '资料不完整' } }
@@ -0,0 +1,31 @@
# Salon 后台单管理员与经营驾驶舱设计
## 目标
后台定位为 Salon 平台管理员工作台,只允许 `type = 4` 的账号登录。登录后不选择门店、不加载权限矩阵,所有后台业务请求使用全平台数据范围;小程序和前台仍保留原有店长、员工及权限模型。
## 认证边界
- `/admin/auth/login` 和 `/admin/auth/refresh` 在服务端拒绝非平台管理员。
- 认证拦截器对 `/admin/**`、`/order/admin/**` 只放行平台管理员。
- 权限注解数据继续保留,平台管理员访问后台接口不依赖具体权限编码;非后台业务接口继续使用权限校验。
- 后台前端不请求登录门店列表、不提供门店切换、不展示授权到期或平台总览分支。
## 驾驶舱数据
`GET /admin/dashboard/overview` 接收统计日期和 7/30 天范围,返回平台资产、当日预约/服务/营业额、待处理事项、趋势和门店排行。订单趋势按订单与历史补单的业务日期聚合,已取消订单不计入经营金额;查询失败返回带降级标识的空数据,并沿用短时缓存。
## 前端结构
- 根路由使用 `SalonDashboardView.vue`,展示系统日期和最近刷新时间。
- 固定导航为:首页、账号管理、注册审核、隐私与内容复核、门店管理、系统设置、个人设置。
- 驾驶舱采用宽屏指标条、趋势柱状图、事项列表、门店排行和平台资产列表,移动端降级为纵向布局。
- 个人设置展示管理员账号资料、密码修改和退出登录;管理员改密需校验当前密码及强度,成功后撤销该账号全部会话并要求重新登录。系统设置保留运行参数、服务接入和管理员会话信息。
## 异常处理与兼容
旧 `/dashboard/stats`、`/dashboard/analytics` 后端接口及其响应模型暂保留兼容,前端首页不再调用,避免未知外部调用立即失效。权限表、预约、订单、库存等 Salon 业务页面保留,管理员前端权限工具对 `type = 4` 直接放行,后端后台门禁仍是最终控制点。
## 验证
使用 Core Maven 编译、Salon 前端单元测试和生产构建验证;以静态引用扫描确认 ArtList 目录和小程序权限模型未修改。
+23
View File
@@ -0,0 +1,23 @@
# Salon 后台残留清理记录
## 已删除或替换
- 删除旧后台首页 `HomeView.vue` 与未再使用的 `DashboardView.vue`。
- 根路由切换为 `SalonDashboardView.vue`,移除旧首页的流量、电商和用户动态指标。
- 删除后台登录的门店列表、门店切换和管理员注册入口。
- 删除前端后台 API 中旧首页统计类型和调用包装,保留业务页面需要的通用接口。
- 删除个人设置中的角色、权限数量、门店上下文与门店切换展示。
- 个人设置现可修改管理员密码;密码服务独立于共享用户服务,保存成功撤销管理员全部会话并返回登录页。
## 保留项及原因
- 后端 `/dashboard/stats`、`/dashboard/analytics` 及其旧指标 VO 保留为兼容接口,未发现仓库内前端调用,但不排除仓库外消费者;新首页只使用聚合式 `/dashboard/overview`。
- 权限表、`PermissionsView.vue` 和权限注解保留,供小程序、前台兼容接口及存量数据使用;平台管理员后台不依赖具体权限编码。
- 订单、售后、库存、排班、作品和消息页面及接口保留,作为 Salon 后续经营管理能力,不因首页重构误删。
- ArtList 前端、Core 和业务接口未修改。
## 检查结果
- 后台路由固定到 Salon 管理菜单,非管理员无法通过服务端后台门禁。
- 首页不再出现浏览量、收藏、加购和 ArtList 用户动态等旧指标。
- ArtList 目录及代码没有改动;兼容接口依旧保留,未作为 Salon 管理首页展示。
+10
View File
@@ -1,5 +1,15 @@
# 项目变更记录
## 2026-10-25 Salon 后台单管理员与经营驾驶舱重构
- 后台登录、Token 刷新和后台请求统一限制为 `type = 4` 平台管理员;删除后台门店预选、门店切换和管理员注册入口。
- 根页面改为 Salon 管理驾驶舱,新增全平台门店、员工、客户、款式、预约、服务、营业额、审核事项和门店排行展示,支持日期与 7/30 天范围切换。
- 清理旧首页 ArtList 流量/电商指标及重复首页文件;个人设置和系统设置移除角色、权限矩阵、门店上下文与授权到期分支。
- 保留权限表和旧统计接口作为兼容能力,小程序与前台权限模型未修改;后台管理员前端不再请求权限列表。
- 将后台 Token 刷新拆为管理员专用入口,普通用户刷新继续沿用原有门店会话规则;登录页移除无业务意义的模糊装饰。
- GitNexus 对共享认证符号执行影响检查,结果包含未知/高风险项;以静态引用、Core 编译、前端单测和生产构建完成替代验证。
- 后台个人设置新增管理员密码修改:服务端校验当前密码和强度,保存成功后撤销该管理员全部会话;前端清理本地后台会话并返回登录页。驾驶舱补充系统日期和最近刷新时间。
## 2026-10-25 Salon 后台系统设置重构
- 系统设置改为左侧分类导航和紧凑设置行,分为运行参数、服务接入、当前账号;运行参数、地图和短信分别保存。