Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1614c7d45 | ||
|
|
886e2748d5 | ||
|
|
1a5aa9b3ef | ||
|
|
0140bb0cc8 |
+43
@@ -194,4 +194,47 @@ public class CheckInHandler {
|
|||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询所有签到记录(支持排序)
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/admin/records
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getAllSignInRecords(ServerRequest request) {
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
String sortBy = request.queryParam("sortBy").orElse("signInTime");
|
||||||
|
String sortOrder = request.queryParam("sortOrder").orElse("desc");
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("管理员查询所有签到记录, startDate: {}, endDate: {}, sortBy: {}, sortOrder: {}", startDate, endDate, sortBy, sortOrder);
|
||||||
|
|
||||||
|
return checkService.getAllSignInRecords(startDate, endDate, sortBy, sortOrder)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(records -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", records)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询签到统计(不限会员)
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/admin/statistics
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getAllSignInStatistics(ServerRequest request) {
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("管理员查询签到统计, startDate: {}, endDate: {}", startDate, endDate);
|
||||||
|
|
||||||
|
return checkService.getAllSignInStats(startDate, endDate)
|
||||||
|
.flatMap(stats -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
@@ -57,6 +57,12 @@ public interface SignInRecordRepository extends R2dbcRepository<SignInRecord, Lo
|
|||||||
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
Flux<SignInRecord> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
Flux<SignInRecord> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据时间范围查询签到记录(支持动态排序)
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByTimeRangeSorted(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 统计会员在时间范围内的签到次数
|
* 统计会员在时间范围内的签到次数
|
||||||
*/
|
*/
|
||||||
|
|||||||
+16
@@ -78,4 +78,20 @@ public interface ICheckInService {
|
|||||||
* @return 签到统计VO
|
* @return 签到统计VO
|
||||||
*/
|
*/
|
||||||
Mono<SignInStatsVO> getDailySignInStats(LocalDate date);
|
Mono<SignInStatsVO> getDailySignInStats(LocalDate date);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询所有签到记录(支持排序)
|
||||||
|
*
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @param sortBy 排序字段
|
||||||
|
* @param sortOrder 排序方向
|
||||||
|
* @return 签到记录列表(含会员姓名、卡类型)
|
||||||
|
*/
|
||||||
|
Flux<SignInRecordVO> getAllSignInRecords(LocalDate startTime, LocalDate endTime, String sortBy, String sortOrder);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询签到统计(不限会员)
|
||||||
|
*/
|
||||||
|
Mono<SignInStatsVO> getAllSignInStats(LocalDate startTime, LocalDate endTime);
|
||||||
}
|
}
|
||||||
|
|||||||
+81
-1
@@ -16,11 +16,13 @@ import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
|||||||
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||||
|
import cn.novalon.gym.manage.member.entity.Member;
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
import cn.novalon.gym.manage.member.repository.IMemberRepository;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -47,6 +49,7 @@ public class CheckServiceImpl implements ICheckInService {
|
|||||||
private final MemberCardRepository memberCardRepository;
|
private final MemberCardRepository memberCardRepository;
|
||||||
private final SignInRecordRepository signInRecordRepository;
|
private final SignInRecordRepository signInRecordRepository;
|
||||||
private final IGroupCourseBookingService groupCourseBookingService;
|
private final IGroupCourseBookingService groupCourseBookingService;
|
||||||
|
private final IMemberRepository memberRepository;
|
||||||
|
|
||||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||||
|
|
||||||
@@ -430,6 +433,83 @@ public class CheckServiceImpl implements ICheckInService {
|
|||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Flux<SignInRecordVO> getAllSignInRecords(LocalDate startTime, LocalDate endTime, String sortBy, String sortOrder) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
Flux<SignInRecord> recordFlux = signInRecordRepository.findByTimeRangeSorted(start, end);
|
||||||
|
|
||||||
|
return recordFlux
|
||||||
|
.flatMap(record -> {
|
||||||
|
// fetch member name
|
||||||
|
Mono<String> memberNameMono = memberRepository.findById(record.getMemberId())
|
||||||
|
.map(Member::getNickname)
|
||||||
|
.defaultIfEmpty("未知");
|
||||||
|
// fetch card type name
|
||||||
|
Mono<String> cardTypeMono = record.getMemberCardId() != null
|
||||||
|
? memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(record.getMemberCardId())
|
||||||
|
.map(MemberCard::getMemberCardName)
|
||||||
|
.defaultIfEmpty("未知")
|
||||||
|
: Mono.just("-");
|
||||||
|
return Mono.zip(memberNameMono, cardTypeMono)
|
||||||
|
.map(tuple -> {
|
||||||
|
SignInRecordVO vo = convertToVO(record);
|
||||||
|
vo.setMemberName(tuple.getT1());
|
||||||
|
vo.setMemberCardType(tuple.getT2());
|
||||||
|
return vo;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.collectList()
|
||||||
|
.flatMapMany(list -> {
|
||||||
|
// in-memory sort
|
||||||
|
boolean asc = "asc".equalsIgnoreCase(sortOrder);
|
||||||
|
java.util.Comparator<SignInRecordVO> comparator;
|
||||||
|
switch (sortBy != null ? sortBy : "signInTime") {
|
||||||
|
case "id":
|
||||||
|
comparator = java.util.Comparator.comparing(SignInRecordVO::getId, java.util.Comparator.nullsLast(Long::compareTo));
|
||||||
|
break;
|
||||||
|
case "memberName":
|
||||||
|
comparator = java.util.Comparator.comparing(SignInRecordVO::getMemberName, java.util.Comparator.nullsLast(String::compareTo));
|
||||||
|
break;
|
||||||
|
case "signInTime":
|
||||||
|
default:
|
||||||
|
comparator = java.util.Comparator.comparing(SignInRecordVO::getSignInTime, java.util.Comparator.nullsLast(java.time.LocalDateTime::compareTo));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!asc) {
|
||||||
|
comparator = comparator.reversed();
|
||||||
|
}
|
||||||
|
list.sort(comparator);
|
||||||
|
return Flux.fromIterable(list);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatsVO> getAllSignInStats(LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return Mono.zip(
|
||||||
|
(Object[] results) -> {
|
||||||
|
Long total = (Long) results[0];
|
||||||
|
Long success = (Long) results[1];
|
||||||
|
Long members = (Long) results[2];
|
||||||
|
SignInStatsVO stats = new SignInStatsVO();
|
||||||
|
stats.setTotalCount(total);
|
||||||
|
stats.setSuccessCount(success);
|
||||||
|
stats.setStartDate(startTime);
|
||||||
|
stats.setEndDate(endTime);
|
||||||
|
stats.setUniqueMemberCount(members);
|
||||||
|
stats.setSuccessRate(total > 0 ? (double) success / total * 100.0 : 0.0);
|
||||||
|
return stats;
|
||||||
|
},
|
||||||
|
signInRecordRepository.countByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countSuccessByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countDistinctMembersByTimeRange(start, end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private long getSecondsUntilEndOfDay() {
|
private long getSecondsUntilEndOfDay() {
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
||||||
|
|||||||
+10
@@ -59,6 +59,16 @@ public class SignInRecordVO {
|
|||||||
*/
|
*/
|
||||||
private String source;
|
private String source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员姓名(关联查询)
|
||||||
|
*/
|
||||||
|
private String memberName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员卡类型名称(关联查询)
|
||||||
|
*/
|
||||||
|
private String memberCardType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建时间
|
* 创建时间
|
||||||
*/
|
*/
|
||||||
|
|||||||
+2
-2
@@ -26,7 +26,7 @@ public class DataStatisticsDao {
|
|||||||
* 统计指定时间范围内新增会员数
|
* 统计指定时间范围内新增会员数
|
||||||
*/
|
*/
|
||||||
public Mono<Long> countNewMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
public Mono<Long> countNewMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE created_at >= :startTime AND created_at < :endTime AND is_deleted = false")
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE created_at >= :startTime AND created_at < :endTime AND deleted_at IS NULL")
|
||||||
.bind("startTime", startTime)
|
.bind("startTime", startTime)
|
||||||
.bind("endTime", endTime)
|
.bind("endTime", endTime)
|
||||||
.map(row -> row.get(0, Long.class))
|
.map(row -> row.get(0, Long.class))
|
||||||
@@ -37,7 +37,7 @@ public class DataStatisticsDao {
|
|||||||
* 统计总会员数
|
* 统计总会员数
|
||||||
*/
|
*/
|
||||||
public Mono<Long> countTotalMembers() {
|
public Mono<Long> countTotalMembers() {
|
||||||
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE is_deleted = false")
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE deleted_at IS NULL")
|
||||||
.map(row -> row.get(0, Long.class))
|
.map(row -> row.get(0, Long.class))
|
||||||
.one();
|
.one();
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -4,6 +4,8 @@ import cn.novalon.gym.manage.datacount.domain.*;
|
|||||||
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
@@ -25,6 +27,8 @@ import java.time.format.DateTimeFormatter;
|
|||||||
@Tag(name = "数据统计", description = "数据统计相关操作")
|
@Tag(name = "数据统计", description = "数据统计相关操作")
|
||||||
public class DataStatisticsHandler {
|
public class DataStatisticsHandler {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DataStatisticsHandler.class);
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IDataStatisticsService dataStatisticsService;
|
private IDataStatisticsService dataStatisticsService;
|
||||||
|
|
||||||
@@ -35,6 +39,7 @@ public class DataStatisticsHandler {
|
|||||||
return dataStatisticsService.getStatisticsSummaryWithCache(query)
|
return dataStatisticsService.getStatisticsSummaryWithCache(query)
|
||||||
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
||||||
.onErrorResume(e -> {
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取综合统计数据失败", e);
|
||||||
StatisticsSummary errorSummary = StatisticsSummary.builder()
|
StatisticsSummary errorSummary = StatisticsSummary.builder()
|
||||||
.statDate(LocalDateTime.now().toLocalDate().toString())
|
.statDate(LocalDateTime.now().toLocalDate().toString())
|
||||||
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
|
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
|
||||||
|
|||||||
+82
-9
@@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
@@ -22,7 +23,9 @@ import java.time.LocalDate;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -173,9 +176,25 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
|
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
|
||||||
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query);
|
String statDate = query.getStartTime() != null
|
||||||
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query);
|
? query.getStartTime().toLocalDate().toString()
|
||||||
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query);
|
: LocalDateTime.now().toLocalDate().toString();
|
||||||
|
|
||||||
|
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取会员统计数据失败", e);
|
||||||
|
return Mono.just(MemberStatistics.builder().statDate(statDate).build());
|
||||||
|
});
|
||||||
|
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取预约统计数据失败", e);
|
||||||
|
return Mono.just(BookingStatistics.builder().statDate(statDate).build());
|
||||||
|
});
|
||||||
|
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取签到统计数据失败", e);
|
||||||
|
return Mono.just(SignInStatistics.builder().statDate(statDate).build());
|
||||||
|
});
|
||||||
|
|
||||||
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono)
|
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono)
|
||||||
.map(tuple -> StatisticsSummary.builder()
|
.map(tuple -> StatisticsSummary.builder()
|
||||||
@@ -188,21 +207,75 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public reactor.core.publisher.Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
public Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
||||||
// 历史统计数据查询(从Redis缓存中获取)
|
// 历史统计数据查询(从Redis缓存中获取)
|
||||||
String cacheKey = buildCacheKey(query);
|
String cacheKey = buildCacheKey(query);
|
||||||
return redisUtil.get(cacheKey, String.class)
|
return redisUtil.get(cacheKey, String.class)
|
||||||
.flatMapMany(json -> {
|
.flatMapMany(json -> {
|
||||||
try {
|
try {
|
||||||
java.util.List<DataStatistics> stats = objectMapper.readValue(json,
|
List<DataStatistics> stats = objectMapper.readValue(json,
|
||||||
objectMapper.getTypeFactory().constructCollectionType(java.util.List.class, DataStatistics.class));
|
objectMapper.getTypeFactory().constructCollectionType(List.class, DataStatistics.class));
|
||||||
return reactor.core.publisher.Flux.fromIterable(stats);
|
return Flux.fromIterable(stats);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to parse historical statistics from cache", e);
|
log.error("Failed to parse historical statistics from cache", e);
|
||||||
return reactor.core.publisher.Flux.empty();
|
return Flux.empty();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.switchIfEmpty(reactor.core.publisher.Flux.empty());
|
.switchIfEmpty(buildLiveStatistics(query));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缓存未命中时,从数据库实时构建统计数据
|
||||||
|
*/
|
||||||
|
private Flux<DataStatistics> buildLiveStatistics(StatisticsQuery query) {
|
||||||
|
LocalDateTime startTime = getStartTime(query);
|
||||||
|
LocalDateTime endTime = getEndTime(query);
|
||||||
|
String periodType = query.getPeriodType() != null ? query.getPeriodType() : "DAY";
|
||||||
|
LocalDateTime statDate = endTime;
|
||||||
|
|
||||||
|
Mono<Long> memberCountMono = dataStatisticsDao.countNewMembers(startTime, endTime);
|
||||||
|
Mono<Long> totalMembersMono = dataStatisticsDao.countTotalMembers();
|
||||||
|
Mono<Long> bookingCountMono = dataStatisticsDao.countBookings(startTime, endTime);
|
||||||
|
Mono<Long> signInCountMono = dataStatisticsDao.countSignIns(startTime, endTime);
|
||||||
|
|
||||||
|
return Mono.zip(memberCountMono, totalMembersMono, bookingCountMono, signInCountMono)
|
||||||
|
.flatMapMany(tuple -> {
|
||||||
|
long newMembers = tuple.getT1() != null ? tuple.getT1() : 0L;
|
||||||
|
long totalMembers = tuple.getT2() != null ? tuple.getT2() : 0L;
|
||||||
|
long bookings = tuple.getT3() != null ? tuple.getT3() : 0L;
|
||||||
|
long signIns = tuple.getT4() != null ? tuple.getT4() : 0L;
|
||||||
|
|
||||||
|
List<DataStatistics> list = new ArrayList<>();
|
||||||
|
|
||||||
|
DataStatistics memberStat = DataStatistics.builder()
|
||||||
|
.statType(DataStatistics.StatType.MEMBER)
|
||||||
|
.periodType(periodType)
|
||||||
|
.statDate(statDate)
|
||||||
|
.count(totalMembers)
|
||||||
|
.extraData("新增" + newMembers + "人")
|
||||||
|
.build();
|
||||||
|
list.add(memberStat);
|
||||||
|
|
||||||
|
DataStatistics bookingStat = DataStatistics.builder()
|
||||||
|
.statType(DataStatistics.StatType.BOOKING)
|
||||||
|
.periodType(periodType)
|
||||||
|
.statDate(statDate)
|
||||||
|
.count(bookings)
|
||||||
|
.extraData("新增" + bookings + "条预约")
|
||||||
|
.build();
|
||||||
|
list.add(bookingStat);
|
||||||
|
|
||||||
|
DataStatistics signInStat = DataStatistics.builder()
|
||||||
|
.statType(DataStatistics.StatType.SIGN_IN)
|
||||||
|
.periodType(periodType)
|
||||||
|
.statDate(statDate)
|
||||||
|
.count(signIns)
|
||||||
|
.extraData("新增" + signIns + "次签到")
|
||||||
|
.build();
|
||||||
|
list.add(signInStat);
|
||||||
|
|
||||||
|
return Flux.fromIterable(list);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+4
@@ -40,6 +40,10 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
|||||||
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
|
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET deleted_at = NULL, status = '1', updated_at = :updatedAt WHERE id = :id AND deleted_at IS NOT NULL")
|
||||||
|
Mono<Integer> restoreCourse(Long id, LocalDateTime updatedAt);
|
||||||
|
|
||||||
@Modifying
|
@Modifying
|
||||||
@Query("UPDATE group_course SET status = '2', updated_at = :updatedAt WHERE status = '0' AND end_time <= NOW() AND deleted_at IS NULL")
|
@Query("UPDATE group_course SET status = '2', updated_at = :updatedAt WHERE status = '0' AND end_time <= NOW() AND deleted_at IS NULL")
|
||||||
Mono<Integer> completeExpiredCourses(LocalDateTime updatedAt);
|
Mono<Integer> completeExpiredCourses(LocalDateTime updatedAt);
|
||||||
|
|||||||
+4
@@ -29,4 +29,8 @@ public interface GroupCourseTypeDao extends R2dbcRepository<GroupCourseTypeEntit
|
|||||||
@Modifying
|
@Modifying
|
||||||
@Query("UPDATE group_course_type SET deleted_at = :deletedAt WHERE id = :id")
|
@Query("UPDATE group_course_type SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course_type SET type_name = :typeName, base_difficulty = :baseDifficulty, description = :description, category = :category, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateFields(Long id, String typeName, Integer baseDifficulty, String description, String category, LocalDateTime updatedAt);
|
||||||
}
|
}
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.util.OSSUtil;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.codec.multipart.FilePart;
|
||||||
|
import org.springframework.http.codec.multipart.Part;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用文件上传处理器
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@Tag(name = "文件上传", description = "通用文件上传到阿里云OSS")
|
||||||
|
public class CommonUploadHandler {
|
||||||
|
|
||||||
|
@Operation(summary = "上传图片文件", description = "上传图片到阿里云OSS,返回ossKey和预签名URL")
|
||||||
|
public Mono<ServerResponse> uploadImage(ServerRequest request) {
|
||||||
|
return request.multipartData()
|
||||||
|
.flatMap(multiValueMap -> {
|
||||||
|
List<Part> fileParts = multiValueMap.get("file");
|
||||||
|
if (fileParts == null || fileParts.isEmpty()) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "未选择文件"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Part part = fileParts.get(0);
|
||||||
|
if (!(part instanceof FilePart filePart)) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "文件格式不正确"));
|
||||||
|
}
|
||||||
|
|
||||||
|
String originalFilename = filePart.filename();
|
||||||
|
String ext = "";
|
||||||
|
int dotIndex = originalFilename.lastIndexOf('.');
|
||||||
|
if (dotIndex > 0) {
|
||||||
|
ext = originalFilename.substring(dotIndex);
|
||||||
|
}
|
||||||
|
String newFileName = UUID.randomUUID().toString().replace("-", "") + ext;
|
||||||
|
|
||||||
|
Path tempFile = null;
|
||||||
|
try {
|
||||||
|
tempFile = Files.createTempFile("upload-", newFileName);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Mono.error(new RuntimeException("创建临时文件失败", e));
|
||||||
|
}
|
||||||
|
Path finalTempFile = tempFile;
|
||||||
|
|
||||||
|
return filePart.transferTo(finalTempFile)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
try {
|
||||||
|
String ossKey;
|
||||||
|
try (InputStream inputStream = Files.newInputStream(finalTempFile)) {
|
||||||
|
ossKey = OSSUtil.uploadCoverToOSS(inputStream, newFileName);
|
||||||
|
}
|
||||||
|
String presignedUrl = OSSUtil.generatePresignedUrl(ossKey);
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of(
|
||||||
|
"code", 200,
|
||||||
|
"message", "上传成功",
|
||||||
|
"data", Map.of(
|
||||||
|
"ossKey", ossKey,
|
||||||
|
"presignedUrl", presignedUrl,
|
||||||
|
"fileName", originalFilename
|
||||||
|
)
|
||||||
|
));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ServerResponse.status(500)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 500, "message", "上传失败: " + e.getMessage()));
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(finalTempFile);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取OSS预签名URL", description = "根据ossKey生成临时访问URL,有效期5分钟")
|
||||||
|
public Mono<ServerResponse> presignUrl(ServerRequest request) {
|
||||||
|
String ossKey = request.queryParam("key").orElse(null);
|
||||||
|
if (ossKey == null || ossKey.isBlank()) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "参数 key 不能为空"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
String presignedUrl = OSSUtil.generatePresignedUrl(ossKey);
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of(
|
||||||
|
"code", 200,
|
||||||
|
"data", Map.of("presignedUrl", presignedUrl)
|
||||||
|
));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ServerResponse.status(500)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 500, "message", "生成预签名URL失败: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-5
@@ -146,18 +146,25 @@ public class CourseLabelHandler {
|
|||||||
|
|
||||||
return request.bodyToMono(Map.class)
|
return request.bodyToMono(Map.class)
|
||||||
.flatMap(body -> {
|
.flatMap(body -> {
|
||||||
@SuppressWarnings("unchecked")
|
Object labelIdsObj = body.get("labelIds");
|
||||||
List<Integer> labelIdsInt = (List<Integer>) body.get("labelIds");
|
|
||||||
|
|
||||||
if (labelIdsInt == null || labelIdsInt.isEmpty()) {
|
if (!(labelIdsObj instanceof List)) {
|
||||||
Map<String, Object> error = new HashMap<>();
|
Map<String, Object> error = new HashMap<>();
|
||||||
error.put("success", false);
|
error.put("success", false);
|
||||||
error.put("message", "labelIds不能为空");
|
error.put("message", "labelIds不能为空");
|
||||||
return ServerResponse.badRequest().bodyValue(error);
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Long> labelIds = labelIdsInt.stream()
|
List<?> rawList = (List<?>) labelIdsObj;
|
||||||
.map(Integer::longValue)
|
if (rawList.isEmpty()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "labelIds不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Long> labelIds = rawList.stream()
|
||||||
|
.map(id -> Long.valueOf(String.valueOf(id)))
|
||||||
.collect(java.util.stream.Collectors.toList());
|
.collect(java.util.stream.Collectors.toList());
|
||||||
|
|
||||||
return courseLabelService.addLabelsToType(typeId, labelIds)
|
return courseLabelService.addLabelsToType(typeId, labelIds)
|
||||||
|
|||||||
+115
-32
@@ -7,10 +7,13 @@ import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
|||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseDetail;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseDetail;
|
||||||
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Validator;
|
import jakarta.validation.Validator;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
@@ -26,15 +29,21 @@ public class GroupCourseHandler {
|
|||||||
private final Validator validator;
|
private final Validator validator;
|
||||||
private final RedisUtil redisUtil;
|
private final RedisUtil redisUtil;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public GroupCourseHandler(IGroupCourseService groupCourseService,
|
public GroupCourseHandler(IGroupCourseService groupCourseService,
|
||||||
Validator validator,
|
Validator validator,
|
||||||
RedisUtil redisUtil,
|
RedisUtil redisUtil,
|
||||||
ObjectMapper objectMapper){
|
ObjectMapper objectMapper,
|
||||||
|
ISysUserService sysUserService,
|
||||||
|
AuthUtil authUtil){
|
||||||
this.groupCourseService = groupCourseService;
|
this.groupCourseService = groupCourseService;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
this.redisUtil = redisUtil;
|
this.redisUtil = redisUtil;
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表")
|
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表")
|
||||||
@@ -114,25 +123,43 @@ public class GroupCourseHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新团课", description = "更新指定团课信息")
|
@Operation(summary = "更新团课", description = "更新指定团课信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateGroupCourse(ServerRequest request) {
|
public Mono<ServerResponse> updateGroupCourse(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
return request.bodyToMono(GroupCourse.class)
|
|
||||||
.flatMap(groupCourse -> {
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
return groupCourseService.update(id, groupCourse)
|
Map<String, Object> error = new HashMap<>();
|
||||||
.flatMap(course -> {
|
error.put("success", false);
|
||||||
Map<String, Object> response = new HashMap<>();
|
error.put("message", "管理员密码不能为空");
|
||||||
response.put("success", true);
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
response.put("message", "团课更新成功");
|
}
|
||||||
response.put("data", course);
|
|
||||||
return ServerResponse.ok().bodyValue(response);
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
})
|
.flatMap(valid -> {
|
||||||
.onErrorResume(error -> {
|
if (!valid) {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> error = new HashMap<>();
|
||||||
response.put("success", false);
|
error.put("success", false);
|
||||||
response.put("message", error.getMessage());
|
error.put("message", "管理员密码错误");
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return request.bodyToMono(GroupCourse.class)
|
||||||
|
.flatMap(groupCourse -> {
|
||||||
|
return groupCourseService.update(id, groupCourse)
|
||||||
|
.flatMap(course -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "团课更新成功");
|
||||||
|
response.put("data", course);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -197,22 +224,78 @@ public class GroupCourseHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除团课", description = "删除指定团课(软删除)")
|
@Operation(summary = "删除团课", description = "删除指定团课(软删除),需验证管理员密码")
|
||||||
public Mono<ServerResponse> deleteGroupCourse(ServerRequest request) {
|
public Mono<ServerResponse> deleteGroupCourse(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
return groupCourseService.delete(id)
|
|
||||||
.then(Mono.defer(() -> {
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> error = new HashMap<>();
|
||||||
response.put("success", true);
|
error.put("success", false);
|
||||||
response.put("message", "团课删除成功");
|
error.put("message", "管理员密码不能为空");
|
||||||
return ServerResponse.ok().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
}))
|
}
|
||||||
.onErrorResume(error -> {
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
response.put("success", false);
|
.flatMap(valid -> {
|
||||||
response.put("message", error.getMessage());
|
if (!valid) {
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return groupCourseService.delete(id)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "团课删除成功");
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
}))
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "恢复已删除团课", description = "将已删除的团课恢复为已取消状态,需验证管理员密码")
|
||||||
|
public Mono<ServerResponse> restoreGroupCourse(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return groupCourseService.restore(id)
|
||||||
|
.flatMap(course -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "团课恢复成功");
|
||||||
|
response.put("data", course);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+103
-42
@@ -2,8 +2,11 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseRecommend;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseRecommend;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
@@ -17,9 +20,15 @@ import java.util.Map;
|
|||||||
public class GroupCourseRecommendHandler {
|
public class GroupCourseRecommendHandler {
|
||||||
|
|
||||||
private final IGroupCourseRecommendService recommendService;
|
private final IGroupCourseRecommendService recommendService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public GroupCourseRecommendHandler(IGroupCourseRecommendService recommendService) {
|
public GroupCourseRecommendHandler(IGroupCourseRecommendService recommendService,
|
||||||
|
ISysUserService sysUserService,
|
||||||
|
AuthUtil authUtil) {
|
||||||
this.recommendService = recommendService;
|
this.recommendService = recommendService;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有团课推荐", description = "获取系统中所有团课推荐列表,支持按优先级排序")
|
@Operation(summary = "获取所有团课推荐", description = "获取系统中所有团课推荐列表,支持按优先级排序")
|
||||||
@@ -80,20 +89,73 @@ public class GroupCourseRecommendHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新团课推荐", description = "更新指定团课推荐信息")
|
@Operation(summary = "更新团课推荐", description = "更新指定团课推荐信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateRecommendation(ServerRequest request) {
|
public Mono<ServerResponse> updateRecommendation(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
return request.bodyToMono(GroupCourseRecommend.class)
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
.flatMap(recommend -> {
|
Map<String, Object> error = new HashMap<>();
|
||||||
return recommendService.update(id, recommend)
|
error.put("success", false);
|
||||||
.flatMap(r -> {
|
error.put("message", "管理员密码不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return request.bodyToMono(GroupCourseRecommend.class)
|
||||||
|
.flatMap(recommend -> recommendService.update(id, recommend)
|
||||||
|
.flatMap(r -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "团课推荐更新成功");
|
||||||
|
response.put("data", r);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除团课推荐", description = "删除指定团课推荐(软删除),需验证管理员密码")
|
||||||
|
public Mono<ServerResponse> deleteRecommendation(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return recommendService.delete(id)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
response.put("success", true);
|
response.put("success", true);
|
||||||
response.put("message", "团课推荐更新成功");
|
response.put("message", "团课推荐删除成功");
|
||||||
response.put("data", r);
|
|
||||||
return ServerResponse.ok().bodyValue(response);
|
return ServerResponse.ok().bodyValue(response);
|
||||||
})
|
}))
|
||||||
.onErrorResume(error -> {
|
.onErrorResume(error -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
response.put("success", false);
|
response.put("success", false);
|
||||||
@@ -103,25 +165,6 @@ public class GroupCourseRecommendHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除团课推荐", description = "删除指定团课推荐(软删除)")
|
|
||||||
public Mono<ServerResponse> deleteRecommendation(ServerRequest request) {
|
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
|
||||||
|
|
||||||
return recommendService.delete(id)
|
|
||||||
.then(Mono.defer(() -> {
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
|
||||||
response.put("success", true);
|
|
||||||
response.put("message", "团课推荐删除成功");
|
|
||||||
return ServerResponse.ok().bodyValue(response);
|
|
||||||
}))
|
|
||||||
.onErrorResume(error -> {
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
|
||||||
response.put("success", false);
|
|
||||||
response.put("message", error.getMessage());
|
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "启用团课推荐", description = "启用指定团课推荐")
|
@Operation(summary = "启用团课推荐", description = "启用指定团课推荐")
|
||||||
public Mono<ServerResponse> enableRecommendation(ServerRequest request) {
|
public Mono<ServerResponse> enableRecommendation(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
@@ -142,23 +185,41 @@ public class GroupCourseRecommendHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "禁用团课推荐", description = "禁用指定团课推荐")
|
@Operation(summary = "禁用团课推荐", description = "禁用指定团课推荐,需验证管理员密码")
|
||||||
public Mono<ServerResponse> disableRecommendation(ServerRequest request) {
|
public Mono<ServerResponse> disableRecommendation(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
return recommendService.disable(id)
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
.flatMap(r -> {
|
Map<String, Object> error = new HashMap<>();
|
||||||
Map<String, Object> response = new HashMap<>();
|
error.put("success", false);
|
||||||
response.put("success", true);
|
error.put("message", "管理员密码不能为空");
|
||||||
response.put("message", "团课推荐禁用成功");
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
response.put("data", r);
|
}
|
||||||
return ServerResponse.ok().bodyValue(response);
|
|
||||||
})
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
.onErrorResume(error -> {
|
.flatMap(valid -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
if (!valid) {
|
||||||
response.put("success", false);
|
Map<String, Object> error = new HashMap<>();
|
||||||
response.put("message", error.getMessage());
|
error.put("success", false);
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return recommendService.disable(id)
|
||||||
|
.flatMap(r -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "团课推荐禁用成功");
|
||||||
|
response.put("data", r);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+76
-31
@@ -2,8 +2,11 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
@@ -17,9 +20,15 @@ import java.util.Map;
|
|||||||
public class GroupCourseTypeHandler {
|
public class GroupCourseTypeHandler {
|
||||||
|
|
||||||
private final IGroupCourseTypeService groupCourseTypeService;
|
private final IGroupCourseTypeService groupCourseTypeService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public GroupCourseTypeHandler(IGroupCourseTypeService groupCourseTypeService) {
|
public GroupCourseTypeHandler(IGroupCourseTypeService groupCourseTypeService,
|
||||||
|
ISysUserService sysUserService,
|
||||||
|
AuthUtil authUtil) {
|
||||||
this.groupCourseTypeService = groupCourseTypeService;
|
this.groupCourseTypeService = groupCourseTypeService;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有团课类型", description = "获取系统中所有团课类型列表")
|
@Operation(summary = "获取所有团课类型", description = "获取系统中所有团课类型列表")
|
||||||
@@ -92,21 +101,76 @@ public class GroupCourseTypeHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新团课类型", description = "更新指定团课类型信息")
|
@Operation(summary = "更新团课类型", description = "更新指定团课类型信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateGroupCourseType(ServerRequest request) {
|
public Mono<ServerResponse> updateGroupCourseType(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
return request.bodyToMono(GroupCourseType.class)
|
|
||||||
.flatMap(groupCourseType -> {
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
groupCourseType.setId(id);
|
Map<String, Object> error = new HashMap<>();
|
||||||
return groupCourseTypeService.update(id, groupCourseType)
|
error.put("success", false);
|
||||||
.flatMap(type -> {
|
error.put("message", "管理员密码不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return request.bodyToMono(GroupCourseType.class)
|
||||||
|
.flatMap(groupCourseType -> {
|
||||||
|
groupCourseType.setId(id);
|
||||||
|
return groupCourseTypeService.update(id, groupCourseType)
|
||||||
|
.flatMap(type -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "团课类型更新成功");
|
||||||
|
response.put("data", type);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除团课类型", description = "删除指定团课类型(软删除),需验证管理员密码,且该类型不能被任何团课引用")
|
||||||
|
public Mono<ServerResponse> deleteGroupCourseType(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "管理员密码错误");
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue(error);
|
||||||
|
}
|
||||||
|
return groupCourseTypeService.delete(id)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
response.put("success", true);
|
response.put("success", true);
|
||||||
response.put("message", "团课类型更新成功");
|
response.put("message", "团课类型删除成功");
|
||||||
response.put("data", type);
|
|
||||||
return ServerResponse.ok().bodyValue(response);
|
return ServerResponse.ok().bodyValue(response);
|
||||||
})
|
}))
|
||||||
.onErrorResume(error -> {
|
.onErrorResume(error -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
response.put("success", false);
|
response.put("success", false);
|
||||||
@@ -115,23 +179,4 @@ public class GroupCourseTypeHandler {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
@Operation(summary = "删除团课类型", description = "删除指定团课类型(软删除)")
|
|
||||||
public Mono<ServerResponse> deleteGroupCourseType(ServerRequest request) {
|
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
|
||||||
|
|
||||||
return groupCourseTypeService.delete(id)
|
|
||||||
.then(Mono.defer(() -> {
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
|
||||||
response.put("success", true);
|
|
||||||
response.put("message", "团课类型删除成功");
|
|
||||||
return ServerResponse.ok().bodyValue(response);
|
|
||||||
}))
|
|
||||||
.onErrorResume(error -> {
|
|
||||||
Map<String, Object> response = new HashMap<>();
|
|
||||||
response.put("success", false);
|
|
||||||
response.put("message", error.getMessage());
|
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+2
@@ -27,6 +27,8 @@ public interface IGroupCourseRepository {
|
|||||||
|
|
||||||
Mono<Void> deleteById(Long id);
|
Mono<Void> deleteById(Long id);
|
||||||
|
|
||||||
|
Mono<GroupCourse> restoreById(Long id);
|
||||||
|
|
||||||
Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta);
|
Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta);
|
||||||
|
|
||||||
Flux<GroupCourse> findByCourseType(Long courseType);
|
Flux<GroupCourse> findByCourseType(Long courseType);
|
||||||
|
|||||||
+11
@@ -169,6 +169,17 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
|||||||
.then();
|
.then();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<GroupCourse> restoreById(Long id) {
|
||||||
|
return groupCourseDao.restoreCourse(id, LocalDateTime.now())
|
||||||
|
.flatMap(updated -> {
|
||||||
|
if (updated > 0) {
|
||||||
|
return findByIdAndDeletedAtIsNull(id);
|
||||||
|
}
|
||||||
|
return Mono.error(new RuntimeException("团课恢复失败,可能该课程未被删除"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta) {
|
public Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta) {
|
||||||
return groupCourseDao.updateCurrentMembers(id, delta, LocalDateTime.now())
|
return groupCourseDao.updateCurrentMembers(id, delta, LocalDateTime.now())
|
||||||
|
|||||||
+14
-15
@@ -105,21 +105,20 @@ public class GroupCourseTypeRepository implements IGroupCourseTypeRepository {
|
|||||||
return groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId())
|
return groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId())
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("团课类型不存在")))
|
.switchIfEmpty(Mono.error(new RuntimeException("团课类型不存在")))
|
||||||
.flatMap(existing -> {
|
.flatMap(existing -> {
|
||||||
existing.markNotNew();
|
String typeName = groupCourseType.getTypeName() != null
|
||||||
if (groupCourseType.getTypeName() != null) {
|
? groupCourseType.getTypeName() : existing.getTypeName();
|
||||||
existing.setTypeName(groupCourseType.getTypeName());
|
Integer baseDifficulty = groupCourseType.getBaseDifficulty() != null
|
||||||
}
|
? groupCourseType.getBaseDifficulty() : existing.getBaseDifficulty();
|
||||||
if (groupCourseType.getBaseDifficulty() != null) {
|
String description = groupCourseType.getDescription() != null
|
||||||
existing.setBaseDifficulty(groupCourseType.getBaseDifficulty());
|
? groupCourseType.getDescription() : existing.getDescription();
|
||||||
}
|
String category = groupCourseType.getCategory() != null
|
||||||
if (groupCourseType.getDescription() != null) {
|
? groupCourseType.getCategory() : existing.getCategory();
|
||||||
existing.setDescription(groupCourseType.getDescription());
|
LocalDateTime now = LocalDateTime.now();
|
||||||
}
|
|
||||||
if (groupCourseType.getCategory() != null) {
|
return groupCourseTypeDao.updateFields(
|
||||||
existing.setCategory(groupCourseType.getCategory());
|
groupCourseType.getId(), typeName, baseDifficulty,
|
||||||
}
|
description, category, now)
|
||||||
existing.setUpdatedAt(LocalDateTime.now());
|
.then(groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId()));
|
||||||
return groupCourseTypeDao.save(existing);
|
|
||||||
})
|
})
|
||||||
.map(converter::toGroupCourseType);
|
.map(converter::toGroupCourseType);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
@@ -26,6 +26,8 @@ public interface IGroupCourseService {
|
|||||||
Mono<GroupCourse> signIn(Long courseId, Long memberId);
|
Mono<GroupCourse> signIn(Long courseId, Long memberId);
|
||||||
|
|
||||||
Mono<Void> delete(Long id);
|
Mono<Void> delete(Long id);
|
||||||
|
|
||||||
|
Mono<GroupCourse> restore(Long id);
|
||||||
|
|
||||||
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-5
@@ -536,14 +536,14 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Void> delete(Long id) {
|
public Mono<Void> delete(Long id) {
|
||||||
// 先查询课程状态,只有已取消的课程才能删除
|
// 已取消或已结束的课程才能删除
|
||||||
return groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
return groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||||
.flatMap(course -> {
|
.flatMap(course -> {
|
||||||
// 检查课程状态是否为已取消(状态码1)
|
Long status = course.getStatus();
|
||||||
if (course.getStatus() == null || !course.getStatus().equals(CourseStatus.CANCELLED.getValue())) {
|
if (status == null || (!status.equals(CourseStatus.CANCELLED.getValue()) && !status.equals(CourseStatus.ENDED.getValue()))) {
|
||||||
return Mono.error(new RuntimeException("只有已取消的课程才能删除,当前状态: " +
|
return Mono.error(new RuntimeException("只有已取消或已结束的课程才能删除,当前状态: " +
|
||||||
(course.getStatus() != null ? course.getStatus() : "未知")));
|
(status != null ? status : "未知")));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除课程
|
// 删除课程
|
||||||
@@ -554,6 +554,14 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<GroupCourse> restore(Long id) {
|
||||||
|
return groupCourseRepository.restoreById(id)
|
||||||
|
.doOnSuccess(course -> logger.info("团课恢复成功 - id={}", id))
|
||||||
|
.flatMap(course -> clearCache().thenReturn(course))
|
||||||
|
.doOnError(error -> logger.error("团课恢复失败 - id={}, error: {}", id, error.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query) {
|
public Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query) {
|
||||||
logger.info("多条件查询团课 - courseName={}, courseType={}, startDate={}, endDate={}, timePeriod={}, priceSort={}, remainingMost={}",
|
logger.info("多条件查询团课 - courseName={}, courseType={}, startDate={}, endDate={}, timePeriod={}, priceSort={}, remainingMost={}",
|
||||||
|
|||||||
+13
-5
@@ -1,6 +1,7 @@
|
|||||||
package cn.novalon.gym.manage.groupcourse.service.impl;
|
package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -9,18 +10,18 @@ import org.springframework.stereotype.Service;
|
|||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class GroupCourseTypeService implements IGroupCourseTypeService {
|
public class GroupCourseTypeService implements IGroupCourseTypeService {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(GroupCourseTypeService.class);
|
private static final Logger logger = LoggerFactory.getLogger(GroupCourseTypeService.class);
|
||||||
|
|
||||||
private final IGroupCourseTypeRepository groupCourseTypeRepository;
|
private final IGroupCourseTypeRepository groupCourseTypeRepository;
|
||||||
|
private final IGroupCourseRepository groupCourseRepository;
|
||||||
|
|
||||||
public GroupCourseTypeService(IGroupCourseTypeRepository groupCourseTypeRepository) {
|
public GroupCourseTypeService(IGroupCourseTypeRepository groupCourseTypeRepository,
|
||||||
|
IGroupCourseRepository groupCourseRepository) {
|
||||||
this.groupCourseTypeRepository = groupCourseTypeRepository;
|
this.groupCourseTypeRepository = groupCourseTypeRepository;
|
||||||
|
this.groupCourseRepository = groupCourseRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -71,7 +72,14 @@ public class GroupCourseTypeService implements IGroupCourseTypeService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Void> delete(Long id) {
|
public Mono<Void> delete(Long id) {
|
||||||
return groupCourseTypeRepository.deleteById(id)
|
return groupCourseRepository.findByCourseType(id)
|
||||||
|
.hasElements()
|
||||||
|
.flatMap(hasCourses -> {
|
||||||
|
if (hasCourses) {
|
||||||
|
return Mono.<Void>error(new RuntimeException("该类型下存在关联团课,无法删除"));
|
||||||
|
}
|
||||||
|
return groupCourseTypeRepository.deleteById(id);
|
||||||
|
})
|
||||||
.doOnSuccess(v -> logger.info("团课类型删除成功 - id={}", id))
|
.doOnSuccess(v -> logger.info("团课类型删除成功 - id={}", id))
|
||||||
.doOnError(error -> logger.error("团课类型删除失败 - id={}, error: {}", id, error.getMessage()));
|
.doOnError(error -> logger.error("团课类型删除失败 - id={}, error: {}", id, error.getMessage()));
|
||||||
}
|
}
|
||||||
|
|||||||
+94
-29
@@ -1,14 +1,19 @@
|
|||||||
package cn.novalon.gym.manage.groupcourse.util;
|
package cn.novalon.gym.manage.groupcourse.util;
|
||||||
|
|
||||||
|
import com.aliyun.oss.HttpMethod;
|
||||||
import com.aliyun.oss.OSS;
|
import com.aliyun.oss.OSS;
|
||||||
import com.aliyun.oss.OSSClientBuilder;
|
import com.aliyun.oss.OSSClientBuilder;
|
||||||
|
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
|
||||||
import com.aliyun.oss.model.PutObjectRequest;
|
import com.aliyun.oss.model.PutObjectRequest;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.URL;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 阿里云OSS工具类
|
* 阿里云OSS工具类
|
||||||
@@ -19,8 +24,8 @@ public class OSSUtil {
|
|||||||
|
|
||||||
// OSS配置信息
|
// OSS配置信息
|
||||||
private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
|
private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
|
||||||
private static final String ACCESS_KEY_ID = "LTAI5t9TFh9Vayeahz45kZjg";
|
private static final String ACCESS_KEY_ID = "LTAI5t9wHCiH68Xjxg64Xx4Y";
|
||||||
private static final String ACCESS_KEY_SECRET = "zD6NlCeH5UhjBs4vnQVqn8Ksi3CaZz";
|
private static final String ACCESS_KEY_SECRET = "isAfz1IFGAnV13LOIrVg19aPhY8aRq";
|
||||||
private static final String BUCKET_NAME = "ycc-filesaver";
|
private static final String BUCKET_NAME = "ycc-filesaver";
|
||||||
|
|
||||||
// OSS访问地址前缀
|
// OSS访问地址前缀
|
||||||
@@ -28,36 +33,31 @@ public class OSSUtil {
|
|||||||
|
|
||||||
// 文件存储目录
|
// 文件存储目录
|
||||||
private static final String QRCODE_DIR = "qrcode/";
|
private static final String QRCODE_DIR = "qrcode/";
|
||||||
|
private static final String COVER_DIR = "cover/";
|
||||||
|
|
||||||
|
// 预签名URL有效期(秒)
|
||||||
|
private static final long PRESIGN_EXPIRE_SECONDS = 300;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 上传文件到阿里云OSS
|
* 上传文件到阿里云OSS(文件默认继承Bucket权限,不设置ACL)
|
||||||
*
|
*
|
||||||
* @param localFilePath 本地文件路径
|
* @param localFilePath 本地文件路径
|
||||||
* @param fileName 文件名(不含路径)
|
* @param fileName 文件名(不含路径)
|
||||||
* @return OSS访问地址
|
* @return OSS object key(不含域名前缀)
|
||||||
*/
|
*/
|
||||||
public static String uploadToOSS(String localFilePath, String fileName) {
|
public static String uploadToOSS(String localFilePath, String fileName) {
|
||||||
OSS ossClient = null;
|
OSS ossClient = null;
|
||||||
try {
|
try {
|
||||||
// 创建OSS客户端
|
|
||||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||||
|
|
||||||
// 构建OSS文件路径:qrcode/2026/06/18/xxx.png
|
|
||||||
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
||||||
String ossFilePath = QRCODE_DIR + datePath + "/" + fileName;
|
String ossFilePath = QRCODE_DIR + datePath + "/" + fileName;
|
||||||
|
|
||||||
// 创建上传请求
|
|
||||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||||
|
|
||||||
// 上传文件
|
|
||||||
ossClient.putObject(putObjectRequest);
|
ossClient.putObject(putObjectRequest);
|
||||||
|
|
||||||
// 构建访问地址
|
logger.info("文件上传到OSS成功: localPath={}, ossKey={}", localFilePath, ossFilePath);
|
||||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
return ossFilePath;
|
||||||
|
|
||||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
|
||||||
|
|
||||||
return accessUrl;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||||
@@ -69,34 +69,25 @@ public class OSSUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 上传文件到阿里云OSS(自定义存储路径)
|
* 上传文件到阿里云OSS(自定义存储路径,文件默认继承Bucket权限)
|
||||||
*
|
*
|
||||||
* @param localFilePath 本地文件路径
|
* @param localFilePath 本地文件路径
|
||||||
* @param ossDirectory OSS存储目录
|
* @param ossDirectory OSS存储目录
|
||||||
* @param fileName 文件名(不含路径)
|
* @param fileName 文件名(不含路径)
|
||||||
* @return OSS访问地址
|
* @return OSS object key(不含域名前缀)
|
||||||
*/
|
*/
|
||||||
public static String uploadToOSS(String localFilePath, String ossDirectory, String fileName) {
|
public static String uploadToOSS(String localFilePath, String ossDirectory, String fileName) {
|
||||||
OSS ossClient = null;
|
OSS ossClient = null;
|
||||||
try {
|
try {
|
||||||
// 创建OSS客户端
|
|
||||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||||
|
|
||||||
// 构建OSS文件路径
|
|
||||||
String ossFilePath = ossDirectory + fileName;
|
String ossFilePath = ossDirectory + fileName;
|
||||||
|
|
||||||
// 创建上传请求
|
|
||||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||||
|
|
||||||
// 上传文件
|
|
||||||
ossClient.putObject(putObjectRequest);
|
ossClient.putObject(putObjectRequest);
|
||||||
|
|
||||||
// 构建访问地址
|
logger.info("文件上传到OSS成功: localPath={}, ossKey={}", localFilePath, ossFilePath);
|
||||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
return ossFilePath;
|
||||||
|
|
||||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
|
||||||
|
|
||||||
return accessUrl;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||||
@@ -106,4 +97,78 @@ public class OSSUtil {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/**
|
||||||
|
* 上传封面图到阿里云OSS(使用InputStream,文件默认继承Bucket权限)
|
||||||
|
*
|
||||||
|
* @param inputStream 文件输入流
|
||||||
|
* @param fileName 文件名(不含路径)
|
||||||
|
* @return OSS object key(不含域名前缀)
|
||||||
|
*/
|
||||||
|
public static String uploadCoverToOSS(InputStream inputStream, String fileName) {
|
||||||
|
OSS ossClient = null;
|
||||||
|
try {
|
||||||
|
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||||
|
|
||||||
|
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
||||||
|
String ossFilePath = COVER_DIR + datePath + "/" + fileName;
|
||||||
|
|
||||||
|
ossClient.putObject(BUCKET_NAME, ossFilePath, inputStream);
|
||||||
|
|
||||||
|
logger.info("封面上传到OSS成功: fileName={}, ossKey={}", fileName, ossFilePath);
|
||||||
|
return ossFilePath;
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("封面上传到OSS失败 - fileName: {}, error: {}", fileName, e.getMessage(), e);
|
||||||
|
throw new RuntimeException("封面上传到OSS失败: " + e.getMessage(), e);
|
||||||
|
} finally {
|
||||||
|
if (ossClient != null) {
|
||||||
|
ossClient.shutdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成OSS对象预签名URL(临时访问链接)
|
||||||
|
*
|
||||||
|
* @param ossKey OSS对象Key(不含域名前缀)
|
||||||
|
* @return 预签名URL
|
||||||
|
*/
|
||||||
|
public static String generatePresignedUrl(String ossKey) {
|
||||||
|
return generatePresignedUrl(ossKey, PRESIGN_EXPIRE_SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成OSS对象预签名URL(可指定有效期)
|
||||||
|
*
|
||||||
|
* @param ossKey OSS对象Key(不含域名前缀)
|
||||||
|
* @param expireSeconds 有效期(秒)
|
||||||
|
* @return 预签名URL
|
||||||
|
*/
|
||||||
|
public static String generatePresignedUrl(String ossKey, long expireSeconds) {
|
||||||
|
OSS ossClient = null;
|
||||||
|
try {
|
||||||
|
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||||
|
|
||||||
|
Date expiration = new Date(System.currentTimeMillis() + expireSeconds * 1000);
|
||||||
|
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(BUCKET_NAME, ossKey, HttpMethod.GET);
|
||||||
|
request.setExpiration(expiration);
|
||||||
|
|
||||||
|
URL signedUrl = ossClient.generatePresignedUrl(request);
|
||||||
|
return signedUrl.toString();
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("生成预签名URL失败 - ossKey: {}, error: {}", ossKey, e.getMessage(), e);
|
||||||
|
throw new RuntimeException("生成预签名URL失败: " + e.getMessage(), e);
|
||||||
|
} finally {
|
||||||
|
if (ossClient != null) {
|
||||||
|
ossClient.shutdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据OSS Key拼接公开访问URL(仅当Bucket为公共读时有效)
|
||||||
|
*/
|
||||||
|
public static String getPublicUrl(String ossKey) {
|
||||||
|
return OSS_URL_PREFIX + ossKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package cn.novalon.gym.manage.member.dto;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.member.enums.GenderEnum;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员编辑会员信息DTO(含密码验证)
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-24
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class AdminEditMemberDto {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员密码(必填,用于验证身份)
|
||||||
|
*/
|
||||||
|
private String adminPassword;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 昵称
|
||||||
|
*/
|
||||||
|
private String nickname;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 性别
|
||||||
|
*/
|
||||||
|
private GenderEnum gender;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生日
|
||||||
|
*/
|
||||||
|
private LocalDate birthday;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 地址
|
||||||
|
*/
|
||||||
|
private String address;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 头像
|
||||||
|
*/
|
||||||
|
private String avatar;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换为 UpdateMemberInfoDto
|
||||||
|
*/
|
||||||
|
public UpdateMemberInfoDto toUpdateMemberInfoDto() {
|
||||||
|
UpdateMemberInfoDto dto = new UpdateMemberInfoDto();
|
||||||
|
dto.setNickname(nickname);
|
||||||
|
dto.setGender(gender);
|
||||||
|
dto.setBirthday(birthday);
|
||||||
|
dto.setAddress(address);
|
||||||
|
dto.setAvatar(avatar);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
+69
-15
@@ -2,16 +2,21 @@ package cn.novalon.gym.manage.member.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
import cn.novalon.gym.manage.member.service.IMemberCardService;
|
import cn.novalon.gym.manage.member.service.IMemberCardService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 会员卡管理处理器
|
* 会员卡管理处理器
|
||||||
*
|
*
|
||||||
@@ -24,9 +29,13 @@ import reactor.core.publisher.Mono;
|
|||||||
public class MemberCardHandler {
|
public class MemberCardHandler {
|
||||||
|
|
||||||
private final IMemberCardService memberCardService;
|
private final IMemberCardService memberCardService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public MemberCardHandler(IMemberCardService memberCardService) {
|
public MemberCardHandler(IMemberCardService memberCardService, ISysUserService sysUserService, AuthUtil authUtil) {
|
||||||
this.memberCardService = memberCardService;
|
this.memberCardService = memberCardService;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "根据ID查询会员卡类型", description = "查询指定ID的会员卡类型详情")
|
@Operation(summary = "根据ID查询会员卡类型", description = "查询指定ID的会员卡类型详情")
|
||||||
@@ -60,27 +69,72 @@ public class MemberCardHandler {
|
|||||||
.flatMap(card -> ServerResponse.status(HttpStatus.CREATED).bodyValue(card));
|
.flatMap(card -> ServerResponse.status(HttpStatus.CREATED).bodyValue(card));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新会员卡类型", description = "更新会员卡类型信息")
|
@Operation(summary = "更新会员卡类型", description = "更新会员卡类型信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateMemberCard(ServerRequest request) {
|
public Mono<ServerResponse> updateMemberCard(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return request.bodyToMono(MemberCard.class)
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
.flatMap(card -> {
|
|
||||||
card.setMemberCardId(id);
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
return memberCardService.save(card);
|
return ServerResponse.badRequest()
|
||||||
})
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.flatMap(updated -> ServerResponse.ok().bodyValue(updated))
|
.bodyValue(Map.of("code", 400, "message", "管理员密码不能为空"))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.flatMap(resp -> Mono.just(resp));
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 403, "message", "管理员密码错误"))
|
||||||
|
.flatMap(resp -> Mono.just(resp));
|
||||||
|
}
|
||||||
|
return request.bodyToMono(MemberCard.class)
|
||||||
|
.flatMap(body -> memberCardService.findByMemberCardIdAndDeletedAtIsNull(id)
|
||||||
|
.flatMap(existing -> {
|
||||||
|
existing.setMemberCardName(body.getMemberCardName());
|
||||||
|
existing.setMemberCardType(body.getMemberCardType());
|
||||||
|
existing.setMemberCardPrice(body.getMemberCardPrice());
|
||||||
|
existing.setMemberCardValidityDays(body.getMemberCardValidityDays());
|
||||||
|
existing.setMemberCardTotalTimes(body.getMemberCardTotalTimes());
|
||||||
|
existing.setMemberCardAmount(body.getMemberCardAmount());
|
||||||
|
existing.setMemberCardStatus(body.getMemberCardStatus());
|
||||||
|
return memberCardService.save(existing);
|
||||||
|
})
|
||||||
|
.flatMap(updated -> ServerResponse.ok().bodyValue(updated))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build()));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除会员卡类型", description = "逻辑删除会员卡类型")
|
@Operation(summary = "删除会员卡类型", description = "逻辑删除会员卡类型,需验证管理员密码")
|
||||||
public Mono<ServerResponse> deleteMemberCard(ServerRequest request) {
|
public Mono<ServerResponse> deleteMemberCard(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return memberCardService.logicalDelete(id)
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
.flatMap(rows -> {
|
|
||||||
if (rows > 0) {
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
return ServerResponse.noContent().build();
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "管理员密码不能为空"))
|
||||||
|
.flatMap(resp -> Mono.just(resp));
|
||||||
|
}
|
||||||
|
|
||||||
|
return sysUserService.verifyPassword(adminId, adminPassword)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 403, "message", "管理员密码错误"))
|
||||||
|
.flatMap(resp -> Mono.just(resp));
|
||||||
}
|
}
|
||||||
return ServerResponse.notFound().build();
|
return memberCardService.logicalDelete(id)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
return ServerResponse.noContent().build();
|
||||||
|
}
|
||||||
|
return ServerResponse.notFound().build();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+28
-9
@@ -1,7 +1,7 @@
|
|||||||
package cn.novalon.gym.manage.member.handler;
|
package cn.novalon.gym.manage.member.handler;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.common.exception.NotFoundException;
|
import cn.novalon.gym.manage.common.exception.NotFoundException;
|
||||||
import cn.novalon.gym.manage.member.config.WechatProperties;
|
import cn.novalon.gym.manage.member.dto.AdminEditMemberDto;
|
||||||
import cn.novalon.gym.manage.member.dto.AdminUpdatePhoneDto;
|
import cn.novalon.gym.manage.member.dto.AdminUpdatePhoneDto;
|
||||||
import cn.novalon.gym.manage.member.dto.SearchMemberDto;
|
import cn.novalon.gym.manage.member.dto.SearchMemberDto;
|
||||||
import cn.novalon.gym.manage.member.dto.UpdateMemberInfoDto;
|
import cn.novalon.gym.manage.member.dto.UpdateMemberInfoDto;
|
||||||
@@ -10,8 +10,8 @@ import cn.novalon.gym.manage.member.service.WechatAuthService;
|
|||||||
import cn.novalon.gym.manage.member.service.WechatOfficialService;
|
import cn.novalon.gym.manage.member.service.WechatOfficialService;
|
||||||
import cn.novalon.gym.manage.member.util.AesUtil;
|
import cn.novalon.gym.manage.member.util.AesUtil;
|
||||||
import cn.novalon.gym.manage.member.util.WechatPhoneUtil;
|
import cn.novalon.gym.manage.member.util.WechatPhoneUtil;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -24,6 +24,8 @@ import org.springframework.web.reactive.function.server.ServerRequest;
|
|||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 会员信息处理器
|
* 会员信息处理器
|
||||||
*
|
*
|
||||||
@@ -41,6 +43,7 @@ public class MemberHandler {
|
|||||||
private final WechatAuthService wechatAuthService;
|
private final WechatAuthService wechatAuthService;
|
||||||
private final WechatOfficialService wechatOfficialService;
|
private final WechatOfficialService wechatOfficialService;
|
||||||
private final AuthUtil authUtil;
|
private final AuthUtil authUtil;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
|
||||||
@Operation(summary = "获取会员信息", description = "根据当前登录用户获取会员基本信息")
|
@Operation(summary = "获取会员信息", description = "根据当前登录用户获取会员基本信息")
|
||||||
public Mono<ServerResponse> getMemberInfo(ServerRequest request) {
|
public Mono<ServerResponse> getMemberInfo(ServerRequest request) {
|
||||||
@@ -165,7 +168,7 @@ public class MemberHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "管理员编辑会员信息", description = "后台管理员编辑会员信息")
|
@Operation(summary = "管理员编辑会员信息", description = "后台管理员编辑会员信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> adminUpdateMemberInfo(ServerRequest request) {
|
public Mono<ServerResponse> adminUpdateMemberInfo(ServerRequest request) {
|
||||||
|
|
||||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
@@ -174,14 +177,30 @@ public class MemberHandler {
|
|||||||
long memberId = NumberUtils.toLong(memberIdStr, 0L);
|
long memberId = NumberUtils.toLong(memberIdStr, 0L);
|
||||||
if(memberId <= 0L) throw new IllegalArgumentException("会员ID格式错误");
|
if(memberId <= 0L) throw new IllegalArgumentException("会员ID格式错误");
|
||||||
|
|
||||||
// TODO: 补充签到记录
|
|
||||||
log.info("前台编辑会员信息, adminId: {}, memberId: {}", adminId, memberId);
|
log.info("前台编辑会员信息, adminId: {}, memberId: {}", adminId, memberId);
|
||||||
|
|
||||||
return request.bodyToMono(UpdateMemberInfoDto.class)
|
return request.bodyToMono(AdminEditMemberDto.class)
|
||||||
.flatMap(updateDto -> memberService.adminUpdateMemberInfo(memberId, updateDto))
|
.flatMap(dto -> {
|
||||||
.flatMap(detail -> ServerResponse.ok()
|
if (dto.getAdminPassword() == null || dto.getAdminPassword().isBlank()) {
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
return ServerResponse.badRequest()
|
||||||
.bodyValue(detail));
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "管理员密码不能为空"))
|
||||||
|
.flatMap(resp -> Mono.<ServerResponse>just(resp));
|
||||||
|
}
|
||||||
|
return sysUserService.verifyPassword(adminId, dto.getAdminPassword())
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 403, "message", "管理员密码错误"))
|
||||||
|
.flatMap(resp -> Mono.<ServerResponse>just(resp));
|
||||||
|
}
|
||||||
|
return memberService.adminUpdateMemberInfo(memberId, dto.toUpdateMemberInfoDto())
|
||||||
|
.flatMap(result -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(result));
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "搜索会员列表", description = "后台管理员按关键词搜索会员,支持性别筛选和分页")
|
@Operation(summary = "搜索会员列表", description = "后台管理员按关键词搜索会员,支持性别筛选和分页")
|
||||||
|
|||||||
+48
-35
@@ -242,45 +242,58 @@ public class MemberServiceImpl implements MemberService {
|
|||||||
log.debug("从缓存获取会员详情, memberId: {}", memberId);
|
log.debug("从缓存获取会员详情, memberId: {}", memberId);
|
||||||
return Mono.just(cached);
|
return Mono.just(cached);
|
||||||
}
|
}
|
||||||
return memberRepository.findById(memberId)
|
// 缓存反序列化异常,查数据库
|
||||||
.zipWith(
|
return queryMemberDetailFromDb(memberId, cacheKey);
|
||||||
memberRepository.findCardRecordsWithCardInfoByMemberId(memberId)
|
})
|
||||||
.collectList(),
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
(baseInfo, cardList) -> {
|
// 缓存不存在,查数据库
|
||||||
MemberDetailVO memberDetailVO = BeanConvertUtil.toBean(baseInfo, MemberDetailVO.class);
|
return queryMemberDetailFromDb(memberId, cacheKey);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
GenderEnum genderEnum = GenderEnum.fromCode(baseInfo.getGender());
|
private Mono<MemberDetailVO> queryMemberDetailFromDb(Long memberId, String cacheKey) {
|
||||||
memberDetailVO.setGenderDesc(genderEnum.getDesc());
|
return memberRepository.findById(memberId)
|
||||||
|
.zipWith(
|
||||||
|
memberRepository.findCardRecordsWithCardInfoByMemberId(memberId)
|
||||||
|
.collectList(),
|
||||||
|
(baseInfo, cardList) -> {
|
||||||
|
MemberDetailVO memberDetailVO = BeanConvertUtil.toBean(baseInfo, MemberDetailVO.class);
|
||||||
|
|
||||||
List<MemberCardInfoVO> enrichedCards = cardList.stream()
|
GenderEnum genderEnum = GenderEnum.fromCode(baseInfo.getGender());
|
||||||
.peek(vo -> {
|
memberDetailVO.setGenderDesc(genderEnum.getDesc());
|
||||||
if (vo.getMemberCardType() != null) {
|
|
||||||
try {
|
|
||||||
MemberCardType cardType = MemberCardType.valueOf(vo.getMemberCardType());
|
|
||||||
vo.setMemberCardTypeDesc(cardType.getDesc());
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
vo.setMemberCardTypeDesc(vo.getMemberCardType());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (vo.getMemberCardStatus() != null) {
|
|
||||||
vo.setMemberCardStatusDesc(vo.getMemberCardStatus() == 1 ? "上架" : "下架");
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
memberDetailVO.setMemberCards(enrichedCards);
|
|
||||||
|
|
||||||
long activeCount = enrichedCards.stream()
|
List<MemberCardInfoVO> enrichedCards = cardList.stream()
|
||||||
.filter(card -> card.getMemberCardStatus() != null && card.getMemberCardStatus() == 1)
|
.peek(vo -> {
|
||||||
.count();
|
if (vo.getMemberCardType() != null) {
|
||||||
memberDetailVO.setActiveCardCount((int) activeCount);
|
try {
|
||||||
memberDetailVO.setInactiveCardCount(enrichedCards.size() - (int) activeCount);
|
MemberCardType cardType = MemberCardType.valueOf(vo.getMemberCardType());
|
||||||
|
vo.setMemberCardTypeDesc(cardType.getDesc());
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
vo.setMemberCardTypeDesc(vo.getMemberCardType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (vo.getMemberCardStatus() != null) {
|
||||||
|
vo.setMemberCardStatusDesc(vo.getMemberCardStatus() == 1 ? "上架" : "下架");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
memberDetailVO.setMemberCards(enrichedCards);
|
||||||
|
|
||||||
return memberDetailVO;
|
long activeCount = enrichedCards.stream()
|
||||||
}
|
.filter(card -> card.getMemberCardStatus() != null && card.getMemberCardStatus() == 1)
|
||||||
)
|
.count();
|
||||||
.flatMap(vo -> redisUtil.setWithExpire(cacheKey, vo, CACHE_EXPIRE_SECONDS)
|
memberDetailVO.setActiveCardCount((int) activeCount);
|
||||||
.then(Mono.just(vo)));
|
memberDetailVO.setInactiveCardCount(enrichedCards.size() - (int) activeCount);
|
||||||
});
|
|
||||||
|
return memberDetailVO;
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.flatMap(vo -> redisUtil.setWithExpire(cacheKey, vo, CACHE_EXPIRE_SECONDS)
|
||||||
|
.then(Mono.just(vo)))
|
||||||
|
.switchIfEmpty(Mono.error(() -> {
|
||||||
|
log.error("会员不存在: memberId={}", memberId);
|
||||||
|
return new NotFoundException(ErrorCode.NOT_FOUND_USER, "会员不存在");
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+32
-4
@@ -10,6 +10,7 @@ import cn.novalon.gym.manage.groupcourse.handler.GroupCourseHandler;
|
|||||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseRecommendHandler;
|
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseRecommendHandler;
|
||||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseTypeHandler;
|
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseTypeHandler;
|
||||||
import cn.novalon.gym.manage.groupcourse.handler.CourseLabelHandler;
|
import cn.novalon.gym.manage.groupcourse.handler.CourseLabelHandler;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.handler.CommonUploadHandler;
|
||||||
import cn.novalon.gym.manage.member.handler.MemberCardHandler;
|
import cn.novalon.gym.manage.member.handler.MemberCardHandler;
|
||||||
import cn.novalon.gym.manage.member.handler.MemberCardRecordHandler;
|
import cn.novalon.gym.manage.member.handler.MemberCardRecordHandler;
|
||||||
import cn.novalon.gym.manage.member.handler.MemberCardTransactionHandler;
|
import cn.novalon.gym.manage.member.handler.MemberCardTransactionHandler;
|
||||||
@@ -17,6 +18,7 @@ import cn.novalon.gym.manage.member.handler.MemberHandler;
|
|||||||
import cn.novalon.gym.manage.member.handler.WechatAuthHandler;
|
import cn.novalon.gym.manage.member.handler.WechatAuthHandler;
|
||||||
import cn.novalon.gym.manage.notify.handler.SysNoticeHandler;
|
import cn.novalon.gym.manage.notify.handler.SysNoticeHandler;
|
||||||
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
|
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
|
||||||
|
import cn.novalon.gym.manage.payment.handler.PaymentHandler;
|
||||||
import cn.novalon.gym.manage.sys.handler.auth.PasswordDiagnosticHandler;
|
import cn.novalon.gym.manage.sys.handler.auth.PasswordDiagnosticHandler;
|
||||||
import cn.novalon.gym.manage.sys.handler.auth.SysAuthHandler;
|
import cn.novalon.gym.manage.sys.handler.auth.SysAuthHandler;
|
||||||
import cn.novalon.gym.manage.sys.handler.config.SysConfigHandler;
|
import cn.novalon.gym.manage.sys.handler.config.SysConfigHandler;
|
||||||
@@ -78,7 +80,9 @@ public class SystemRouter {
|
|||||||
CourseLabelHandler courseLabelHandler,
|
CourseLabelHandler courseLabelHandler,
|
||||||
CheckInHandler checkInHandler,
|
CheckInHandler checkInHandler,
|
||||||
DataStatisticsHandler dataStatisticsHandler,
|
DataStatisticsHandler dataStatisticsHandler,
|
||||||
PhoneAuthHandler phoneAuthHandler) {
|
PhoneAuthHandler phoneAuthHandler,
|
||||||
|
PaymentHandler paymentHandler,
|
||||||
|
CommonUploadHandler commonUploadHandler) {
|
||||||
|
|
||||||
return route()
|
return route()
|
||||||
// ========== 诊断路由 ==========
|
// ========== 诊断路由 ==========
|
||||||
@@ -166,6 +170,7 @@ public class SystemRouter {
|
|||||||
.POST("/api/auth/login", authHandler::login)
|
.POST("/api/auth/login", authHandler::login)
|
||||||
.POST("/api/auth/register", authHandler::register)
|
.POST("/api/auth/register", authHandler::register)
|
||||||
.POST("/api/auth/logout", authHandler::logout)
|
.POST("/api/auth/logout", authHandler::logout)
|
||||||
|
.GET("/api/auth/me", authHandler::me)
|
||||||
|
|
||||||
// ========== 统计路由 ==========
|
// ========== 统计路由 ==========
|
||||||
.GET("/api/stats/overview", statsHandler::getOverview)
|
.GET("/api/stats/overview", statsHandler::getOverview)
|
||||||
@@ -213,6 +218,10 @@ public class SystemRouter {
|
|||||||
.GET("/api/files/preview/{fileName}", fileHandler::previewFileByName)
|
.GET("/api/files/preview/{fileName}", fileHandler::previewFileByName)
|
||||||
.DELETE("/api/files/{id}", fileHandler::deleteFile)
|
.DELETE("/api/files/{id}", fileHandler::deleteFile)
|
||||||
|
|
||||||
|
// ===== 通用文件上传(OSS)=====
|
||||||
|
.POST("/api/upload/image", commonUploadHandler::uploadImage)
|
||||||
|
.GET("/api/upload/presign", commonUploadHandler::presignUrl)
|
||||||
|
|
||||||
// ========== 权限路由 ==========
|
// ========== 权限路由 ==========
|
||||||
.GET("/api/permissions", permissionHandler::getAllPermissions)
|
.GET("/api/permissions", permissionHandler::getAllPermissions)
|
||||||
.GET("/api/permissions/{id}", permissionHandler::getPermissionById)
|
.GET("/api/permissions/{id}", permissionHandler::getPermissionById)
|
||||||
@@ -253,8 +262,11 @@ public class SystemRouter {
|
|||||||
|
|
||||||
// ===== 会员卡类型管理 =====
|
// ===== 会员卡类型管理 =====
|
||||||
.GET("/api/member-cards/active", memberCardHandler::getActiveCards)
|
.GET("/api/member-cards/active", memberCardHandler::getActiveCards)
|
||||||
|
.GET("/api/member-cards", memberCardHandler::listMemberCards)
|
||||||
.GET("/api/member-cards/{memberCardId}", memberCardHandler::getMemberCardById)
|
.GET("/api/member-cards/{memberCardId}", memberCardHandler::getMemberCardById)
|
||||||
.POST("/api/member-cards", memberCardHandler::createMemberCard)
|
.POST("/api/member-cards", memberCardHandler::createMemberCard)
|
||||||
|
.PUT("/api/member-cards/{id}", memberCardHandler::updateMemberCard)
|
||||||
|
.DELETE("/api/member-cards/{id}", memberCardHandler::deleteMemberCard)
|
||||||
|
|
||||||
// ===== 会员卡记录管理(核心业务)=====
|
// ===== 会员卡记录管理(核心业务)=====
|
||||||
.POST("/api/member-card-records/purchase", memberCardRecordHandler::purchaseCard)
|
.POST("/api/member-card-records/purchase", memberCardRecordHandler::purchaseCard)
|
||||||
@@ -329,6 +341,7 @@ public class SystemRouter {
|
|||||||
.PUT("/api/groupCourse/{id}", groupCourseHandler::updateGroupCourse)
|
.PUT("/api/groupCourse/{id}", groupCourseHandler::updateGroupCourse)
|
||||||
.DELETE("/api/groupCourse/{id}", groupCourseHandler::deleteGroupCourse)
|
.DELETE("/api/groupCourse/{id}", groupCourseHandler::deleteGroupCourse)
|
||||||
.POST("/api/groupCourse/{id}/cancel", groupCourseHandler::cancelGroupCourse)
|
.POST("/api/groupCourse/{id}/cancel", groupCourseHandler::cancelGroupCourse)
|
||||||
|
.POST("/api/groupCourse/{id}/restore", groupCourseHandler::restoreGroupCourse)
|
||||||
.POST("/api/groupCourse/signin/{memberId}", groupCourseHandler::signIn)
|
.POST("/api/groupCourse/signin/{memberId}", groupCourseHandler::signIn)
|
||||||
.POST("/api/groupCourse/search", groupCourseHandler::searchGroupCourses)
|
.POST("/api/groupCourse/search", groupCourseHandler::searchGroupCourses)
|
||||||
|
|
||||||
@@ -338,15 +351,17 @@ public class SystemRouter {
|
|||||||
.GET("/api/checkIn/qrcode", checkInHandler::getQRCode)
|
.GET("/api/checkIn/qrcode", checkInHandler::getQRCode)
|
||||||
|
|
||||||
// ===== 签到记录管理 =====
|
// ===== 签到记录管理 =====
|
||||||
|
.GET("/api/checkIn/records/export", checkInHandler::exportSignInRecords)
|
||||||
.GET("/api/checkIn/records", checkInHandler::getSignInRecords)
|
.GET("/api/checkIn/records", checkInHandler::getSignInRecords)
|
||||||
.GET("/api/checkIn/records/{id}", checkInHandler::getSignInRecordById)
|
.GET("/api/checkIn/records/{id}", checkInHandler::getSignInRecordById)
|
||||||
|
|
||||||
// ===== 签到统计 =====
|
// ===== 签到统计 =====
|
||||||
.GET("/api/checkIn/statistics", checkInHandler::getSignInStatistics)
|
.GET("/api/checkIn/statistics", checkInHandler::getSignInStatistics)
|
||||||
.GET("/api/checkIn/daily-stats", checkInHandler::getDailySignInStats)
|
.GET("/api/checkIn/daily-stats", checkInHandler::getDailySignInStats)
|
||||||
|
|
||||||
// ===== 签到数据导出 =====
|
// ===== 管理员签到记录(全员) =====
|
||||||
.GET("/api/checkIn/records/export", checkInHandler::exportSignInRecords)
|
.GET("/api/checkIn/admin/records", checkInHandler::getAllSignInRecords)
|
||||||
|
.GET("/api/checkIn/admin/statistics", checkInHandler::getAllSignInStatistics)
|
||||||
|
|
||||||
// ========================================
|
// ========================================
|
||||||
// ========== 数据统计模块路由 ============
|
// ========== 数据统计模块路由 ============
|
||||||
@@ -360,6 +375,19 @@ public class SystemRouter {
|
|||||||
.GET("/api/datacount/history", dataStatisticsHandler::queryHistoricalStatistics)
|
.GET("/api/datacount/history", dataStatisticsHandler::queryHistoricalStatistics)
|
||||||
.GET("/api/datacount/export", dataStatisticsHandler::exportStatistics)
|
.GET("/api/datacount/export", dataStatisticsHandler::exportStatistics)
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// ========== 支付模块路由 =================
|
||||||
|
// ========================================
|
||||||
|
|
||||||
|
// ===== 支付宝App支付 =====
|
||||||
|
.POST("/api/payment/create", paymentHandler::createPayment)
|
||||||
|
.GET("/api/payment/{orderId}", paymentHandler::getPaymentStatus)
|
||||||
|
.POST("/api/payment/{orderId}/refund", paymentHandler::refundPayment)
|
||||||
|
.POST("/api/payment/notify", paymentHandler::alipayNotify)
|
||||||
|
|
||||||
|
// ===== 支付宝扫码支付 =====
|
||||||
|
.POST("/api/payment/qrcode/create", paymentHandler::createQrCodePayment)
|
||||||
|
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ spring:
|
|||||||
cache:
|
cache:
|
||||||
type: none
|
type: none
|
||||||
r2dbc:
|
r2dbc:
|
||||||
url: r2dbc:postgresql://localhost:5432/manage_system
|
url: r2dbc:postgresql://localhost:55432/manage_system
|
||||||
username: postgres
|
username: novalon
|
||||||
password: 123456
|
password: novalon123
|
||||||
pool:
|
pool:
|
||||||
initial-size: 5
|
initial-size: 5
|
||||||
max-size: 20
|
max-size: 20
|
||||||
@@ -12,9 +12,9 @@ spring:
|
|||||||
max-life-time: 30m
|
max-life-time: 30m
|
||||||
acquire-timeout: 3s
|
acquire-timeout: 3s
|
||||||
flyway:
|
flyway:
|
||||||
url: jdbc:postgresql://localhost:5432/manage_system
|
url: jdbc:postgresql://localhost:55432/manage_system
|
||||||
user: postgres
|
user: novalon
|
||||||
password: 123456
|
password: novalon123
|
||||||
enabled: false
|
enabled: false
|
||||||
locations: classpath:db/migration
|
locations: classpath:db/migration
|
||||||
baseline-on-migrate: true
|
baseline-on-migrate: true
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ spring:
|
|||||||
exclude:
|
exclude:
|
||||||
- org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
|
- org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
|
||||||
r2dbc:
|
r2dbc:
|
||||||
url: r2dbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:manage_system}
|
url: r2dbc:postgresql://${DB_HOST:localhost}:${DB_PORT:55432}/${DB_NAME:manage_system}
|
||||||
username: ${DB_USERNAME:postgres}
|
username: ${DB_USERNAME:novalon}
|
||||||
password: ${DB_PASSWORD:123456}
|
password: ${DB_PASSWORD:novalon123}
|
||||||
pool:
|
pool:
|
||||||
initial-size: 10
|
initial-size: 10
|
||||||
max-size: 50
|
max-size: 50
|
||||||
@@ -25,9 +25,9 @@ spring:
|
|||||||
max-life-time: 1h
|
max-life-time: 1h
|
||||||
acquire-timeout: 5s
|
acquire-timeout: 5s
|
||||||
datasource:
|
datasource:
|
||||||
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:manage_system}
|
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:55432}/${DB_NAME:manage_system}
|
||||||
username: ${DB_USERNAME:postgres}
|
username: ${DB_USERNAME:novalon}
|
||||||
password: ${DB_PASSWORD:123456}
|
password: ${DB_PASSWORD:novalon123}
|
||||||
driver-class-name: org.postgresql.Driver
|
driver-class-name: org.postgresql.Driver
|
||||||
flyway:
|
flyway:
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|||||||
@@ -60,6 +60,10 @@
|
|||||||
<groupId>org.springframework.data</groupId>
|
<groupId>org.springframework.data</groupId>
|
||||||
<artifactId>spring-data-redis</artifactId>
|
<artifactId>spring-data-redis</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
+15
-2
@@ -1,5 +1,8 @@
|
|||||||
package cn.novalon.gym.manage.common.config;
|
package cn.novalon.gym.manage.common.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
|
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
|
||||||
@@ -24,13 +27,23 @@ public class RedisConfig {
|
|||||||
public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(
|
public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(
|
||||||
ReactiveRedisConnectionFactory connectionFactory) {
|
ReactiveRedisConnectionFactory connectionFactory) {
|
||||||
|
|
||||||
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
objectMapper.registerModule(new JavaTimeModule());
|
||||||
|
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||||
|
objectMapper.activateDefaultTyping(
|
||||||
|
objectMapper.getPolymorphicTypeValidator(),
|
||||||
|
ObjectMapper.DefaultTyping.NON_FINAL
|
||||||
|
);
|
||||||
|
|
||||||
|
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);
|
||||||
|
|
||||||
// 配置序列化上下文
|
// 配置序列化上下文
|
||||||
RedisSerializationContext<String, Object> serializationContext =
|
RedisSerializationContext<String, Object> serializationContext =
|
||||||
RedisSerializationContext.<String, Object>newSerializationContext()
|
RedisSerializationContext.<String, Object>newSerializationContext()
|
||||||
.key(StringRedisSerializer.UTF_8)
|
.key(StringRedisSerializer.UTF_8)
|
||||||
.value(new GenericJackson2JsonRedisSerializer())
|
.value(serializer)
|
||||||
.hashKey(StringRedisSerializer.UTF_8)
|
.hashKey(StringRedisSerializer.UTF_8)
|
||||||
.hashValue(new GenericJackson2JsonRedisSerializer())
|
.hashValue(serializer)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
|
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
|
||||||
|
|||||||
+181
-101
@@ -9,24 +9,17 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.core.Ordered;
|
import org.springframework.core.Ordered;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||||
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.HandlerStrategies;
|
|
||||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
|
||||||
import org.springframework.web.server.ServerWebExchange;
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
import org.springframework.web.server.WebFilter;
|
import org.springframework.web.server.WebFilter;
|
||||||
import org.springframework.web.server.WebFilterChain;
|
import org.springframework.web.server.WebFilterChain;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.util.LinkedHashMap;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||||
@@ -37,19 +30,76 @@ public class OperationLogWebFilter implements WebFilter {
|
|||||||
private final IOperationLogService operationLogService;
|
private final IOperationLogService operationLogService;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
private static final Map<String, OperationInfo> OPERATION_MAPPING = new ConcurrentHashMap<>();
|
/** 精确匹配的操作映射(method:path → module, operation) */
|
||||||
|
private static final Map<String, OperationInfo> PRECISE_MAPPING = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
/** 前缀匹配的操作映射(按声明顺序) */
|
||||||
|
private static final Map<String, OperationInfo> PREFIX_MAPPING = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
/** URL模块名称映射 */
|
||||||
|
private static final Map<String, String> MODULE_NAMES = new LinkedHashMap<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
OPERATION_MAPPING.put("POST:/api/roles", new OperationInfo("角色管理", "创建角色"));
|
// ===== 精确路径匹配 =====
|
||||||
OPERATION_MAPPING.put("PUT:/api/roles/", new OperationInfo("角色管理", "更新角色"));
|
PRECISE_MAPPING.put("POST:/api/roles", new OperationInfo("角色管理", "创建角色"));
|
||||||
OPERATION_MAPPING.put("DELETE:/api/roles/", new OperationInfo("角色管理", "删除角色"));
|
PRECISE_MAPPING.put("POST:/api/users", new OperationInfo("用户管理", "创建用户"));
|
||||||
OPERATION_MAPPING.put("POST:/api/users", new OperationInfo("用户管理", "创建用户"));
|
PRECISE_MAPPING.put("POST:/api/menus", new OperationInfo("菜单管理", "创建菜单"));
|
||||||
OPERATION_MAPPING.put("PUT:/api/users/", new OperationInfo("用户管理", "更新用户"));
|
PRECISE_MAPPING.put("POST:/api/auth/login", new OperationInfo("认证", "用户登录"));
|
||||||
OPERATION_MAPPING.put("DELETE:/api/users/", new OperationInfo("用户管理", "删除用户"));
|
PRECISE_MAPPING.put("GET:/api/groupCourse/types/categories", new OperationInfo("团课类型", "查询分类"));
|
||||||
OPERATION_MAPPING.put("POST:/api/users/", new OperationInfo("用户管理", "用户操作"));
|
PRECISE_MAPPING.put("POST:/api/groupCourse/types", new OperationInfo("团课类型", "创建类型"));
|
||||||
OPERATION_MAPPING.put("POST:/api/menus", new OperationInfo("菜单管理", "创建菜单"));
|
PRECISE_MAPPING.put("POST:/api/groupCourse", new OperationInfo("团课管理", "创建团课"));
|
||||||
OPERATION_MAPPING.put("PUT:/api/menus/", new OperationInfo("菜单管理", "更新菜单"));
|
PRECISE_MAPPING.put("POST:/api/member", new OperationInfo("会员管理", "创建会员"));
|
||||||
OPERATION_MAPPING.put("DELETE:/api/menus/", new OperationInfo("菜单管理", "删除菜单"));
|
PRECISE_MAPPING.put("POST:/api/member-cards", new OperationInfo("会员卡管理", "创建会员卡"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/groupCourse/recommend", new OperationInfo("推荐管理", "创建推荐"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/checkIn", new OperationInfo("签到管理", "签到"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/payment/create", new OperationInfo("支付管理", "创建支付"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/upload/image", new OperationInfo("文件管理", "上传图片"));
|
||||||
|
|
||||||
|
// ===== 前缀匹配 =====
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/roles/", new OperationInfo("角色管理", "更新角色"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/roles/", new OperationInfo("角色管理", "删除角色"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/users/", new OperationInfo("用户管理", "更新用户"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/users/", new OperationInfo("用户管理", "删除用户"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/menus/", new OperationInfo("菜单管理", "更新菜单"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/menus/", new OperationInfo("菜单管理", "删除菜单"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/groupCourse/types/", new OperationInfo("团课类型", "更新类型"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/types/", new OperationInfo("团课类型", "删除类型"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/groupCourse/", new OperationInfo("团课管理", "更新团课"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/", new OperationInfo("团课管理", "删除团课"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/groupCourse/", new OperationInfo("团课管理", "操作团课"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/member/", new OperationInfo("会员管理", "编辑会员"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/member/", new OperationInfo("会员管理", "删除会员"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/member-cards/", new OperationInfo("会员卡管理", "编辑会员卡"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/member-cards/", new OperationInfo("会员卡管理", "删除会员卡"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/groupCourse/recommend/", new OperationInfo("推荐管理", "更新推荐"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/recommend/", new OperationInfo("推荐管理", "删除推荐"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/groupCourse/recommend/", new OperationInfo("推荐管理", "操作推荐"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/member-card-transactions/", new OperationInfo("会员卡", "交易操作"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/payment/", new OperationInfo("支付管理", "更新支付"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/payment/", new OperationInfo("支付管理", "支付操作"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/admin/member/", new OperationInfo("会员管理", "管理员编辑会员"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/admin/member/", new OperationInfo("会员管理", "管理员删除会员"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/labels/", new OperationInfo("标签管理", "删除标签"));
|
||||||
|
|
||||||
|
// ===== URL模块名映射(用于未匹配写操作自动生成) =====
|
||||||
|
MODULE_NAMES.put("roles", "角色管理");
|
||||||
|
MODULE_NAMES.put("users", "用户管理");
|
||||||
|
MODULE_NAMES.put("menus", "菜单管理");
|
||||||
|
MODULE_NAMES.put("auth", "认证");
|
||||||
|
MODULE_NAMES.put("groupCourse", "团课管理");
|
||||||
|
MODULE_NAMES.put("member", "会员管理");
|
||||||
|
MODULE_NAMES.put("member-cards", "会员卡管理");
|
||||||
|
MODULE_NAMES.put("member-card-records", "会员卡记录");
|
||||||
|
MODULE_NAMES.put("member-card-transactions", "会员卡交易");
|
||||||
|
MODULE_NAMES.put("checkIn", "签到管理");
|
||||||
|
MODULE_NAMES.put("payment", "支付管理");
|
||||||
|
MODULE_NAMES.put("dictionaries", "字典管理");
|
||||||
|
MODULE_NAMES.put("config", "系统配置");
|
||||||
|
MODULE_NAMES.put("upload", "文件管理");
|
||||||
|
MODULE_NAMES.put("logs", "日志管理");
|
||||||
|
MODULE_NAMES.put("datacount", "数据统计");
|
||||||
|
MODULE_NAMES.put("diagnostic", "诊断");
|
||||||
|
MODULE_NAMES.put("stats", "统计");
|
||||||
}
|
}
|
||||||
|
|
||||||
public OperationLogWebFilter(IOperationLogService operationLogService, ObjectMapper objectMapper) {
|
public OperationLogWebFilter(IOperationLogService operationLogService, ObjectMapper objectMapper) {
|
||||||
@@ -61,10 +111,8 @@ public class OperationLogWebFilter implements WebFilter {
|
|||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void init() {
|
public void init() {
|
||||||
logger.info("=== OperationLogWebFilter 初始化 ===");
|
logger.info("=== OperationLogWebFilter 初始化 ===");
|
||||||
logger.info("操作日志映射配置数量: {}", OPERATION_MAPPING.size());
|
logger.info("精确匹配配置数量: {}, 前缀匹配配置数量: {}, 模块映射数量: {}",
|
||||||
OPERATION_MAPPING.forEach((key, value) -> {
|
PRECISE_MAPPING.size(), PREFIX_MAPPING.size(), MODULE_NAMES.size());
|
||||||
logger.info(" {} -> {}:{}", key, value.module, value.operation);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -72,103 +120,135 @@ public class OperationLogWebFilter implements WebFilter {
|
|||||||
ServerHttpRequest request = exchange.getRequest();
|
ServerHttpRequest request = exchange.getRequest();
|
||||||
String method = request.getMethod().name();
|
String method = request.getMethod().name();
|
||||||
String path = request.getPath().value();
|
String path = request.getPath().value();
|
||||||
|
String key = method + ":" + path;
|
||||||
|
|
||||||
logger.info("WebFilter 拦截请求: {} {}", method, path);
|
// 先尝试精确匹配
|
||||||
|
OperationInfo operationInfo = PRECISE_MAPPING.get(key);
|
||||||
|
|
||||||
OperationInfo operationInfo = findOperationInfo(method, path);
|
if (operationInfo == null) {
|
||||||
|
// 尝试前缀匹配
|
||||||
|
operationInfo = findPrefixMatch(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (operationInfo == null) {
|
||||||
|
// 未匹配:如果是写操作(POST/PUT/DELETE),自动生成记录
|
||||||
|
if (isWriteOperation(method)) {
|
||||||
|
operationInfo = buildAutoOperationInfo(method, path);
|
||||||
|
logger.info("自动生成操作日志: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("匹配到操作日志配置: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
||||||
|
}
|
||||||
|
|
||||||
if (operationInfo == null) {
|
if (operationInfo == null) {
|
||||||
logger.info("未匹配到操作日志配置,跳过: {} {}", method, path);
|
|
||||||
return chain.filter(exchange);
|
return chain.filter(exchange);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("匹配到操作日志配置: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
|
||||||
|
|
||||||
long startTime = System.currentTimeMillis();
|
long startTime = System.currentTimeMillis();
|
||||||
String ip = IpUtils.getClientIp(request);
|
String ip = IpUtils.getClientIp(request);
|
||||||
|
final OperationInfo finalInfo = operationInfo;
|
||||||
|
|
||||||
return Mono.deferContextual(contextView -> {
|
return chain.filter(exchange)
|
||||||
return chain.filter(exchange)
|
.then(Mono.defer(() -> {
|
||||||
.then(Mono.defer(() -> {
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
long duration = System.currentTimeMillis() - startTime;
|
return getCurrentUsername()
|
||||||
logger.info("请求处理完成,准备保存操作日志: {} {}, 耗时: {}ms", method, path, duration);
|
.flatMap(username -> saveOperationLog(username, method, path, ip, duration, "0", null, finalInfo));
|
||||||
|
}))
|
||||||
return ReactiveSecurityContextHolder.getContext()
|
.onErrorResume(error -> {
|
||||||
.flatMap(securityContext -> {
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
Object principal = securityContext.getAuthentication().getPrincipal();
|
logger.error("请求处理失败: {} {}, 错误: {}", method, path, error.getMessage());
|
||||||
String username = principal instanceof String ? (String) principal : "system";
|
return getCurrentUsername()
|
||||||
logger.info("获取到用户名: {}", username);
|
.flatMap(username -> saveOperationLog(username, method, path, ip, duration, "1",
|
||||||
return Mono.just(username);
|
error.getMessage().substring(0, Math.min(error.getMessage().length(), 500)), finalInfo))
|
||||||
})
|
.then(Mono.error(error));
|
||||||
.defaultIfEmpty("system")
|
});
|
||||||
.flatMap(username -> {
|
|
||||||
logger.info("开始保存操作日志: 用户={}, 操作={}", username,
|
|
||||||
operationInfo.module + " - " + operationInfo.operation);
|
|
||||||
|
|
||||||
OperationLog log = new OperationLog();
|
|
||||||
log.setUsername(username);
|
|
||||||
log.setOperation(operationInfo.module + " - " + operationInfo.operation);
|
|
||||||
log.setMethod(method + " " + path);
|
|
||||||
log.setParams(null);
|
|
||||||
log.setIp(ip);
|
|
||||||
log.setDuration(duration);
|
|
||||||
log.setStatus("0");
|
|
||||||
|
|
||||||
return operationLogService.save(log)
|
|
||||||
.doOnSuccess(saved -> logger.info("操作日志保存成功: {} - {}",
|
|
||||||
operationInfo.module, operationInfo.operation))
|
|
||||||
.doOnError(e -> logger.error("操作日志保存失败: {}", e.getMessage(), e))
|
|
||||||
.onErrorResume(e -> Mono.empty());
|
|
||||||
})
|
|
||||||
.then();
|
|
||||||
}))
|
|
||||||
.onErrorResume(error -> {
|
|
||||||
long duration = System.currentTimeMillis() - startTime;
|
|
||||||
logger.error("请求处理失败: {} {}, 错误: {}", method, path, error.getMessage());
|
|
||||||
|
|
||||||
return ReactiveSecurityContextHolder.getContext()
|
|
||||||
.flatMap(securityContext -> {
|
|
||||||
Object principal = securityContext.getAuthentication().getPrincipal();
|
|
||||||
String username = principal instanceof String ? (String) principal : "system";
|
|
||||||
return Mono.just(username);
|
|
||||||
})
|
|
||||||
.defaultIfEmpty("system")
|
|
||||||
.flatMap(username -> {
|
|
||||||
OperationLog log = new OperationLog();
|
|
||||||
log.setUsername(username);
|
|
||||||
log.setOperation(operationInfo.module + " - " + operationInfo.operation);
|
|
||||||
log.setMethod(method + " " + path);
|
|
||||||
log.setParams(null);
|
|
||||||
log.setIp(ip);
|
|
||||||
log.setDuration(duration);
|
|
||||||
log.setStatus("1");
|
|
||||||
log.setErrorMsg(error.getMessage());
|
|
||||||
|
|
||||||
return operationLogService.save(log)
|
|
||||||
.doOnError(e -> logger.error("错误日志保存失败: {}", e.getMessage()))
|
|
||||||
.onErrorResume(e -> Mono.empty());
|
|
||||||
})
|
|
||||||
.then(Mono.error(error));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationInfo findOperationInfo(String method, String path) {
|
private boolean isWriteOperation(String method) {
|
||||||
String key = method + ":" + path;
|
return HttpMethod.POST.name().equals(method) ||
|
||||||
if (OPERATION_MAPPING.containsKey(key)) {
|
HttpMethod.PUT.name().equals(method) ||
|
||||||
return OPERATION_MAPPING.get(key);
|
HttpMethod.DELETE.name().equals(method) ||
|
||||||
}
|
HttpMethod.PATCH.name().equals(method);
|
||||||
|
}
|
||||||
|
|
||||||
for (Map.Entry<String, OperationInfo> entry : OPERATION_MAPPING.entrySet()) {
|
private OperationInfo findPrefixMatch(String key) {
|
||||||
String mappingKey = entry.getKey();
|
for (Map.Entry<String, OperationInfo> entry : PREFIX_MAPPING.entrySet()) {
|
||||||
if (key.startsWith(mappingKey)) {
|
if (key.startsWith(entry.getKey())) {
|
||||||
return entry.getValue();
|
return entry.getValue();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据URL路径自动生成操作信息
|
||||||
|
* 例如: DELETE:/api/groupCourse/types/5 → 团课管理 - 删除操作
|
||||||
|
*/
|
||||||
|
private OperationInfo buildAutoOperationInfo(String method, String path) {
|
||||||
|
String module = extractModuleFromPath(path);
|
||||||
|
String operation = methodToOperationName(method);
|
||||||
|
return new OperationInfo(module, operation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractModuleFromPath(String path) {
|
||||||
|
// 去掉 /api/ 前缀,取第一段作为模块名
|
||||||
|
if (path.startsWith("/api/")) {
|
||||||
|
String subPath = path.substring(5); // remove "/api/"
|
||||||
|
int slashIdx = subPath.indexOf('/');
|
||||||
|
String moduleKey = slashIdx > 0 ? subPath.substring(0, slashIdx) : subPath;
|
||||||
|
|
||||||
|
// 尝试复合模块名 (如 member-cards)
|
||||||
|
if (slashIdx > 0) {
|
||||||
|
String rest = subPath.substring(slashIdx + 1);
|
||||||
|
int nextSlash = rest.indexOf('/');
|
||||||
|
String secondPart = nextSlash > 0 ? rest.substring(0, nextSlash) : rest;
|
||||||
|
String compositeKey = moduleKey + "/" + secondPart;
|
||||||
|
if (MODULE_NAMES.containsKey(compositeKey)) {
|
||||||
|
return MODULE_NAMES.get(compositeKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return MODULE_NAMES.getOrDefault(moduleKey, moduleKey);
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String methodToOperationName(String method) {
|
||||||
|
switch (method.toUpperCase()) {
|
||||||
|
case "POST": return "创建/新增操作";
|
||||||
|
case "PUT": return "编辑/更新操作";
|
||||||
|
case "DELETE": return "删除操作";
|
||||||
|
case "PATCH": return "修改操作";
|
||||||
|
default: return "操作";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<String> getCurrentUsername() {
|
||||||
|
return ReactiveSecurityContextHolder.getContext()
|
||||||
|
.map(ctx -> ctx.getAuthentication().getPrincipal())
|
||||||
|
.map(principal -> principal instanceof String ? (String) principal : "system")
|
||||||
|
.defaultIfEmpty("system")
|
||||||
|
.onErrorReturn("system");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> saveOperationLog(String username, String method, String path, String ip,
|
||||||
|
long duration, String status, String errorMsg, OperationInfo info) {
|
||||||
|
OperationLog log = new OperationLog();
|
||||||
|
log.setUsername(username);
|
||||||
|
log.setOperation(info.module + " - " + info.operation);
|
||||||
|
log.setMethod(method + " " + path);
|
||||||
|
log.setIp(ip);
|
||||||
|
log.setDuration(duration);
|
||||||
|
log.setStatus(status);
|
||||||
|
log.setErrorMsg(errorMsg);
|
||||||
|
|
||||||
|
return operationLogService.save(log)
|
||||||
|
.doOnSuccess(saved -> logger.debug("操作日志保存成功: {} - {}", info.module, info.operation))
|
||||||
|
.doOnError(e -> logger.error("操作日志保存失败: {}", e.getMessage(), e))
|
||||||
|
.onErrorResume(e -> Mono.empty())
|
||||||
|
.then();
|
||||||
|
}
|
||||||
|
|
||||||
private static class OperationInfo {
|
private static class OperationInfo {
|
||||||
final String module;
|
final String module;
|
||||||
final String operation;
|
final String operation;
|
||||||
|
|||||||
+20
@@ -11,6 +11,11 @@ import org.springframework.security.config.annotation.web.reactive.EnableWebFlux
|
|||||||
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
|
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
|
||||||
import org.springframework.security.config.web.server.ServerHttpSecurity;
|
import org.springframework.security.config.web.server.ServerHttpSecurity;
|
||||||
import org.springframework.security.web.server.SecurityWebFilterChain;
|
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||||
|
import org.springframework.web.cors.CorsConfiguration;
|
||||||
|
import org.springframework.web.cors.reactive.CorsConfigurationSource;
|
||||||
|
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebFluxSecurity
|
@EnableWebFluxSecurity
|
||||||
@@ -29,6 +34,20 @@ public class SecurityConfig {
|
|||||||
this.environment = environment;
|
this.environment = environment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CorsConfigurationSource corsConfigurationSource() {
|
||||||
|
CorsConfiguration configuration = new CorsConfiguration();
|
||||||
|
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
|
||||||
|
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||||
|
configuration.setAllowedHeaders(Arrays.asList("*"));
|
||||||
|
configuration.setAllowCredentials(true);
|
||||||
|
configuration.setMaxAge(3600L);
|
||||||
|
|
||||||
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||||
|
source.registerCorsConfiguration("/**", configuration);
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
||||||
String[] activeProfiles = environment.getActiveProfiles();
|
String[] activeProfiles = environment.getActiveProfiles();
|
||||||
@@ -41,6 +60,7 @@ public class SecurityConfig {
|
|||||||
activeProfiles.length > 0 ? String.join(",", activeProfiles) : "default", isDevOrTest);
|
activeProfiles.length > 0 ? String.join(",", activeProfiles) : "default", isDevOrTest);
|
||||||
|
|
||||||
http
|
http
|
||||||
|
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||||
.csrf(ServerHttpSecurity.CsrfSpec::disable)
|
.csrf(ServerHttpSecurity.CsrfSpec::disable)
|
||||||
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
|
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
|
||||||
.formLogin(ServerHttpSecurity.FormLoginSpec::disable)
|
.formLogin(ServerHttpSecurity.FormLoginSpec::disable)
|
||||||
|
|||||||
+2
@@ -53,6 +53,8 @@ public interface ISysUserService {
|
|||||||
|
|
||||||
Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword);
|
Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword);
|
||||||
|
|
||||||
|
Mono<Boolean> verifyPassword(Long userId, String password);
|
||||||
|
|
||||||
Mono<Void> updateRoleIdToNullByRoleId(Long roleId);
|
Mono<Void> updateRoleIdToNullByRoleId(Long roleId);
|
||||||
|
|
||||||
Mono<Void> assignRolesToUser(Long userId, java.util.List<Long> roleIds);
|
Mono<Void> assignRolesToUser(Long userId, java.util.List<Long> roleIds);
|
||||||
|
|||||||
+3
@@ -120,6 +120,9 @@ public class SysPermissionService implements ISysPermissionService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Flux<SysPermission> findByRoleIds(List<Long> roleIds) {
|
public Flux<SysPermission> findByRoleIds(List<Long> roleIds) {
|
||||||
|
if (roleIds == null || roleIds.isEmpty()) {
|
||||||
|
return Flux.empty();
|
||||||
|
}
|
||||||
return permissionRepository.findByRoleIds(roleIds);
|
return permissionRepository.findByRoleIds(roleIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-1
@@ -83,7 +83,6 @@ public class SysRoleService implements ISysRoleService {
|
|||||||
@Override
|
@Override
|
||||||
public Mono<SysRole> createRole(CreateRoleCommand command) {
|
public Mono<SysRole> createRole(CreateRoleCommand command) {
|
||||||
SysRole role = new SysRole();
|
SysRole role = new SysRole();
|
||||||
role.generateId();
|
|
||||||
role.setRoleName(command.roleName());
|
role.setRoleName(command.roleName());
|
||||||
role.setRoleKey(command.roleKey());
|
role.setRoleKey(command.roleKey());
|
||||||
role.setRoleSort(command.roleSort());
|
role.setRoleSort(command.roleSort());
|
||||||
|
|||||||
+7
-2
@@ -97,7 +97,6 @@ public class SysUserService implements ISysUserService {
|
|||||||
logger.info("SysUserService.createUser - 用户名: {}, 密码前缀: {}",
|
logger.info("SysUserService.createUser - 用户名: {}, 密码前缀: {}",
|
||||||
user.getUsername(),
|
user.getUsername(),
|
||||||
user.getPassword() != null ? user.getPassword().substring(0, 7) : "null");
|
user.getPassword() != null ? user.getPassword().substring(0, 7) : "null");
|
||||||
user.generateId();
|
|
||||||
if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")
|
if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")
|
||||||
&& !user.getPassword().startsWith("$2b$")) {
|
&& !user.getPassword().startsWith("$2b$")) {
|
||||||
logger.info("密码不以$2a$或$2b$开头,重新编码");
|
logger.info("密码不以$2a$或$2b$开头,重新编码");
|
||||||
@@ -117,7 +116,6 @@ public class SysUserService implements ISysUserService {
|
|||||||
@Override
|
@Override
|
||||||
public Mono<SysUser> createUser(CreateUserCommand command) {
|
public Mono<SysUser> createUser(CreateUserCommand command) {
|
||||||
SysUser user = new SysUser();
|
SysUser user = new SysUser();
|
||||||
user.generateId();
|
|
||||||
user.setUsername(command.username().getValue());
|
user.setUsername(command.username().getValue());
|
||||||
user.setPassword(passwordEncoder.encode(command.password().getValue()));
|
user.setPassword(passwordEncoder.encode(command.password().getValue()));
|
||||||
user.setEmail(command.email().getValue());
|
user.setEmail(command.email().getValue());
|
||||||
@@ -204,6 +202,13 @@ public class SysUserService implements ISysUserService {
|
|||||||
return userRepository.updateRoleIdToNullByRoleId(roleId);
|
return userRepository.updateRoleIdToNullByRoleId(roleId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Boolean> verifyPassword(Long userId, String password) {
|
||||||
|
return userRepository.findById(userId)
|
||||||
|
.map(user -> passwordEncoder.matches(password, user.getPassword()))
|
||||||
|
.defaultIfEmpty(false);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword) {
|
public Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword) {
|
||||||
return userRepository.findById(userId)
|
return userRepository.findById(userId)
|
||||||
|
|||||||
+27
-1
@@ -2,6 +2,8 @@ package cn.novalon.gym.manage.sys.dto.response;
|
|||||||
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证响应DTO
|
* 认证响应DTO
|
||||||
*
|
*
|
||||||
@@ -20,13 +22,21 @@ public class AuthResponse {
|
|||||||
@Schema(description = "用户名", example = "admin")
|
@Schema(description = "用户名", example = "admin")
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
|
@Schema(description = "角色标识列表", example = "[\"admin\"]")
|
||||||
|
private List<String> roles;
|
||||||
|
|
||||||
|
@Schema(description = "权限码列表", example = "[\"system:user:view\", \"system:user:create\"]")
|
||||||
|
private List<String> permissions;
|
||||||
|
|
||||||
public AuthResponse() {
|
public AuthResponse() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public AuthResponse(String token, Long userId, String username) {
|
public AuthResponse(String token, Long userId, String username, List<String> roles, List<String> permissions) {
|
||||||
this.token = token;
|
this.token = token;
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
this.username = username;
|
this.username = username;
|
||||||
|
this.roles = roles;
|
||||||
|
this.permissions = permissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getToken() {
|
public String getToken() {
|
||||||
@@ -52,4 +62,20 @@ public class AuthResponse {
|
|||||||
public void setUsername(String username) {
|
public void setUsername(String username) {
|
||||||
this.username = username;
|
this.username = username;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<String> getRoles() {
|
||||||
|
return roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRoles(List<String> roles) {
|
||||||
|
this.roles = roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getPermissions() {
|
||||||
|
return permissions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPermissions(List<String> permissions) {
|
||||||
|
this.permissions = permissions;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+88
-19
@@ -8,6 +8,7 @@ import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
|||||||
import cn.novalon.gym.manage.sys.core.domain.SysLoginLog;
|
import cn.novalon.gym.manage.sys.core.domain.SysLoginLog;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysLoginLogService;
|
import cn.novalon.gym.manage.sys.core.service.ISysLoginLogService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
||||||
import cn.novalon.gym.manage.sys.util.UserAgentParser;
|
import cn.novalon.gym.manage.sys.util.UserAgentParser;
|
||||||
import cn.novalon.gym.manage.sys.util.IpLocationParser;
|
import cn.novalon.gym.manage.sys.util.IpLocationParser;
|
||||||
import cn.novalon.gym.manage.common.util.StatusConstants;
|
import cn.novalon.gym.manage.common.util.StatusConstants;
|
||||||
@@ -28,6 +29,7 @@ import org.springframework.web.reactive.function.server.ServerResponse;
|
|||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -50,6 +52,7 @@ public class SysAuthHandler {
|
|||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final JwtTokenProvider jwtTokenProvider;
|
private final JwtTokenProvider jwtTokenProvider;
|
||||||
private final ISysLoginLogService loginLogService;
|
private final ISysLoginLogService loginLogService;
|
||||||
|
private final ISysPermissionService permissionService;
|
||||||
private final UserAgentParser userAgentParser;
|
private final UserAgentParser userAgentParser;
|
||||||
private final IpLocationParser ipLocationParser;
|
private final IpLocationParser ipLocationParser;
|
||||||
|
|
||||||
@@ -60,11 +63,13 @@ public class SysAuthHandler {
|
|||||||
public SysAuthHandler(ISysUserService userService,
|
public SysAuthHandler(ISysUserService userService,
|
||||||
@Qualifier("passwordEncoder") PasswordEncoder passwordEncoder,
|
@Qualifier("passwordEncoder") PasswordEncoder passwordEncoder,
|
||||||
JwtTokenProvider jwtTokenProvider, ISysLoginLogService loginLogService,
|
JwtTokenProvider jwtTokenProvider, ISysLoginLogService loginLogService,
|
||||||
|
ISysPermissionService permissionService,
|
||||||
UserAgentParser userAgentParser, IpLocationParser ipLocationParser) {
|
UserAgentParser userAgentParser, IpLocationParser ipLocationParser) {
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
this.jwtTokenProvider = jwtTokenProvider;
|
this.jwtTokenProvider = jwtTokenProvider;
|
||||||
this.loginLogService = loginLogService;
|
this.loginLogService = loginLogService;
|
||||||
|
this.permissionService = permissionService;
|
||||||
this.userAgentParser = userAgentParser;
|
this.userAgentParser = userAgentParser;
|
||||||
this.ipLocationParser = ipLocationParser;
|
this.ipLocationParser = ipLocationParser;
|
||||||
|
|
||||||
@@ -126,29 +131,49 @@ public class SysAuthHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return userService.getUserRoles(user.getId())
|
return userService.getUserRoles(user.getId())
|
||||||
.map(role -> role.getRoleKey())
|
|
||||||
.collectList()
|
.collectList()
|
||||||
.flatMap(roleKeys -> {
|
.flatMap(roles -> {
|
||||||
String token = jwtTokenProvider
|
List<String> roleKeys = roles.stream()
|
||||||
.generateToken(
|
.map(r -> r.getRoleKey())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
List<Long> roleIds = roles.stream()
|
||||||
|
.map(r -> r.getId())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
Mono<List<String>> permCodesMono;
|
||||||
|
if (roleIds.isEmpty()) {
|
||||||
|
permCodesMono = Mono.just(java.util.Collections.<String>emptyList());
|
||||||
|
} else {
|
||||||
|
permCodesMono = permissionService.findByRoleIds(roleIds)
|
||||||
|
.map(p -> p.getPermissionCode())
|
||||||
|
.collectList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return permCodesMono
|
||||||
|
.flatMap(permCodes -> {
|
||||||
|
String token = jwtTokenProvider
|
||||||
|
.generateToken(
|
||||||
user.getUsername(),
|
user.getUsername(),
|
||||||
user.getId(),
|
user.getId(),
|
||||||
roleKeys);
|
roleKeys);
|
||||||
logger.info("用户登录成功: username={}, userId={}, roles={}",
|
logger.info("用户登录成功: username={}, userId={}, roles={}, permissions={}",
|
||||||
user.getUsername(),
|
user.getUsername(),
|
||||||
user.getId(),
|
user.getId(),
|
||||||
roleKeys);
|
roleKeys,
|
||||||
recordLoginLog(loginRequest
|
permCodes.size());
|
||||||
.getUsername(),
|
recordLoginLog(loginRequest.getUsername(),
|
||||||
clientIp,
|
clientIp,
|
||||||
"0", "登录成功",
|
"0", "登录成功",
|
||||||
userAgent);
|
userAgent);
|
||||||
AuthResponse response = new AuthResponse(
|
AuthResponse response = new AuthResponse(
|
||||||
token,
|
token,
|
||||||
user.getId(),
|
user.getId(),
|
||||||
user.getUsername());
|
user.getUsername(),
|
||||||
return ServerResponse.ok()
|
roleKeys,
|
||||||
.bodyValue(response);
|
permCodes);
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.bodyValue(response);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.switchIfEmpty(Mono.defer(() -> {
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
@@ -190,6 +215,50 @@ public class SysAuthHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取当前用户信息", description = "根据Token获取当前登录用户的详细信息和权限")
|
||||||
|
public Mono<ServerResponse> me(ServerRequest request) {
|
||||||
|
String authHeader = request.headers().firstHeader("Authorization");
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
return ServerResponse.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
if (!jwtTokenProvider.validateToken(token)) {
|
||||||
|
return ServerResponse.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
Long userId = jwtTokenProvider.getUserIdFromToken(token);
|
||||||
|
return userService.findById(userId)
|
||||||
|
.flatMap(user -> userService.getUserRoles(user.getId())
|
||||||
|
.collectList()
|
||||||
|
.flatMap(roles -> {
|
||||||
|
List<String> roleKeys = roles.stream()
|
||||||
|
.map(r -> r.getRoleKey())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
List<Long> roleIds = roles.stream()
|
||||||
|
.map(r -> r.getId())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
Mono<List<String>> permCodesMono;
|
||||||
|
if (roleIds.isEmpty()) {
|
||||||
|
permCodesMono = Mono.just(java.util.Collections.<String>emptyList());
|
||||||
|
} else {
|
||||||
|
permCodesMono = permissionService.findByRoleIds(roleIds)
|
||||||
|
.map(p -> p.getPermissionCode())
|
||||||
|
.collectList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return permCodesMono
|
||||||
|
.flatMap(permCodes -> {
|
||||||
|
AuthResponse response = new AuthResponse(
|
||||||
|
token,
|
||||||
|
user.getId(),
|
||||||
|
user.getUsername(),
|
||||||
|
roleKeys,
|
||||||
|
permCodes);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
private void recordLoginLog(String username, String ip, String status, String message, String userAgent) {
|
private void recordLoginLog(String username, String ip, String status, String message, String userAgent) {
|
||||||
try {
|
try {
|
||||||
SysLoginLog loginLog = new SysLoginLog();
|
SysLoginLog loginLog = new SysLoginLog();
|
||||||
|
|||||||
+34
-6
@@ -1,7 +1,11 @@
|
|||||||
package cn.novalon.gym.manage.sys.handler.permission;
|
package cn.novalon.gym.manage.sys.handler.permission;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysPermission;
|
import cn.novalon.gym.manage.sys.core.domain.SysPermission;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -22,10 +26,19 @@ import java.util.List;
|
|||||||
@Tag(name = "权限管理", description = "权限相关操作")
|
@Tag(name = "权限管理", description = "权限相关操作")
|
||||||
public class SysPermissionHandler {
|
public class SysPermissionHandler {
|
||||||
|
|
||||||
private final ISysPermissionService permissionService;
|
private static final Long BUILTIN_ROLE_ID = 1L;
|
||||||
|
|
||||||
public SysPermissionHandler(ISysPermissionService permissionService) {
|
private final ISysPermissionService permissionService;
|
||||||
|
private final ISysRoleService roleService;
|
||||||
|
private final ISysUserService userService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
|
public SysPermissionHandler(ISysPermissionService permissionService, ISysRoleService roleService,
|
||||||
|
ISysUserService userService, AuthUtil authUtil) {
|
||||||
this.permissionService = permissionService;
|
this.permissionService = permissionService;
|
||||||
|
this.roleService = roleService;
|
||||||
|
this.userService = userService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有权限", description = "获取系统中所有权限列表")
|
@Operation(summary = "获取所有权限", description = "获取系统中所有权限列表")
|
||||||
@@ -97,12 +110,27 @@ public class SysPermissionHandler {
|
|||||||
.body(permissionService.getPermissionsByRoleId(roleId), SysPermission.class);
|
.body(permissionService.getPermissionsByRoleId(roleId), SysPermission.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表")
|
@Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表,需验证管理员密码,超级管理员角色不可被分配")
|
||||||
public Mono<ServerResponse> assignPermissionsToRole(ServerRequest request) {
|
public Mono<ServerResponse> assignPermissionsToRole(ServerRequest request) {
|
||||||
Long roleId = Long.valueOf(request.pathVariable("id"));
|
Long roleId = Long.valueOf(request.pathVariable("id"));
|
||||||
return request.bodyToMono(AssignPermissionsRequest.class)
|
|
||||||
.flatMap(req -> permissionService.assignPermissionsToRole(roleId, req.permissionIds()))
|
return verifyAdminPassword(request)
|
||||||
.then(ServerResponse.ok().build());
|
.flatMap(valid -> {
|
||||||
|
if (!valid) return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
|
if (BUILTIN_ROLE_ID.equals(roleId)) return ServerResponse.badRequest().bodyValue("超级管理员角色权限不可被修改");
|
||||||
|
return request.bodyToMono(AssignPermissionsRequest.class)
|
||||||
|
.flatMap(req -> permissionService.assignPermissionsToRole(roleId, req.permissionIds()))
|
||||||
|
.then(ServerResponse.ok().build());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Boolean> verifyAdminPassword(ServerRequest request) {
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
return userService.verifyPassword(adminId, adminPassword);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record AssignPermissionsRequest(List<Long> permissionIds) {}
|
private record AssignPermissionsRequest(List<Long> permissionIds) {}
|
||||||
|
|||||||
+43
-17
@@ -2,6 +2,8 @@ package cn.novalon.gym.manage.sys.handler.role;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.RoleCreateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.RoleCreateRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
||||||
@@ -30,12 +32,18 @@ import java.util.Map;
|
|||||||
@Tag(name = "角色管理", description = "角色相关操作")
|
@Tag(name = "角色管理", description = "角色相关操作")
|
||||||
public class SysRoleHandler {
|
public class SysRoleHandler {
|
||||||
|
|
||||||
|
private static final Long BUILTIN_ROLE_ID = 1L;
|
||||||
|
|
||||||
private final ISysRoleService roleService;
|
private final ISysRoleService roleService;
|
||||||
private final Validator validator;
|
private final Validator validator;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
private final ISysUserService userService;
|
||||||
|
|
||||||
public SysRoleHandler(ISysRoleService roleService, Validator validator) {
|
public SysRoleHandler(ISysRoleService roleService, Validator validator, AuthUtil authUtil, ISysUserService userService) {
|
||||||
this.roleService = roleService;
|
this.roleService = roleService;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
|
this.authUtil = authUtil;
|
||||||
|
this.userService = userService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有角色", description = "获取系统中所有角色列表")
|
@Operation(summary = "获取所有角色", description = "获取系统中所有角色列表")
|
||||||
@@ -115,30 +123,39 @@ public class SysRoleHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新角色", description = "更新角色信息")
|
@Operation(summary = "更新角色", description = "更新角色信息,需验证管理员密码,超级管理员角色不可被编辑")
|
||||||
@OperationLog(operation = "更新角色", module = "角色管理")
|
@OperationLog(operation = "更新角色", module = "角色管理")
|
||||||
public Mono<ServerResponse> updateRole(ServerRequest request) {
|
public Mono<ServerResponse> updateRole(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return request.bodyToMono(RoleUpdateRequest.class)
|
|
||||||
.map(req -> UpdateRoleCommand.of(
|
return verifyAdminPassword(request)
|
||||||
id,
|
.flatMap(valid -> {
|
||||||
req.getRoleName(),
|
if (!valid) return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
req.getRoleKey(),
|
if (BUILTIN_ROLE_ID.equals(id)) return ServerResponse.badRequest().bodyValue("超级管理员角色不可编辑");
|
||||||
req.getRoleSort(),
|
return request.bodyToMono(RoleUpdateRequest.class)
|
||||||
req.getStatus()
|
.map(req -> UpdateRoleCommand.of(
|
||||||
))
|
id, req.getRoleName(), req.getRoleKey(),
|
||||||
.flatMap(roleService::updateRole)
|
req.getRoleSort(), req.getStatus()
|
||||||
.flatMap(updatedRole -> ServerResponse.ok().bodyValue(updatedRole))
|
))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.flatMap(roleService::updateRole)
|
||||||
|
.flatMap(updatedRole -> ServerResponse.ok().bodyValue(updatedRole))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除角色", description = "逻辑删除角色")
|
@Operation(summary = "删除角色", description = "逻辑删除角色,需验证管理员密码,超级管理员角色不可被删除")
|
||||||
@OperationLog(operation = "删除角色", module = "角色管理")
|
@OperationLog(operation = "删除角色", module = "角色管理")
|
||||||
public Mono<ServerResponse> deleteRole(ServerRequest request) {
|
public Mono<ServerResponse> deleteRole(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return roleService.logicalDeleteRole(id)
|
|
||||||
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
return verifyAdminPassword(request)
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.flatMap(valid -> {
|
||||||
|
if (!valid) return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
|
if (BUILTIN_ROLE_ID.equals(id)) return ServerResponse.badRequest().bodyValue("超级管理员角色不可删除");
|
||||||
|
return roleService.logicalDeleteRole(id)
|
||||||
|
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "恢复角色", description = "恢复被逻辑删除的角色")
|
@Operation(summary = "恢复角色", description = "恢复被逻辑删除的角色")
|
||||||
@@ -148,4 +165,13 @@ public class SysRoleHandler {
|
|||||||
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Mono<Boolean> verifyAdminPassword(ServerRequest request) {
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
return userService.verifyPassword(adminId, adminPassword);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+92
-32
@@ -2,6 +2,7 @@ package cn.novalon.gym.manage.sys.handler.user;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.AssignRolesRequest;
|
import cn.novalon.gym.manage.sys.dto.request.AssignRolesRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.PasswordChangeRequest;
|
import cn.novalon.gym.manage.sys.dto.request.PasswordChangeRequest;
|
||||||
@@ -42,10 +43,12 @@ public class SysUserHandler {
|
|||||||
private static final Logger logger = LoggerFactory.getLogger(SysUserHandler.class);
|
private static final Logger logger = LoggerFactory.getLogger(SysUserHandler.class);
|
||||||
private final ISysUserService userService;
|
private final ISysUserService userService;
|
||||||
private final Validator validator;
|
private final Validator validator;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public SysUserHandler(ISysUserService userService, Validator validator) {
|
public SysUserHandler(ISysUserService userService, Validator validator, AuthUtil authUtil) {
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有用户", description = "获取系统中所有用户列表")
|
@Operation(summary = "获取所有用户", description = "获取系统中所有用户列表")
|
||||||
@@ -152,39 +155,63 @@ public class SysUserHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新用户", description = "更新用户信息")
|
@Operation(summary = "更新用户", description = "更新用户信息,需验证管理员密码,超级管理员不可编辑")
|
||||||
@OperationLog(operation = "更新用户", module = "用户管理")
|
@OperationLog(operation = "更新用户", module = "用户管理")
|
||||||
public Mono<ServerResponse> updateUser(ServerRequest request) {
|
public Mono<ServerResponse> updateUser(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return request.bodyToMono(UserUpdateRequest.class)
|
|
||||||
.map(req -> {
|
return verifyAdminPassword(request)
|
||||||
boolean clearRole = Boolean.TRUE.equals(req.getClearRole()) ||
|
.flatMap(valid -> {
|
||||||
(req.getRoleId() == null && req.getClearRole() != null);
|
if (!valid) {
|
||||||
return UpdateUserCommand.of(
|
return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
id,
|
}
|
||||||
null,
|
return userService.findById(id)
|
||||||
null,
|
.flatMap(user -> {
|
||||||
req.getEmail(),
|
if ("admin".equals(user.getUsername())) {
|
||||||
req.getRoleId(),
|
return Mono.<ServerResponse>error(new RuntimeException("超级管理员不可编辑"));
|
||||||
req.getStatus(),
|
}
|
||||||
clearRole
|
return request.bodyToMono(UserUpdateRequest.class)
|
||||||
);
|
.map(req -> {
|
||||||
})
|
boolean clearRole = Boolean.TRUE.equals(req.getClearRole()) ||
|
||||||
.flatMap(userService::updateUser)
|
(req.getRoleId() == null && req.getClearRole() != null);
|
||||||
.flatMap(user -> ServerResponse.ok().bodyValue(user))
|
return UpdateUserCommand.of(
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
id, null, null, req.getEmail(),
|
||||||
|
req.getRoleId(), req.getStatus(), clearRole
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.flatMap(userService::updateUser)
|
||||||
|
.flatMap(updated -> ServerResponse.ok().bodyValue(updated));
|
||||||
|
})
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除用户", description = "物理删除用户")
|
@Operation(summary = "删除用户", description = "物理删除用户,需验证管理员密码,超级管理员不可删除")
|
||||||
@OperationLog(operation = "删除用户", module = "用户管理")
|
@OperationLog(operation = "删除用户", module = "用户管理")
|
||||||
public Mono<ServerResponse> deleteUser(ServerRequest request) {
|
public Mono<ServerResponse> deleteUser(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return userService.findById(id)
|
|
||||||
.flatMap(user -> userService.deleteUser(id)
|
return verifyAdminPassword(request)
|
||||||
.then(ServerResponse.noContent().build()))
|
.flatMap(valid -> {
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("User not found")))
|
if (!valid) {
|
||||||
|
return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
|
}
|
||||||
|
return userService.findById(id)
|
||||||
|
.flatMap(user -> {
|
||||||
|
if ("admin".equals(user.getUsername())) {
|
||||||
|
return Mono.<ServerResponse>error(new RuntimeException("超级管理员不可删除"));
|
||||||
|
}
|
||||||
|
return userService.deleteUser(id)
|
||||||
|
.then(ServerResponse.noContent().build());
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("User not found")));
|
||||||
|
})
|
||||||
.onErrorResume(RuntimeException.class, ex -> {
|
.onErrorResume(RuntimeException.class, ex -> {
|
||||||
if (ex.getMessage().contains("not found")) {
|
String msg = ex.getMessage();
|
||||||
|
if ("超级管理员不可删除".equals(msg) || "超级管理员不可编辑".equals(msg)) {
|
||||||
|
return ServerResponse.badRequest().bodyValue(msg);
|
||||||
|
}
|
||||||
|
if ("User not found".equals(msg)) {
|
||||||
return ServerResponse.notFound().build();
|
return ServerResponse.notFound().build();
|
||||||
}
|
}
|
||||||
return Mono.error(ex);
|
return Mono.error(ex);
|
||||||
@@ -258,16 +285,37 @@ public class SysUserHandler {
|
|||||||
.flatMap(exists -> ServerResponse.ok().bodyValue(exists));
|
.flatMap(exists -> ServerResponse.ok().bodyValue(exists));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "为用户分配角色", description = "为指定用户分配角色列表")
|
@Operation(summary = "为用户分配角色", description = "为指定用户分配角色列表,需验证管理员密码,超级管理员不可分配")
|
||||||
@OperationLog(operation = "分配角色", module = "用户管理")
|
@OperationLog(operation = "分配角色", module = "用户管理")
|
||||||
public Mono<ServerResponse> assignRoles(ServerRequest request) {
|
public Mono<ServerResponse> assignRoles(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return request.bodyToMono(AssignRolesRequest.class)
|
|
||||||
.flatMap(req -> userService.assignRolesToUser(id, req.getRoleIdsAsLong()))
|
return verifyAdminPassword(request)
|
||||||
.then(ServerResponse.ok().build())
|
.flatMap(valid -> {
|
||||||
.onErrorResume(error -> {
|
if (!valid) {
|
||||||
logger.error("分配角色失败", error);
|
return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
return ServerResponse.status(500).bodyValue("分配角色失败: " + error.getMessage());
|
}
|
||||||
|
return userService.findById(id)
|
||||||
|
.flatMap(user -> {
|
||||||
|
if ("admin".equals(user.getUsername())) {
|
||||||
|
return Mono.<ServerResponse>error(new RuntimeException("超级管理员不可被分配角色"));
|
||||||
|
}
|
||||||
|
return request.bodyToMono(AssignRolesRequest.class)
|
||||||
|
.flatMap(req -> userService.assignRolesToUser(id, req.getRoleIdsAsLong()))
|
||||||
|
.then(ServerResponse.ok().build());
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("User not found")));
|
||||||
|
})
|
||||||
|
.onErrorResume(RuntimeException.class, ex -> {
|
||||||
|
String msg = ex.getMessage();
|
||||||
|
if ("超级管理员不可被分配角色".equals(msg)) {
|
||||||
|
return ServerResponse.badRequest().bodyValue(msg);
|
||||||
|
}
|
||||||
|
if ("User not found".equals(msg)) {
|
||||||
|
return ServerResponse.notFound().build();
|
||||||
|
}
|
||||||
|
logger.error("分配角色失败", ex);
|
||||||
|
return ServerResponse.status(500).bodyValue("分配角色失败: " + msg);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,4 +325,16 @@ public class SysUserHandler {
|
|||||||
return ServerResponse.ok()
|
return ServerResponse.ok()
|
||||||
.body(userService.getUserRoles(id), cn.novalon.gym.manage.sys.core.domain.SysRole.class);
|
.body(userService.getUserRoles(id), cn.novalon.gym.manage.sys.core.domain.SysRole.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证管理员密码
|
||||||
|
*/
|
||||||
|
private Mono<Boolean> verifyAdminPassword(ServerRequest request) {
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
return userService.verifyPassword(adminId, adminPassword);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
VITE_API_BASE_URL=http://localhost:8084
|
||||||
|
VITE_APP_TITLE=CUIT Gym 管理系统
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
VITE_API_BASE_URL=/api
|
||||||
|
VITE_APP_TITLE=CUIT Gym 管理系统
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
.DS_Store
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
coverage
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
|
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
.eslintcache
|
||||||
|
|
||||||
|
# Cypress
|
||||||
|
/cypress/videos/
|
||||||
|
/cypress/screenshots/
|
||||||
|
|
||||||
|
# Vitest
|
||||||
|
__screenshots__/
|
||||||
|
|
||||||
|
# Vite
|
||||||
|
*.timestamp-*-*.mjs
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/prettierrc",
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 100
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"Vue.volar",
|
||||||
|
"esbenp.prettier-vscode"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# gym-manage-cuit
|
||||||
|
|
||||||
|
This template should help get you started developing with Vue 3 in Vite.
|
||||||
|
|
||||||
|
## Recommended IDE Setup
|
||||||
|
|
||||||
|
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
|
||||||
|
|
||||||
|
## Recommended Browser Setup
|
||||||
|
|
||||||
|
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
|
||||||
|
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
|
||||||
|
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
|
||||||
|
- Firefox:
|
||||||
|
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
|
||||||
|
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
|
||||||
|
|
||||||
|
## Type Support for `.vue` Imports in TS
|
||||||
|
|
||||||
|
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
|
||||||
|
|
||||||
|
## Customize configuration
|
||||||
|
|
||||||
|
See [Vite Configuration Reference](https://vite.dev/config/).
|
||||||
|
|
||||||
|
## Project Setup
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compile and Hot-Reload for Development
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Type-Check, Compile and Minify for Production
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" href="/favicon.ico" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>CUIT Gym 管理系统</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"name": "gym-manage-cuit",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "run-p type-check \"build-only {@}\" --",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"build-only": "vite build",
|
||||||
|
"type-check": "vue-tsc --build",
|
||||||
|
"format": "prettier --write --experimental-cli src/"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
|
"axios": "^1.18.1",
|
||||||
|
"dayjs": "^1.11.21",
|
||||||
|
"echarts": "^6.1.0",
|
||||||
|
"element-plus": "^2.14.2",
|
||||||
|
"pinia": "^3.0.4",
|
||||||
|
"vue": "^3.5.38",
|
||||||
|
"vue-router": "^5.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tsconfig/node24": "^24.0.4",
|
||||||
|
"@types/node": "^24.13.2",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.7",
|
||||||
|
"@vue/tsconfig": "^0.9.1",
|
||||||
|
"npm-run-all2": "^9.0.2",
|
||||||
|
"prettier": "3.8.4",
|
||||||
|
"sass-embedded": "^1.100.0",
|
||||||
|
"typescript": "~6.0.0",
|
||||||
|
"vite": "^8.0.16",
|
||||||
|
"vite-plugin-vue-devtools": "^8.1.2",
|
||||||
|
"vue-tsc": "^3.3.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^22.18.0 || >=24.12.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+2957
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,12 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<router-view />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
#app {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { post, get } from '@/api/request'
|
||||||
|
|
||||||
|
export interface LoginParams {
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthResponse {
|
||||||
|
token: string
|
||||||
|
userId: number
|
||||||
|
username: string
|
||||||
|
roles: string[]
|
||||||
|
permissions: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function login(params: LoginParams): Promise<AuthResponse> {
|
||||||
|
return post('/api/auth/login', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function register(data: any) {
|
||||||
|
return post('/api/auth/register', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function logout() {
|
||||||
|
return post('/api/auth/logout')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCurrentUser(): Promise<AuthResponse> {
|
||||||
|
return get('/api/auth/me')
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { get, post } from '@/api/request'
|
||||||
|
|
||||||
|
export function getSignInRecords(params: any) {
|
||||||
|
return get('/api/checkIn/records', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSignInRecordById(id: number) {
|
||||||
|
return get(`/api/checkIn/records/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSignInStatistics(params: any) {
|
||||||
|
return get('/api/checkIn/statistics', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDailySignInStats(params: any) {
|
||||||
|
return get('/api/checkIn/daily-stats', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllSignInRecords(params: any) {
|
||||||
|
return get('/api/checkIn/admin/records', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllSignInStatistics(params: any) {
|
||||||
|
return get('/api/checkIn/admin/statistics', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkIn(data: any) {
|
||||||
|
return post('/api/checkIn', data)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { get } from '@/api/request'
|
||||||
|
|
||||||
|
export function getStatisticsSummary(params?: any) {
|
||||||
|
return get('/api/datacount/summary', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMemberStatistics(params?: any) {
|
||||||
|
return get('/api/datacount/member', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBookingStatistics(params?: any) {
|
||||||
|
return get('/api/datacount/booking', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSignInStatistics(params?: any) {
|
||||||
|
return get('/api/datacount/signin', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getHistoricalStatistics(params?: any) {
|
||||||
|
return get('/api/datacount/history', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getStatsOverview() {
|
||||||
|
return get('/api/stats/overview')
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
import type { AxiosRequestConfig } from 'axios'
|
||||||
|
import instance from '@/api/request'
|
||||||
|
|
||||||
|
export function uploadImage(file: File) {
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', file)
|
||||||
|
return instance.post('/api/upload/image', formData, {
|
||||||
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
|
}).then((res) => res.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPresignedUrl(ossKey: string) {
|
||||||
|
return get<{ code: number; data: { presignedUrl: string } }>('/api/upload/presign', { key: ossKey })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGroupCoursesByPage(data: any) {
|
||||||
|
return post('/api/groupCourse/page', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllGroupCourses(includeDeleted?: boolean) {
|
||||||
|
return get('/api/groupCourse/list', { includeDeleted: includeDeleted ? 'true' : 'false' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGroupCourseById(id: number) {
|
||||||
|
return get(`/api/groupCourse/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGroupCourseDetailById(id: number) {
|
||||||
|
return get(`/api/groupCourse/${id}/detail`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createGroupCourse(data: any) {
|
||||||
|
return post('/api/groupCourse', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateGroupCourse(id: number, data: any, config?: AxiosRequestConfig) {
|
||||||
|
return put(`/api/groupCourse/${id}`, data, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteGroupCourse(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return del(`/api/groupCourse/${id}`, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreGroupCourse(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return post(`/api/groupCourse/${id}/restore`, null, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cancelGroupCourse(id: number) {
|
||||||
|
return post(`/api/groupCourse/${id}/cancel`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function searchGroupCourses(data: any) {
|
||||||
|
return post('/api/groupCourse/search', data)
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
import type { AxiosRequestConfig } from 'axios'
|
||||||
|
|
||||||
|
export function getAllRecommendations(params?: any) {
|
||||||
|
return get('/api/groupCourse/recommend/list', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllActiveRecommendations() {
|
||||||
|
return get('/api/groupCourse/recommend/active')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRecommendationById(id: number) {
|
||||||
|
return get(`/api/groupCourse/recommend/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRecommendation(data: any) {
|
||||||
|
return post('/api/groupCourse/recommend', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateRecommendation(id: number, data: any, config?: AxiosRequestConfig) {
|
||||||
|
return put(`/api/groupCourse/recommend/${id}`, data, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteRecommendation(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return del(`/api/groupCourse/recommend/${id}`, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function enableRecommendation(id: number) {
|
||||||
|
return post(`/api/groupCourse/recommend/${id}/enable`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function disableRecommendation(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return post(`/api/groupCourse/recommend/${id}/disable`, null, config)
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
import type { AxiosRequestConfig } from 'axios'
|
||||||
|
|
||||||
|
export function getAllGroupCourseTypes() {
|
||||||
|
return get('/api/groupCourse/types')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getGroupCourseTypeById(id: number) {
|
||||||
|
return get(`/api/groupCourse/types/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createGroupCourseType(data: any) {
|
||||||
|
return post('/api/groupCourse/types', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateGroupCourseType(id: number, data: any, config?: AxiosRequestConfig) {
|
||||||
|
return put(`/api/groupCourse/types/${id}`, data, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteGroupCourseType(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return del(`/api/groupCourse/types/${id}`, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCategories() {
|
||||||
|
return get('/api/groupCourse/types/categories')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllLabels() {
|
||||||
|
return get('/api/groupCourse/labels')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLabel(data: any) {
|
||||||
|
return post('/api/groupCourse/labels', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateLabel(id: number, data: any) {
|
||||||
|
return put(`/api/groupCourse/labels/${id}`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteLabel(id: number) {
|
||||||
|
return del(`/api/groupCourse/labels/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLabelsByTypeId(typeId: number) {
|
||||||
|
return get(`/api/groupCourse/types/${typeId}/labels`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addLabelsToType(typeId: number, labelIds: number[]) {
|
||||||
|
return post(`/api/groupCourse/types/${typeId}/labels`, { labelIds })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeLabelFromType(typeId: number, labelId: number) {
|
||||||
|
return del(`/api/groupCourse/types/${typeId}/labels/${labelId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearTypeLabels(typeId: number) {
|
||||||
|
return del(`/api/groupCourse/types/${typeId}/labels`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { get, post, put } from '@/api/request'
|
||||||
|
|
||||||
|
export function searchMembers(params: any) {
|
||||||
|
return get('/api/admin/members', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllMembers(params?: any) {
|
||||||
|
return get('/api/admin/members/all', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMemberDetail(id: number) {
|
||||||
|
return get(`/api/admin/member/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMember(id: number, data: any) {
|
||||||
|
return put(`/api/admin/member/${id}`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMemberPhone(id: number, data: any) {
|
||||||
|
return post(`/api/admin/member/${id}/phone`, data)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
|
||||||
|
export function getAllMemberCards() {
|
||||||
|
return get('/api/member-cards/active')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listMemberCards(params?: any) {
|
||||||
|
return get('/api/member-cards', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMemberCardById(id: number) {
|
||||||
|
return get(`/api/member-cards/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMemberCard(data: any) {
|
||||||
|
return post('/api/member-cards', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMemberCard(id: number, data: any, params?: any) {
|
||||||
|
return put(`/api/member-cards/${id}`, data, params ? { params } : undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteMemberCard(id: number, params?: any) {
|
||||||
|
return del(`/api/member-cards/${id}`, params ? { params } : undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMemberCardRecords(memberId: number) {
|
||||||
|
return get(`/api/member-card-records/my-cards/${memberId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function purchaseCard(data: any) {
|
||||||
|
return post('/api/member-card-records/purchase', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renewCard(recordId: number, data: any) {
|
||||||
|
return post(`/api/member-card-records/${recordId}/renew`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCard(recordId: number, data: any) {
|
||||||
|
return post(`/api/member-card-records/${recordId}/use`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function refundCard(recordId: number, data: any) {
|
||||||
|
return post(`/api/member-card-records/${recordId}/refund`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMemberCardTransactions(params: any) {
|
||||||
|
return get('/api/member-card-transactions', params)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
|
||||||
|
export function getAllMenus() {
|
||||||
|
return get('/api/menus')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMenuTree() {
|
||||||
|
return get('/api/menus/tree')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMenuById(id: number) {
|
||||||
|
return get(`/api/menus/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMenu(data: any) {
|
||||||
|
return post('/api/menus', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMenu(id: number, data: any) {
|
||||||
|
return put(`/api/menus/${id}`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteMenu(id: number) {
|
||||||
|
return del(`/api/menus/${id}`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { get } from '@/api/request'
|
||||||
|
|
||||||
|
export function getOperationLogsByPage(params: any) {
|
||||||
|
return get('/api/logs/operation/page', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllOperationLogs() {
|
||||||
|
return get('/api/logs/operation')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getOperationLogById(id: number) {
|
||||||
|
return get(`/api/logs/operation/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exportOperationLogs(params: any) {
|
||||||
|
return get('/api/logs/operation/export', params)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
import type { AxiosRequestConfig } from 'axios'
|
||||||
|
|
||||||
|
export function getRolesByPage(params: any) {
|
||||||
|
return get('/api/roles/page', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllRoles() {
|
||||||
|
return get('/api/roles')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRoleById(id: number) {
|
||||||
|
return get(`/api/roles/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRole(data: any) {
|
||||||
|
return post('/api/roles', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateRole(id: number, data: any, config?: AxiosRequestConfig) {
|
||||||
|
return put(`/api/roles/${id}`, data, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteRole(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return del(`/api/roles/${id}`, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkRoleName(name: string) {
|
||||||
|
return get('/api/roles/check-name', { name })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRolePermissions(id: number) {
|
||||||
|
return get(`/api/roles/${id}/permissions`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assignPermissionsToRole(id: number, permissionIds: number[], config?: AxiosRequestConfig) {
|
||||||
|
return post(`/api/roles/${id}/permissions`, { permissionIds }, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllPermissions() {
|
||||||
|
return get('/api/permissions')
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { get, post, put, del } from '@/api/request'
|
||||||
|
import type { AxiosRequestConfig } from 'axios'
|
||||||
|
|
||||||
|
export function getUsersByPage(params: any) {
|
||||||
|
return get('/api/users/page', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllUsers(params?: any) {
|
||||||
|
return get('/api/users', params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUserById(id: number) {
|
||||||
|
return get(`/api/users/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createUser(data: any) {
|
||||||
|
return post('/api/users', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateUser(id: number, data: any, config?: AxiosRequestConfig) {
|
||||||
|
return put(`/api/users/${id}`, data, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteUser(id: number, config?: AxiosRequestConfig) {
|
||||||
|
return del(`/api/users/${id}`, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function changePassword(id: number, data: any) {
|
||||||
|
return post(`/api/users/${id}/action/change-password`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUserRoles(id: number) {
|
||||||
|
return get(`/api/users/${id}/roles`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assignRoles(id: number, roleIds: number[], config?: AxiosRequestConfig) {
|
||||||
|
return post(`/api/users/${id}/roles`, { roleIds }, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkUsername(username: string) {
|
||||||
|
return get('/api/users/check/username', { username })
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
|
||||||
|
import { getToken, removeToken } from '@/utils/token'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
const instance: AxiosInstance = axios.create({
|
||||||
|
baseURL: '',
|
||||||
|
timeout: 15000,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
|
||||||
|
instance.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const token = getToken()
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
(error) => Promise.reject(error),
|
||||||
|
)
|
||||||
|
|
||||||
|
instance.interceptors.response.use(
|
||||||
|
(response: AxiosResponse) => {
|
||||||
|
const data = response.data
|
||||||
|
if (data?.code === 401) {
|
||||||
|
removeToken()
|
||||||
|
window.location.href = '/login'
|
||||||
|
return Promise.reject(new Error('登录已过期'))
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
removeToken()
|
||||||
|
window.location.href = '/login'
|
||||||
|
ElMessage.error('登录已过期,请重新登录')
|
||||||
|
} else {
|
||||||
|
const msg = error.response?.data?.message || error.message || '请求失败'
|
||||||
|
ElMessage.error(msg)
|
||||||
|
}
|
||||||
|
return Promise.reject(error)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
export function get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
|
||||||
|
return instance.get(url, { params, ...config }).then((res) => res.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
|
||||||
|
return instance.post(url, data, config).then((res) => res.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
|
||||||
|
return instance.put(url, data, config).then((res) => res.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function del<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
||||||
|
return instance.delete(url, config).then((res) => res.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function download(url: string, params?: any, filename?: string): Promise<void> {
|
||||||
|
return instance
|
||||||
|
.get(url, { params, responseType: 'blob' })
|
||||||
|
.then((res) => {
|
||||||
|
const blob = new Blob([res.data])
|
||||||
|
const link = document.createElement('a')
|
||||||
|
link.href = URL.createObjectURL(blob)
|
||||||
|
link.download = filename || 'export.xlsx'
|
||||||
|
link.click()
|
||||||
|
URL.revokeObjectURL(link.href)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export default instance
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
:root {
|
||||||
|
--color-primary: #1890ff;
|
||||||
|
--color-success: #52c41a;
|
||||||
|
--color-warning: #faad14;
|
||||||
|
--color-danger: #ff4d4f;
|
||||||
|
--color-info: #909399;
|
||||||
|
--bg-base: #f0f2f5;
|
||||||
|
--bg-sidebar: #001529;
|
||||||
|
--bg-header: #fff;
|
||||||
|
--text-primary: #303133;
|
||||||
|
--text-regular: #606266;
|
||||||
|
--text-secondary: #909399;
|
||||||
|
--border-base: #dcdfe6;
|
||||||
|
--sidebar-width: 220px;
|
||||||
|
--header-height: 56px;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body, #app {
|
||||||
|
height: 100%;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
color: var(--text-primary);
|
||||||
|
background: var(--bg-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: var(--color-primary);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-container {
|
||||||
|
padding: 16px;
|
||||||
|
height: 100%;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-card {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flex-between {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-right {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mb-16 {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mr-8 {
|
||||||
|
margin-right: 8px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import type { Directive, DirectiveBinding } from 'vue'
|
||||||
|
import { hasPermission, hasAnyPermission } from '@/utils/token'
|
||||||
|
|
||||||
|
export const permission: Directive = {
|
||||||
|
mounted(el: HTMLElement, binding: DirectiveBinding) {
|
||||||
|
const { value } = binding
|
||||||
|
if (!value) return
|
||||||
|
|
||||||
|
let allowed = false
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
allowed = hasAnyPermission(...value)
|
||||||
|
} else {
|
||||||
|
allowed = hasPermission(String(value))
|
||||||
|
}
|
||||||
|
if (!allowed) {
|
||||||
|
el.style.display = 'none'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export const permissionDisabled: Directive = {
|
||||||
|
mounted(el: HTMLElement, binding: DirectiveBinding) {
|
||||||
|
const { value } = binding
|
||||||
|
if (!value) return
|
||||||
|
|
||||||
|
let allowed = false
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
allowed = hasAnyPermission(...value)
|
||||||
|
} else {
|
||||||
|
allowed = hasPermission(String(value))
|
||||||
|
}
|
||||||
|
if (!allowed) {
|
||||||
|
el.setAttribute('disabled', 'true')
|
||||||
|
el.classList.add('is-disabled')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useAppStore } from '@/stores/app'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
|
||||||
|
const appStore = useAppStore()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const route = useRoute()
|
||||||
|
|
||||||
|
function getPageTitle() {
|
||||||
|
return route.meta?.title as string || '管理后台'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="header-container">
|
||||||
|
<div class="header-left">
|
||||||
|
<el-icon class="collapse-btn" @click="appStore.toggleCollapsed" :size="20">
|
||||||
|
<component :is="appStore.collapsed ? 'Expand' : 'Fold'" />
|
||||||
|
</el-icon>
|
||||||
|
<span class="page-title">{{ getPageTitle() }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="header-right">
|
||||||
|
<span class="username">{{ userStore.user?.username }}</span>
|
||||||
|
<el-dropdown trigger="click">
|
||||||
|
<el-avatar :size="32" icon="UserFilled" style="cursor: pointer; margin-left: 12px;" />
|
||||||
|
<template #dropdown>
|
||||||
|
<el-dropdown-menu>
|
||||||
|
<el-dropdown-item @click="userStore.logout">退出登录</el-dropdown-item>
|
||||||
|
</el-dropdown-menu>
|
||||||
|
</template>
|
||||||
|
</el-dropdown>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.header-container {
|
||||||
|
height: var(--header-height);
|
||||||
|
background: var(--bg-header);
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0 20px;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||||
|
z-index: 10;
|
||||||
|
}
|
||||||
|
.header-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.collapse-btn {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.collapse-btn:hover {
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
.page-title {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.header-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.username {
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text-regular);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { useAppStore } from '@/stores/app'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { usePermissionStore, type MenuItem } from '@/stores/permission'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const appStore = useAppStore()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const permStore = usePermissionStore()
|
||||||
|
|
||||||
|
const collapsed = computed(() => appStore.collapsed)
|
||||||
|
|
||||||
|
const menus = computed(() => permStore.menus)
|
||||||
|
|
||||||
|
const activeMenu = ref(route.path)
|
||||||
|
|
||||||
|
watch(() => route.path, (val) => {
|
||||||
|
activeMenu.value = val
|
||||||
|
})
|
||||||
|
|
||||||
|
function handleSelect(path: string) {
|
||||||
|
router.push(path)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="sidebar-container" :class="{ collapsed }">
|
||||||
|
<div class="logo">
|
||||||
|
<span v-if="!collapsed" class="logo-text">CUIT Gym</span>
|
||||||
|
<span v-else class="logo-text-mini">CG</span>
|
||||||
|
</div>
|
||||||
|
<el-menu
|
||||||
|
:default-active="activeMenu"
|
||||||
|
:collapse="collapsed"
|
||||||
|
background-color="#001529"
|
||||||
|
text-color="#ffffffb3"
|
||||||
|
active-text-color="#fff"
|
||||||
|
@select="handleSelect"
|
||||||
|
>
|
||||||
|
<template v-for="menu in menus" :key="menu.path">
|
||||||
|
<el-sub-menu v-if="menu.children?.length" :index="menu.path">
|
||||||
|
<template #title>
|
||||||
|
<el-icon><component :is="menu.meta.icon" /></el-icon>
|
||||||
|
<span>{{ menu.meta.title }}</span>
|
||||||
|
</template>
|
||||||
|
<el-menu-item
|
||||||
|
v-for="child in menu.children"
|
||||||
|
:key="child.path"
|
||||||
|
:index="child.path"
|
||||||
|
>
|
||||||
|
<el-icon><component :is="child.meta.icon" /></el-icon>
|
||||||
|
<span>{{ child.meta.title }}</span>
|
||||||
|
</el-menu-item>
|
||||||
|
</el-sub-menu>
|
||||||
|
<el-menu-item v-else :index="menu.path">
|
||||||
|
<el-icon><component :is="menu.meta.icon" /></el-icon>
|
||||||
|
<span>{{ menu.meta.title }}</span>
|
||||||
|
</el-menu-item>
|
||||||
|
</template>
|
||||||
|
</el-menu>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.sidebar-container {
|
||||||
|
width: var(--sidebar-width, 220px);
|
||||||
|
height: 100vh;
|
||||||
|
background: #001529;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
transition: width 0.3s;
|
||||||
|
}
|
||||||
|
.sidebar-container.collapsed {
|
||||||
|
width: 64px;
|
||||||
|
}
|
||||||
|
.logo {
|
||||||
|
height: 64px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: #002140;
|
||||||
|
}
|
||||||
|
.logo-text {
|
||||||
|
color: #fff;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 700;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.logo-text-mini {
|
||||||
|
color: #fff;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
:deep(.el-menu) {
|
||||||
|
border-right: none;
|
||||||
|
}
|
||||||
|
:deep(.el-menu-item.is-active) {
|
||||||
|
background-color: var(--color-primary, #1890ff) !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import Sidebar from './Sidebar.vue'
|
||||||
|
import Header from './Header.vue'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="layout-container">
|
||||||
|
<Sidebar />
|
||||||
|
<div class="layout-right">
|
||||||
|
<Header />
|
||||||
|
<div class="layout-content">
|
||||||
|
<router-view />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.layout-container {
|
||||||
|
display: flex;
|
||||||
|
height: 100%;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.layout-right {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.layout-content {
|
||||||
|
flex: 1;
|
||||||
|
overflow: auto;
|
||||||
|
padding: 16px;
|
||||||
|
background: var(--bg-base);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
import './assets/styles/global.scss'
|
||||||
|
import { permission, permissionDisabled } from './directives/permission'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
|
||||||
|
app.use(createPinia())
|
||||||
|
app.use(router)
|
||||||
|
app.use(ElementPlus, { size: 'default' })
|
||||||
|
|
||||||
|
app.directive('permission', permission)
|
||||||
|
app.directive('permission-disabled', permissionDisabled)
|
||||||
|
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import routes from './routes'
|
||||||
|
import { getToken } from '@/utils/token'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { usePermissionStore } from '@/stores/permission'
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
|
routes,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 权限码到路由路径的映射
|
||||||
|
const permRouteMap: Record<string, string> = {
|
||||||
|
'business:member:view': '/member/list',
|
||||||
|
'business:memberCard:view': '/member/card',
|
||||||
|
'business:groupCourse:view': '/groupCourse/list',
|
||||||
|
'business:groupCourseType:view': '/groupCourse/type',
|
||||||
|
'business:groupCourseRecommend:view': '/groupCourse/recommend',
|
||||||
|
'business:checkIn:view': '/checkIn',
|
||||||
|
'business:dataCount:view': '/datacount',
|
||||||
|
'system:log:view': '/operationLog',
|
||||||
|
'system:user:view': '/system/account',
|
||||||
|
'system:role:view': '/system/role',
|
||||||
|
'system:dict:view': '/system/dict',
|
||||||
|
}
|
||||||
|
|
||||||
|
let permissionFetched = false
|
||||||
|
|
||||||
|
router.beforeEach(async (to, _from, next) => {
|
||||||
|
const token = getToken()
|
||||||
|
|
||||||
|
// 登录页:已登录则跳转仪表盘
|
||||||
|
if (to.path === '/login') {
|
||||||
|
if (token) {
|
||||||
|
next('/dashboard')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 未登录则跳转登录
|
||||||
|
if (!token) {
|
||||||
|
next('/login')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const permStore = usePermissionStore()
|
||||||
|
|
||||||
|
// 首次进入时拉取权限并生成路由
|
||||||
|
if (!permissionFetched) {
|
||||||
|
try {
|
||||||
|
await userStore.fetchCurrentUser()
|
||||||
|
permissionFetched = true
|
||||||
|
} catch {
|
||||||
|
next('/login')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 仪表盘无需权限检查
|
||||||
|
if (to.path === '/dashboard') {
|
||||||
|
next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查找该路径需要的权限
|
||||||
|
const requiredPerm = Object.entries(permRouteMap).find(([, path]) => path === to.path)?.[0]
|
||||||
|
|
||||||
|
if (requiredPerm && !userStore.hasPermission(requiredPerm)) {
|
||||||
|
next('/dashboard')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import type { RouteRecordRaw } from 'vue-router'
|
||||||
|
import Layout from '@/layout/index.vue'
|
||||||
|
|
||||||
|
const routes: RouteRecordRaw[] = [
|
||||||
|
{
|
||||||
|
path: '/login',
|
||||||
|
name: 'Login',
|
||||||
|
component: () => import('@/views/login/index.vue'),
|
||||||
|
meta: { title: '登录', hidden: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
component: Layout,
|
||||||
|
redirect: '/dashboard',
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: 'dashboard',
|
||||||
|
name: 'Dashboard',
|
||||||
|
component: () => import('@/views/dashboard/index.vue'),
|
||||||
|
meta: { title: '仪表盘', icon: 'Odometer' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'member/list',
|
||||||
|
name: 'MemberList',
|
||||||
|
component: () => import('@/views/member/index.vue'),
|
||||||
|
meta: { title: '会员管理', icon: 'User' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'member/card',
|
||||||
|
name: 'MemberCard',
|
||||||
|
component: () => import('@/views/memberCard/index.vue'),
|
||||||
|
meta: { title: '会员卡管理', icon: 'CreditCard' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'checkIn',
|
||||||
|
name: 'CheckIn',
|
||||||
|
component: () => import('@/views/checkIn/index.vue'),
|
||||||
|
meta: { title: '签到明细', icon: 'Checked' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'groupCourse/list',
|
||||||
|
name: 'GroupCourseList',
|
||||||
|
component: () => import('@/views/groupCourse/index.vue'),
|
||||||
|
meta: { title: '团课管理', icon: 'Calendar' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'groupCourse/type',
|
||||||
|
name: 'GroupCourseType',
|
||||||
|
component: () => import('@/views/groupCourseType/index.vue'),
|
||||||
|
meta: { title: '类型管理', icon: 'SetUp' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'groupCourse/recommend',
|
||||||
|
name: 'GroupCourseRecommend',
|
||||||
|
component: () => import('@/views/groupCourseRecommend/index.vue'),
|
||||||
|
meta: { title: '推荐团课', icon: 'Star' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'datacount',
|
||||||
|
name: 'DataCount',
|
||||||
|
component: () => import('@/views/datacount/index.vue'),
|
||||||
|
meta: { title: '数据报表', icon: 'DataAnalysis' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'operationLog',
|
||||||
|
name: 'OperationLog',
|
||||||
|
component: () => import('@/views/operationLog/index.vue'),
|
||||||
|
meta: { title: '操作日志', icon: 'Document' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'system/account',
|
||||||
|
name: 'Account',
|
||||||
|
component: () => import('@/views/account/index.vue'),
|
||||||
|
meta: { title: '账号管理', icon: 'Avatar' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'system/role',
|
||||||
|
name: 'Role',
|
||||||
|
component: () => import('@/views/role/index.vue'),
|
||||||
|
meta: { title: '角色管理', icon: 'UserFilled' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'system/dict',
|
||||||
|
name: 'Dict',
|
||||||
|
component: () => import('@/views/dict/index.vue'),
|
||||||
|
meta: { title: '字典管理', icon: 'Notebook' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export default routes
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export const useAppStore = defineStore('app', () => {
|
||||||
|
const collapsed = ref(false)
|
||||||
|
const title = ref('CUIT Gym 管理系统')
|
||||||
|
|
||||||
|
function toggleCollapsed() {
|
||||||
|
collapsed.value = !collapsed.value
|
||||||
|
}
|
||||||
|
|
||||||
|
return { collapsed, title, toggleCollapsed }
|
||||||
|
})
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
|
||||||
|
export const useCounterStore = defineStore('counter', () => {
|
||||||
|
const count = ref(0)
|
||||||
|
const doubleCount = computed(() => count.value * 2)
|
||||||
|
function increment() {
|
||||||
|
count.value++
|
||||||
|
}
|
||||||
|
|
||||||
|
return { count, doubleCount, increment }
|
||||||
|
})
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { hasPermission } from '@/utils/token'
|
||||||
|
|
||||||
|
export interface MenuItem {
|
||||||
|
path: string
|
||||||
|
name: string
|
||||||
|
meta: {
|
||||||
|
title: string
|
||||||
|
icon: string
|
||||||
|
permission?: string
|
||||||
|
hidden?: boolean
|
||||||
|
}
|
||||||
|
children?: MenuItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const allMenus: MenuItem[] = [
|
||||||
|
{
|
||||||
|
path: '/dashboard',
|
||||||
|
name: 'Dashboard',
|
||||||
|
meta: { title: '仪表盘', icon: 'Odometer' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/member',
|
||||||
|
name: 'member',
|
||||||
|
meta: { title: '会员管理', icon: 'User', permission: 'business:member:view' },
|
||||||
|
children: [
|
||||||
|
{ path: '/member/list', name: 'MemberList', meta: { title: '会员列表', icon: 'List', permission: 'business:member:view' } },
|
||||||
|
{ path: '/member/card', name: 'MemberCard', meta: { title: '会员卡管理', icon: 'CreditCard', permission: 'business:memberCard:view' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/groupCourse',
|
||||||
|
name: 'groupCourse',
|
||||||
|
meta: { title: '团课管理', icon: 'Calendar', permission: 'business:groupCourse:view' },
|
||||||
|
children: [
|
||||||
|
{ path: '/groupCourse/list', name: 'GroupCourseList', meta: { title: '团课列表', icon: 'List', permission: 'business:groupCourse:view' } },
|
||||||
|
{ path: '/groupCourse/type', name: 'GroupCourseType', meta: { title: '类型管理', icon: 'SetUp', permission: 'business:groupCourseType:view' } },
|
||||||
|
{ path: '/groupCourse/recommend', name: 'GroupCourseRecommend', meta: { title: '推荐管理', icon: 'Star', permission: 'business:groupCourseRecommend:view' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/checkIn',
|
||||||
|
name: 'CheckIn',
|
||||||
|
meta: { title: '签到明细', icon: 'Checked', permission: 'business:checkIn:view' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/datacount',
|
||||||
|
name: 'DataCount',
|
||||||
|
meta: { title: '数据报表', icon: 'DataAnalysis', permission: 'business:dataCount:view' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/operationLog',
|
||||||
|
name: 'OperationLog',
|
||||||
|
meta: { title: '操作日志', icon: 'Document', permission: 'system:log:view' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/system',
|
||||||
|
name: 'system',
|
||||||
|
meta: { title: '系统管理', icon: 'Setting' },
|
||||||
|
children: [
|
||||||
|
{ path: '/system/account', name: 'Account', meta: { title: '账号管理', icon: 'Avatar', permission: 'system:user:view' } },
|
||||||
|
{ path: '/system/role', name: 'Role', meta: { title: '角色管理', icon: 'UserFilled', permission: 'system:role:view' } },
|
||||||
|
{ path: '/system/dict', name: 'Dict', meta: { title: '字典管理', icon: 'Notebook', permission: 'system:dict:view' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
function filterMenus(menus: MenuItem[]): MenuItem[] {
|
||||||
|
return menus
|
||||||
|
.map(menu => {
|
||||||
|
const children = menu.children ? filterMenus(menu.children) : undefined
|
||||||
|
const hasChildren = children && children.length > 0
|
||||||
|
const hasPerm = !menu.meta.permission || hasPermission(menu.meta.permission)
|
||||||
|
if (hasPerm || hasChildren) {
|
||||||
|
return { ...menu, children: hasChildren ? children : menu.children }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
.filter(Boolean) as MenuItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const usePermissionStore = defineStore('permission', () => {
|
||||||
|
const menus = ref<MenuItem[]>([])
|
||||||
|
|
||||||
|
function generateRoutes() {
|
||||||
|
menus.value = filterMenus(allMenus)
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetRoutes() {
|
||||||
|
menus.value = []
|
||||||
|
}
|
||||||
|
|
||||||
|
return { menus, generateRoutes, resetRoutes }
|
||||||
|
})
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { login as apiLogin, getCurrentUser, type AuthResponse } from '@/api/modules/auth'
|
||||||
|
import { setToken, removeToken, setUserInfo, removeUserInfo, getUserInfo, setPermissions, removePermissions, setRoles, removeRoles, getPermissions } from '@/utils/token'
|
||||||
|
import { usePermissionStore } from '@/stores/permission'
|
||||||
|
import router from '@/router'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
const user = ref<{ id: number; username: string } | null>(getUserInfo())
|
||||||
|
const token = ref<string | null>(null)
|
||||||
|
const permissions = ref<string[]>(getPermissions())
|
||||||
|
|
||||||
|
async function login(params: { username: string; password: string }) {
|
||||||
|
const res: AuthResponse = await apiLogin(params)
|
||||||
|
token.value = res.token
|
||||||
|
user.value = { id: res.userId, username: res.username }
|
||||||
|
permissions.value = res.permissions || []
|
||||||
|
setToken(res.token)
|
||||||
|
setUserInfo(user.value)
|
||||||
|
setPermissions(res.permissions || [])
|
||||||
|
setRoles(res.roles || [])
|
||||||
|
usePermissionStore().generateRoutes()
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
function logout() {
|
||||||
|
token.value = null
|
||||||
|
user.value = null
|
||||||
|
permissions.value = []
|
||||||
|
removeToken()
|
||||||
|
removeUserInfo()
|
||||||
|
removePermissions()
|
||||||
|
removeRoles()
|
||||||
|
usePermissionStore().resetRoutes()
|
||||||
|
router.push('/login')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchCurrentUser() {
|
||||||
|
try {
|
||||||
|
const res = await getCurrentUser()
|
||||||
|
user.value = { id: res.userId, username: res.username }
|
||||||
|
permissions.value = res.permissions || []
|
||||||
|
setUserInfo(user.value)
|
||||||
|
setPermissions(res.permissions || [])
|
||||||
|
setRoles(res.roles || [])
|
||||||
|
usePermissionStore().generateRoutes()
|
||||||
|
} catch {
|
||||||
|
ElMessage.error('获取用户信息失败,请重新登录')
|
||||||
|
logout()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasPermission(code: string): boolean {
|
||||||
|
return permissions.value.includes(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasAnyPermission(...codes: string[]): boolean {
|
||||||
|
return codes.some(c => permissions.value.includes(c))
|
||||||
|
}
|
||||||
|
|
||||||
|
return { user, token, permissions, login, logout, fetchCurrentUser, hasPermission, hasAnyPermission }
|
||||||
|
})
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import dayjs from 'dayjs'
|
||||||
|
|
||||||
|
export function formatDate(date: string | Date, fmt = 'YYYY-MM-DD HH:mm:ss'): string {
|
||||||
|
return dayjs(date).format(fmt)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDateShort(date: string | Date): string {
|
||||||
|
return dayjs(date).format('YYYY-MM-DD')
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
const TOKEN_KEY = 'gym_admin_token'
|
||||||
|
const USER_KEY = 'gym_admin_user'
|
||||||
|
const PERMISSIONS_KEY = 'gym_admin_permissions'
|
||||||
|
const ROLES_KEY = 'gym_admin_roles'
|
||||||
|
|
||||||
|
export function getToken(): string | null {
|
||||||
|
return localStorage.getItem(TOKEN_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setToken(token: string): void {
|
||||||
|
localStorage.setItem(TOKEN_KEY, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeToken(): void {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUserInfo(): any {
|
||||||
|
const raw = localStorage.getItem(USER_KEY)
|
||||||
|
return raw ? JSON.parse(raw) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setUserInfo(user: any): void {
|
||||||
|
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeUserInfo(): void {
|
||||||
|
localStorage.removeItem(USER_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPermissions(): string[] {
|
||||||
|
const raw = localStorage.getItem(PERMISSIONS_KEY)
|
||||||
|
return raw ? JSON.parse(raw) : []
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setPermissions(perms: string[]): void {
|
||||||
|
localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(perms))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removePermissions(): void {
|
||||||
|
localStorage.removeItem(PERMISSIONS_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRoles(): string[] {
|
||||||
|
const raw = localStorage.getItem(ROLES_KEY)
|
||||||
|
return raw ? JSON.parse(raw) : []
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setRoles(roles: string[]): void {
|
||||||
|
localStorage.setItem(ROLES_KEY, JSON.stringify(roles))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeRoles(): void {
|
||||||
|
localStorage.removeItem(ROLES_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasPermission(code: string): boolean {
|
||||||
|
return getPermissions().includes(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasAnyPermission(...codes: string[]): boolean {
|
||||||
|
const perms = getPermissions()
|
||||||
|
return codes.some(c => perms.includes(c))
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted, computed } from 'vue'
|
||||||
|
import { getUsersByPage, createUser, updateUser, deleteUser, getUserRoles, assignRoles } from '@/api/modules/user'
|
||||||
|
import { getAllRoles } from '@/api/modules/role'
|
||||||
|
import { formatDateShort } from '@/utils/format'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<any[]>([])
|
||||||
|
const total = ref(0)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const roleVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const editId = ref<number | null>(null)
|
||||||
|
const allRoles = ref<any[]>([])
|
||||||
|
const selectedRoles = ref<number[]>([])
|
||||||
|
|
||||||
|
const isBuiltinAdmin = (row: any) => row?.username === 'admin'
|
||||||
|
|
||||||
|
const page = reactive({ page: 0, size: 10, sort: 'id', order: 'asc', keyword: '' })
|
||||||
|
const currentPage = computed({
|
||||||
|
get: () => page.page + 1,
|
||||||
|
set: (val: number) => { page.page = val - 1 }
|
||||||
|
})
|
||||||
|
const form = reactive({ username: '', password: '', email: '', nickname: '', phone: '', roles: [] as number[] })
|
||||||
|
|
||||||
|
const avatarColors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa541c']
|
||||||
|
const avatarColor = (name: string) => {
|
||||||
|
let hash = 0
|
||||||
|
for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash)
|
||||||
|
return avatarColors[Math.abs(hash) % avatarColors.length]
|
||||||
|
}
|
||||||
|
|
||||||
|
const maskEmail = (email: string | null | undefined): string => {
|
||||||
|
if (!email) return '-'
|
||||||
|
const at = email.indexOf('@')
|
||||||
|
if (at <= 1) return email
|
||||||
|
return email[0] + '***' + email.slice(at)
|
||||||
|
}
|
||||||
|
|
||||||
|
const maskPhone = (phone: string | null | undefined): string => {
|
||||||
|
if (!phone) return '-'
|
||||||
|
if (phone.length < 7) return phone
|
||||||
|
return phone.slice(0, 3) + '****' + phone.slice(-4)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await getUsersByPage(page)
|
||||||
|
if (res?.content) {
|
||||||
|
list.value = res.content; total.value = res.totalElements || 0
|
||||||
|
} else if (Array.isArray(res)) {
|
||||||
|
list.value = res; total.value = res.length
|
||||||
|
}
|
||||||
|
} catch { list.value = [] } finally { loading.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(row: any) {
|
||||||
|
if (isBuiltinAdmin(row)) {
|
||||||
|
ElMessage.warning('超级管理员不可删除')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认删除', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
}).catch(() => {})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await deleteUser(row.id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
fetchData()
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data || e?.message || '删除失败'
|
||||||
|
ElMessage.error(typeof msg === 'string' ? msg : '删除失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() { isEdit.value = false; dialogVisible.value = true }
|
||||||
|
function openEdit(row: any) { isEdit.value = true; editId.value = row.id; Object.assign(form, row); dialogVisible.value = true }
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
if (isEdit.value && isBuiltinAdmin(form)) {
|
||||||
|
ElMessage.warning('超级管理员不可编辑')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (isEdit.value) {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认编辑', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
}).catch(() => {})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await updateUser(editId.value!, { email: form.email, nickname: form.nickname, phone: form.phone }, { params: { adminPassword: pwd } })
|
||||||
|
} else {
|
||||||
|
await createUser(form)
|
||||||
|
}
|
||||||
|
ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
|
||||||
|
dialogVisible.value = false
|
||||||
|
fetchData()
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data || e?.message || '操作失败'
|
||||||
|
ElMessage.error(typeof msg === 'string' ? msg : '操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAssignRoles(row: any) {
|
||||||
|
if (isBuiltinAdmin(row)) {
|
||||||
|
ElMessage.warning('超级管理员不可被分配角色')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const roles = await getAllRoles()
|
||||||
|
allRoles.value = Array.isArray(roles) ? roles : []
|
||||||
|
try {
|
||||||
|
const userRoles = await getUserRoles(row.id)
|
||||||
|
selectedRoles.value = Array.isArray(userRoles) ? userRoles.map((r: any) => r.id) : []
|
||||||
|
} catch { selectedRoles.value = [] }
|
||||||
|
editId.value = row.id
|
||||||
|
roleVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAssignRoles() {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认分配角色', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
}).catch(() => {})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await assignRoles(editId.value!, selectedRoles.value, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('分配成功')
|
||||||
|
roleVisible.value = false
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data || e?.message || '分配失败'
|
||||||
|
ElMessage.error(typeof msg === 'string' ? msg : '分配失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => fetchData())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom:16px">账号管理</h2>
|
||||||
|
<el-card class="search-card">
|
||||||
|
<el-form inline>
|
||||||
|
<el-form-item label="关键词"><el-input v-model="page.keyword" placeholder="用户名/邮箱" clearable @keyup.enter="fetchData" /></el-form-item>
|
||||||
|
<el-form-item><el-button type="primary" @click="fetchData">查询</el-button></el-form-item>
|
||||||
|
<el-form-item><el-button type="primary" @click="openCreate" v-permission="'system:user:create'">新增用户</el-button></el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="list" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||||
|
<el-table-column label="用户" min-width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div style="display:flex;align-items:center;gap:10px">
|
||||||
|
<div
|
||||||
|
:style="{
|
||||||
|
width:'36px',height:'36px',borderRadius:'50%',
|
||||||
|
background: avatarColor(row.username),
|
||||||
|
color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',
|
||||||
|
fontSize:'14px',fontWeight:'600',flexShrink:0,
|
||||||
|
}"
|
||||||
|
>{{ row.username?.[0]?.toUpperCase() }}</div>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:2px">
|
||||||
|
<span style="font-weight:500;line-height:1.2">{{ row.username }}</span>
|
||||||
|
<span v-if="isBuiltinAdmin(row)" style="font-size:12px;color:#e6a23c;line-height:1.2">超级管理员</span>
|
||||||
|
</div>
|
||||||
|
<el-tag v-if="isBuiltinAdmin(row)" type="warning" size="small" effect="dark" style="margin-left:auto">内置</el-tag>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="nickname" label="昵称" width="120" />
|
||||||
|
<el-table-column label="邮箱" width="200">
|
||||||
|
<template #default="{ row }">{{ maskEmail(row.email) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="手机号" width="140">
|
||||||
|
<template #default="{ row }">{{ maskPhone(row.phone) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="80" align="center">
|
||||||
|
<template #default="{ row }"><el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">{{ row.status === 1 ? '启用' : '禁用' }}</el-tag></template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="创建时间" width="170" align="center">
|
||||||
|
<template #default="{ row }">{{ row.createdAt ? formatDateShort(row.createdAt) : '-' }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="260" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'system:user:edit'">编辑</el-button>
|
||||||
|
<el-button type="primary" link @click="openAssignRoles(row)" v-permission="'system:user:edit'">分配角色</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)" v-permission="'system:user:delete'">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div style="margin-top:16px;text-align:right">
|
||||||
|
<el-pagination v-model:current-page="currentPage" :page-size="page.size" :total="total" layout="prev,pager,next,total" @current-change="fetchData" />
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="500px" :close-on-click-modal="false">
|
||||||
|
<el-form :model="form" label-width="100px">
|
||||||
|
<el-form-item label="用户名"><el-input v-model="form.username" :disabled="isEdit" /></el-form-item>
|
||||||
|
<el-form-item v-if="!isEdit" label="密码"><el-input v-model="form.password" type="password" /></el-form-item>
|
||||||
|
<el-form-item label="邮箱"><el-input v-model="form.email" /></el-form-item>
|
||||||
|
<el-form-item label="昵称"><el-input v-model="form.nickname" /></el-form-item>
|
||||||
|
<el-form-item label="手机号"><el-input v-model="form.phone" /></el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<el-dialog v-model="roleVisible" title="分配角色" width="400px" :close-on-click-modal="false">
|
||||||
|
<el-checkbox-group v-model="selectedRoles">
|
||||||
|
<el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
|
||||||
|
</el-checkbox-group>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="roleVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleAssignRoles">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.search-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { getAllSignInRecords, getAllSignInStatistics } from '@/api/modules/checkIn'
|
||||||
|
import { formatDate } from '@/utils/format'
|
||||||
|
import { download } from '@/api/request'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<any[]>([])
|
||||||
|
const stats = ref<any>({})
|
||||||
|
|
||||||
|
const filters = reactive({
|
||||||
|
startDate: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
|
||||||
|
endDate: dayjs().format('YYYY-MM-DD'),
|
||||||
|
})
|
||||||
|
|
||||||
|
const sortMode = ref('timeDesc')
|
||||||
|
|
||||||
|
const sortOptions: { label: string; value: string; sortBy: string; sortOrder: string }[] = [
|
||||||
|
{ label: '签到时间 新→旧', value: 'timeDesc', sortBy: 'signInTime', sortOrder: 'desc' },
|
||||||
|
{ label: '签到时间 旧→新', value: 'timeAsc', sortBy: 'signInTime', sortOrder: 'asc' },
|
||||||
|
{ label: 'ID 升序', value: 'idAsc', sortBy: 'id', sortOrder: 'asc' },
|
||||||
|
{ label: 'ID 降序', value: 'idDesc', sortBy: 'id', sortOrder: 'desc' },
|
||||||
|
{ label: '会员姓名 A→Z', value: 'nameAsc', sortBy: 'memberName', sortOrder: 'asc' },
|
||||||
|
{ label: '会员姓名 Z→A', value: 'nameDesc', sortBy: 'memberName', sortOrder: 'desc' },
|
||||||
|
]
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const sortOpt = sortOptions.find((o) => o.value === sortMode.value)!
|
||||||
|
const res = await getAllSignInRecords({
|
||||||
|
startDate: filters.startDate,
|
||||||
|
endDate: filters.endDate,
|
||||||
|
sortBy: sortOpt.sortBy,
|
||||||
|
sortOrder: sortOpt.sortOrder,
|
||||||
|
})
|
||||||
|
if (res?.data) {
|
||||||
|
list.value = Array.isArray(res.data) ? res.data : []
|
||||||
|
}
|
||||||
|
const statsRes = await getAllSignInStatistics({
|
||||||
|
startDate: filters.startDate,
|
||||||
|
endDate: filters.endDate,
|
||||||
|
})
|
||||||
|
if (statsRes?.data) {
|
||||||
|
stats.value = statsRes.data
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
list.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleExport() {
|
||||||
|
await download('/api/checkIn/records/export', filters, '签到记录.csv')
|
||||||
|
}
|
||||||
|
|
||||||
|
function signInTypeLabel(type: string) {
|
||||||
|
const map: Record<string, string> = { QR_CODE: '扫码', MANUAL: '手动', FACE: '人脸' }
|
||||||
|
return map[type] || type || '-'
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { fetchData() })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom:16px">签到明细</h2>
|
||||||
|
<el-card class="search-card" shadow="never">
|
||||||
|
<el-form :model="filters" inline>
|
||||||
|
<el-form-item label="开始日期">
|
||||||
|
<el-date-picker v-model="filters.startDate" type="date" value-format="YYYY-MM-DD" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="结束日期">
|
||||||
|
<el-date-picker v-model="filters.endDate" type="date" value-format="YYYY-MM-DD" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="排序">
|
||||||
|
<el-select v-model="sortMode" style="width:180px">
|
||||||
|
<el-option v-for="opt in sortOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="fetchData">查询</el-button>
|
||||||
|
<el-button @click="handleExport">导出签到记录</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-row :gutter="16" style="margin-bottom:16px">
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#1890ff">{{ stats.totalCount ?? 0 }}</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px">签到总次数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#52c41a">{{ stats.successCount ?? 0 }}</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px">成功签到</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#e6a23c">
|
||||||
|
{{ stats.successRate != null ? stats.successRate.toFixed(1) + '%' : '0%' }}
|
||||||
|
</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px">签到成功率</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#722ed1">{{ stats.uniqueMemberCount ?? 0 }}</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px">活跃会员数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<el-card shadow="never">
|
||||||
|
<el-table :data="list" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||||
|
<el-table-column prop="memberName" label="会员姓名" width="120" />
|
||||||
|
<el-table-column label="签到时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.signInTime ? formatDate(row.signInTime) : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="签到方式" width="90" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag size="small">{{ signInTypeLabel(row.signInType) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="memberCardType" label="会员卡类型" width="130" show-overflow-tooltip />
|
||||||
|
<el-table-column label="状态" width="90" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.signInStatus === 'SUCCESS' ? 'success' : 'danger'" size="small">
|
||||||
|
{{ row.signInStatus === 'SUCCESS' ? '成功' : '失败' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="source" label="来源" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.source === 'MINI_PROGRAM' ? '小程序' : row.source === 'PC_BACKEND' ? '后台' : row.source || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="失败原因" min-width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.failReason || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div v-if="list.length === 0 && !loading" style="color:#909399;font-size:13px;text-align:center;padding:40px">
|
||||||
|
暂无签到记录
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.search-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted, nextTick } from 'vue'
|
||||||
|
import * as echarts from 'echarts'
|
||||||
|
import {
|
||||||
|
getMemberStatistics,
|
||||||
|
getBookingStatistics,
|
||||||
|
getSignInStatistics,
|
||||||
|
} from '@/api/modules/datacount'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
|
||||||
|
interface StatCard {
|
||||||
|
label: string
|
||||||
|
value: number | string
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const statCards = ref<StatCard[]>([
|
||||||
|
{ label: '会员总数', value: 0, color: '#1890ff' },
|
||||||
|
{ label: '今日新增', value: 0, color: '#52c41a' },
|
||||||
|
{ label: '今日签到', value: 0, color: '#722ed1' },
|
||||||
|
{ label: '今日预约', value: 0, color: '#faad14' },
|
||||||
|
])
|
||||||
|
|
||||||
|
const memberChartRef = ref()
|
||||||
|
const bookingChartRef = ref()
|
||||||
|
const signinChartRef = ref()
|
||||||
|
|
||||||
|
let memberChart: echarts.ECharts | null = null
|
||||||
|
let bookingChart: echarts.ECharts | null = null
|
||||||
|
let signinChart: echarts.ECharts | null = null
|
||||||
|
|
||||||
|
function buildDayLabels(days: number) {
|
||||||
|
const labels: string[] = []
|
||||||
|
for (let i = days - 1; i >= 0; i--) {
|
||||||
|
labels.push(dayjs().subtract(i, 'day').format('MM/DD'))
|
||||||
|
}
|
||||||
|
return labels
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDayRange(dayOffset: number) {
|
||||||
|
const d = dayjs().subtract(dayOffset, 'day')
|
||||||
|
return {
|
||||||
|
startTime: d.startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
|
||||||
|
endTime: d.endOf('day').format('YYYY-MM-DDTHH:mm:ss'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildChartOption(title: string, subtext: string, legendData: string[], seriesData: any[]) {
|
||||||
|
return {
|
||||||
|
title: {
|
||||||
|
text: title,
|
||||||
|
subtext,
|
||||||
|
left: 'center',
|
||||||
|
textStyle: { fontSize: 15, fontWeight: 600, color: '#303133' },
|
||||||
|
subtextStyle: { color: '#909399' },
|
||||||
|
},
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { data: legendData, bottom: 0 },
|
||||||
|
xAxis: { data: buildDayLabels(7) },
|
||||||
|
yAxis: { type: 'value', minInterval: 1 },
|
||||||
|
grid: { top: 72, bottom: 48, left: 52, right: 20 },
|
||||||
|
series: seriesData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
|
||||||
|
const newMemberData = new Array(7).fill(0)
|
||||||
|
const activeMemberData = new Array(7).fill(0)
|
||||||
|
const bookingData = new Array(7).fill(0)
|
||||||
|
const cancelData = new Array(7).fill(0)
|
||||||
|
const signinData = new Array(7).fill(0)
|
||||||
|
|
||||||
|
// 今日数据索引(6 = 今天)
|
||||||
|
const todayIdx = 6
|
||||||
|
|
||||||
|
try {
|
||||||
|
const promises: Promise<any>[] = []
|
||||||
|
for (let i = 0; i < 7; i++) {
|
||||||
|
const range = getDayRange(6 - i)
|
||||||
|
|
||||||
|
promises.push(
|
||||||
|
getMemberStatistics(range).then((res: any) => {
|
||||||
|
newMemberData[i] = res?.newMembers ?? 0
|
||||||
|
activeMemberData[i] = res?.activeMembers ?? 0
|
||||||
|
if (i === todayIdx) {
|
||||||
|
statCards.value[0].value = res?.totalMembers ?? 0
|
||||||
|
statCards.value[1].value = res?.newMembers ?? 0
|
||||||
|
}
|
||||||
|
}).catch(() => {}),
|
||||||
|
|
||||||
|
getBookingStatistics(range).then((res: any) => {
|
||||||
|
bookings[i] = res?.newBookings ?? 0
|
||||||
|
cancelData[i] = res?.cancelBookings ?? 0
|
||||||
|
if (i === todayIdx) {
|
||||||
|
statCards.value[3].value = res?.newBookings ?? 0
|
||||||
|
}
|
||||||
|
}).catch(() => {}),
|
||||||
|
|
||||||
|
getSignInStatistics(range).then((res: any) => {
|
||||||
|
signinData[i] = res?.totalSignIns ?? 0
|
||||||
|
if (i === todayIdx) {
|
||||||
|
statCards.value[2].value = res?.totalSignIns ?? 0
|
||||||
|
}
|
||||||
|
}).catch(() => {}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
await Promise.allSettled(promises)
|
||||||
|
} catch {
|
||||||
|
// fallback: empty data
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
setChartData(newMemberData, activeMemberData, bookingData, cancelData, signinData)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setChartData(
|
||||||
|
newMember: number[],
|
||||||
|
activeMember: number[],
|
||||||
|
bookings: number[],
|
||||||
|
cancels: number[],
|
||||||
|
signins: number[],
|
||||||
|
) {
|
||||||
|
if (!memberChart || !bookingChart || !signinChart) {
|
||||||
|
initCharts(newMember, activeMember, bookings, cancels, signins)
|
||||||
|
} else {
|
||||||
|
memberChart.setOption({
|
||||||
|
series: [
|
||||||
|
{ data: newMember },
|
||||||
|
{ data: activeMember },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
bookingChart.setOption({
|
||||||
|
series: [
|
||||||
|
{ data: bookings },
|
||||||
|
{ data: cancels },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
signinChart.setOption({
|
||||||
|
series: [{ data: signins }],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function initCharts(
|
||||||
|
newMember: number[],
|
||||||
|
activeMember: number[],
|
||||||
|
bookings: number[],
|
||||||
|
cancels: number[],
|
||||||
|
signins: number[],
|
||||||
|
) {
|
||||||
|
const memberOption = buildChartOption('会员趋势', '近7天新增与活跃会员', ['新增会员', '活跃会员'], [
|
||||||
|
{ name: '新增会员', type: 'bar', data: newMember, itemStyle: { borderRadius: 4 }, color: '#1890ff' },
|
||||||
|
{ name: '活跃会员', type: 'bar', data: activeMember, itemStyle: { borderRadius: 4 }, color: '#52c41a' },
|
||||||
|
] as any[])
|
||||||
|
|
||||||
|
const bookingOption = buildChartOption('预约趋势', '近7天预约与取消', ['预约数', '取消数'], [
|
||||||
|
{ name: '预约数', type: 'line', data: bookings, smooth: true, color: '#1890ff' },
|
||||||
|
{ name: '取消数', type: 'line', data: cancels, smooth: true, color: '#ff4d4f' },
|
||||||
|
] as any[])
|
||||||
|
|
||||||
|
const signinOption = buildChartOption('签到趋势', '近7天每日签到人数', ['签到人数'], [
|
||||||
|
{ name: '签到人数', type: 'line', data: signins, areaStyle: { opacity: 0.2 }, smooth: true, color: '#722ed1' },
|
||||||
|
] as any[])
|
||||||
|
|
||||||
|
nextTick(() => {
|
||||||
|
memberChart = echarts.init(memberChartRef.value)
|
||||||
|
memberChart.setOption(memberOption)
|
||||||
|
bookingChart = echarts.init(bookingChartRef.value)
|
||||||
|
bookingChart.setOption(bookingOption)
|
||||||
|
signinChart = echarts.init(signinChartRef.value)
|
||||||
|
signinChart.setOption(signinOption)
|
||||||
|
|
||||||
|
const onResize = () => {
|
||||||
|
memberChart?.resize()
|
||||||
|
bookingChart?.resize()
|
||||||
|
signinChart?.resize()
|
||||||
|
}
|
||||||
|
window.addEventListener('resize', onResize)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-loading="loading">
|
||||||
|
<h2 style="margin-bottom: 16px">仪表盘</h2>
|
||||||
|
|
||||||
|
<el-row :gutter="16" style="margin-bottom: 16px">
|
||||||
|
<el-col :span="6" v-for="card in statCards" :key="card.label">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align: center">
|
||||||
|
<div style="font-size: 28px; font-weight: bold" :style="{ color: card.color }">
|
||||||
|
{{ typeof card.value === 'number' ? card.value.toLocaleString() : card.value }}
|
||||||
|
</div>
|
||||||
|
<div style="color: var(--text-secondary); margin-top: 8px">{{ card.label }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<el-row :gutter="16" style="margin-bottom: 16px">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div ref="memberChartRef" style="height: 300px"></div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div ref="bookingChartRef" style="height: 300px"></div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<el-row :gutter="16">
|
||||||
|
<el-col :span="24">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div ref="signinChartRef" style="height: 300px"></div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted, nextTick, type Ref } from 'vue'
|
||||||
|
import {
|
||||||
|
getStatisticsSummary,
|
||||||
|
getMemberStatistics,
|
||||||
|
getBookingStatistics,
|
||||||
|
getSignInStatistics,
|
||||||
|
getHistoricalStatistics,
|
||||||
|
} from '@/api/modules/datacount'
|
||||||
|
import { download } from '@/api/request'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import * as echarts from 'echarts'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const summary = ref<any>({})
|
||||||
|
const memberStats = ref<any>({})
|
||||||
|
const bookingStats = ref<any>({})
|
||||||
|
const signInStats = ref<any>({})
|
||||||
|
const historyList = ref<any[]>([])
|
||||||
|
const chartRef: Ref<HTMLElement | null> = ref(null)
|
||||||
|
let chartInstance: echarts.ECharts | null = null
|
||||||
|
|
||||||
|
const filters = reactive({
|
||||||
|
startDate: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
|
||||||
|
endDate: dayjs().format('YYYY-MM-DD'),
|
||||||
|
periodType: 'DAY',
|
||||||
|
})
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const startTime = dayjs(filters.startDate).startOf('day').format('YYYY-MM-DDTHH:mm:ss')
|
||||||
|
const endTime = dayjs(filters.endDate).endOf('day').format('YYYY-MM-DDTHH:mm:ss')
|
||||||
|
const params = { periodType: filters.periodType, startTime, endTime }
|
||||||
|
|
||||||
|
const [s, m, b, si, h] = await Promise.all([
|
||||||
|
getStatisticsSummary(params),
|
||||||
|
getMemberStatistics(params),
|
||||||
|
getBookingStatistics(params),
|
||||||
|
getSignInStatistics(params),
|
||||||
|
getHistoricalStatistics(params),
|
||||||
|
])
|
||||||
|
summary.value = s || {}
|
||||||
|
memberStats.value = m || {}
|
||||||
|
bookingStats.value = b || {}
|
||||||
|
signInStats.value = si || {}
|
||||||
|
historyList.value = Array.isArray(h) ? h : []
|
||||||
|
} catch {
|
||||||
|
summary.value = {}
|
||||||
|
memberStats.value = {}
|
||||||
|
bookingStats.value = {}
|
||||||
|
signInStats.value = {}
|
||||||
|
historyList.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
await nextTick()
|
||||||
|
renderChart()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderChart() {
|
||||||
|
if (!chartRef.value) return
|
||||||
|
if (!chartInstance) {
|
||||||
|
chartInstance = echarts.init(chartRef.value)
|
||||||
|
}
|
||||||
|
const si = signInStats.value
|
||||||
|
const bk = bookingStats.value
|
||||||
|
|
||||||
|
chartInstance.setOption({
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: {
|
||||||
|
bottom: 0,
|
||||||
|
left: 'center',
|
||||||
|
itemGap: 16,
|
||||||
|
data: ['签到总次数', '成功签到', '预约数', '出席预约'],
|
||||||
|
},
|
||||||
|
grid: { left: 50, right: 20, top: 20, bottom: 50 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: ['本周期'],
|
||||||
|
},
|
||||||
|
yAxis: { type: 'value', minInterval: 1 },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
name: '签到总次数', type: 'bar', barWidth: 36,
|
||||||
|
data: [si.totalSignIns || 0],
|
||||||
|
itemStyle: { color: '#1890ff' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '成功签到', type: 'bar', barWidth: 36,
|
||||||
|
data: [si.successSignIns || 0],
|
||||||
|
itemStyle: { color: '#52c41a' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '预约数', type: 'bar', barWidth: 36,
|
||||||
|
data: [bk.newBookings || 0],
|
||||||
|
itemStyle: { color: '#faad14' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '出席预约', type: 'bar', barWidth: 36,
|
||||||
|
data: [bk.attendBookings || 0],
|
||||||
|
itemStyle: { color: '#722ed1' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleExport() {
|
||||||
|
try {
|
||||||
|
const startTime = dayjs(filters.startDate).startOf('day').format('YYYY-MM-DDTHH:mm:ss')
|
||||||
|
const endTime = dayjs(filters.endDate).endOf('day').format('YYYY-MM-DDTHH:mm:ss')
|
||||||
|
await download('/api/datacount/export', { periodType: filters.periodType, startTime, endTime }, '数据报表.xlsx')
|
||||||
|
ElMessage.success('导出成功')
|
||||||
|
} catch {
|
||||||
|
ElMessage.error('导出失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dateLabel(d: string | null) {
|
||||||
|
if (!d) return '-'
|
||||||
|
return dayjs(d).format('YYYY-MM-DD')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom:16px">数据报表</h2>
|
||||||
|
|
||||||
|
<!-- Filter -->
|
||||||
|
<el-card class="search-card" shadow="never">
|
||||||
|
<el-form :model="filters" inline>
|
||||||
|
<el-form-item label="开始日期">
|
||||||
|
<el-date-picker v-model="filters.startDate" type="date" value-format="YYYY-MM-DD" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="结束日期">
|
||||||
|
<el-date-picker v-model="filters.endDate" type="date" value-format="YYYY-MM-DD" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="统计周期">
|
||||||
|
<el-select v-model="filters.periodType" style="width:120px">
|
||||||
|
<el-option label="按日" value="DAY" />
|
||||||
|
<el-option label="按周" value="WEEK" />
|
||||||
|
<el-option label="按月" value="MONTH" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="fetchData">查询</el-button>
|
||||||
|
<el-button @click="handleExport">导出报表</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Summary Cards -->
|
||||||
|
<el-row :gutter="16" style="margin-bottom:16px">
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#1890ff">
|
||||||
|
{{ memberStats.totalMembers ?? 0 }}
|
||||||
|
</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px;margin-top:4px">会员总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#52c41a">
|
||||||
|
{{ memberStats.newMembers ?? 0 }}
|
||||||
|
</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px;margin-top:4px">新增会员</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#faad14">
|
||||||
|
{{ bookingStats.newBookings ?? 0 }}
|
||||||
|
</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px;margin-top:4px">预约总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align:center">
|
||||||
|
<div style="font-size:28px;font-weight:bold;color:#722ed1">
|
||||||
|
{{ signInStats.totalSignIns ?? 0 }}
|
||||||
|
</div>
|
||||||
|
<div style="color:var(--text-secondary);font-size:13px;margin-top:4px">签到总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Member detail row -->
|
||||||
|
<el-row :gutter="16" style="margin-bottom:16px">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card shadow="never">
|
||||||
|
<template #header><strong>会员统计</strong></template>
|
||||||
|
<el-descriptions :column="2" border size="small">
|
||||||
|
<el-descriptions-item label="累计会员">{{ memberStats.totalMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="新增会员">{{ memberStats.newMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="活跃会员">{{ memberStats.activeMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="签到会员">{{ memberStats.signInMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="预约会员">{{ memberStats.bookingMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="取消预约">{{ memberStats.cancelBookingMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card shadow="never">
|
||||||
|
<template #header><strong>预约统计</strong></template>
|
||||||
|
<el-descriptions :column="2" border size="small">
|
||||||
|
<el-descriptions-item label="预约数">{{ bookingStats.newBookings ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="取消预约">{{ bookingStats.cancelBookings ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="出席预约">{{ bookingStats.attendBookings ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="缺席预约">{{ bookingStats.absentBookings ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="出席率">{{ bookingStats.attendanceRate != null ? bookingStats.attendanceRate + '%' : '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="取消率">{{ bookingStats.cancelRate != null ? bookingStats.cancelRate + '%' : '-' }}</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- SignIn detail row -->
|
||||||
|
<el-row :gutter="16" style="margin-bottom:16px">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card shadow="never">
|
||||||
|
<template #header><strong>签到统计</strong></template>
|
||||||
|
<el-descriptions :column="2" border size="small">
|
||||||
|
<el-descriptions-item label="签到总数">{{ signInStats.totalSignIns ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="成功签到">{{ signInStats.successSignIns ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="失败签到">{{ signInStats.failedSignIns ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="成功率">{{ signInStats.successRate != null ? signInStats.successRate + '%' : '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="签到人数">{{ signInStats.signInMembers ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="扫码/手动/人脸">
|
||||||
|
{{ signInStats.qrCodeSignIns ?? 0 }} / {{ signInStats.manualSignIns ?? 0 }} / {{ signInStats.faceSignIns ?? 0 }}
|
||||||
|
</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card shadow="never">
|
||||||
|
<template #header><strong>数据趋势</strong></template>
|
||||||
|
<div ref="chartRef" style="width:100%;height:220px"></div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Historical data table -->
|
||||||
|
<el-card shadow="never">
|
||||||
|
<template #header><strong>历史统计</strong></template>
|
||||||
|
<el-table :data="historyList" v-loading="loading" stripe>
|
||||||
|
<el-table-column label="统计日期" width="170" align="center">
|
||||||
|
<template #default="{ row }">{{ dateLabel(row.statDate) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="统计类型" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag size="small" :type="row.statType === 'MEMBER' ? '' : row.statType === 'BOOKING' ? 'success' : 'warning'">
|
||||||
|
{{ row.statType === 'MEMBER' ? '会员' : row.statType === 'BOOKING' ? '预约' : row.statType === 'SIGN_IN' ? '签到' : row.statType }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="周期" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.periodType === 'DAY' ? '按日' : row.periodType === 'WEEK' ? '按周' : row.periodType === 'MONTH' ? '按月' : row.periodType || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="count" label="数量" width="100" align="center" />
|
||||||
|
<el-table-column prop="extraData" label="详细信息" min-width="160" show-overflow-tooltip />
|
||||||
|
</el-table>
|
||||||
|
<div v-if="historyList.length === 0 && !loading" style="color:#909399;font-size:13px;text-align:center;padding:40px">
|
||||||
|
暂无历史统计数据
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.search-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { get } from '@/api/request'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<any[]>([])
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await get('/api/dictionaries')
|
||||||
|
list.value = Array.isArray(res) ? res : []
|
||||||
|
} catch { list.value = [] } finally { loading.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => fetchData())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom:16px">字典管理</h2>
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="list" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="type" label="字典类型" width="160" />
|
||||||
|
<el-table-column prop="code" label="编码" width="160" />
|
||||||
|
<el-table-column prop="name" label="字典名称" width="160" />
|
||||||
|
<el-table-column prop="value" label="值" />
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,773 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, computed, onMounted, watch } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import {
|
||||||
|
getAllGroupCourses,
|
||||||
|
createGroupCourse,
|
||||||
|
updateGroupCourse,
|
||||||
|
deleteGroupCourse,
|
||||||
|
restoreGroupCourse,
|
||||||
|
uploadImage,
|
||||||
|
getPresignedUrl,
|
||||||
|
} from '@/api/modules/groupCourse'
|
||||||
|
import { getAllGroupCourseTypes } from '@/api/modules/groupCourseType'
|
||||||
|
import { formatDate } from '@/utils/format'
|
||||||
|
|
||||||
|
interface CourseItem {
|
||||||
|
id: number
|
||||||
|
courseName: string
|
||||||
|
coachId: number
|
||||||
|
courseType: number
|
||||||
|
startTime: string | null
|
||||||
|
endTime: string | null
|
||||||
|
maxMembers: number
|
||||||
|
currentMembers: number
|
||||||
|
status: number
|
||||||
|
location: string
|
||||||
|
coverImage: string | null
|
||||||
|
description: string
|
||||||
|
storedValueAmount: number
|
||||||
|
createdAt: string | null
|
||||||
|
updatedAt: string | null
|
||||||
|
deletedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- State ----
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<CourseItem[]>([])
|
||||||
|
const total = ref(0)
|
||||||
|
const typeMap = ref<Record<number, string>>({})
|
||||||
|
|
||||||
|
// stats (from full dataset)
|
||||||
|
const allCourses = ref<CourseItem[]>([])
|
||||||
|
const statsNonDeleted = ref({ total: 0, normal: 0, cancelled: 0, ended: 0, deleted: 0 })
|
||||||
|
const stats = computed(() => statsNonDeleted.value)
|
||||||
|
|
||||||
|
// filters
|
||||||
|
const keyword = ref('')
|
||||||
|
const typeFilter = ref<number | null>(null)
|
||||||
|
const statusFilter = ref<number | null>(null)
|
||||||
|
const dateRange = ref<[string, string] | null>(null)
|
||||||
|
const timePeriod = ref<string | null>(null)
|
||||||
|
|
||||||
|
// sorting
|
||||||
|
type SortMode = 'default' | 'priceAsc' | 'priceDesc' | 'remainingMost'
|
||||||
|
const sortMode = ref<SortMode>('default')
|
||||||
|
|
||||||
|
const currentPage = ref(0)
|
||||||
|
const pageSize = ref(10)
|
||||||
|
|
||||||
|
const displayPage = computed({
|
||||||
|
get: () => currentPage.value + 1,
|
||||||
|
set: (val: number) => {
|
||||||
|
currentPage.value = val - 1
|
||||||
|
applyPage()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// dialogs
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const adminPassword = ref('')
|
||||||
|
const pendingCoverFile = ref<File | null>(null)
|
||||||
|
const coverPreviewUrl = ref('')
|
||||||
|
|
||||||
|
const form = reactive({
|
||||||
|
id: 0,
|
||||||
|
courseName: '',
|
||||||
|
coachId: null as number | null,
|
||||||
|
courseType: null as number | null,
|
||||||
|
startTime: '',
|
||||||
|
endTime: '',
|
||||||
|
maxMembers: 20,
|
||||||
|
currentMembers: 0,
|
||||||
|
status: 0,
|
||||||
|
location: '',
|
||||||
|
coverImage: '',
|
||||||
|
description: '',
|
||||||
|
storedValueAmount: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const coverUrlMap = ref<Record<number, string>>({})
|
||||||
|
|
||||||
|
// ---- Helpers ----
|
||||||
|
const toNum = (v: any): number => Number(v)
|
||||||
|
const statusLabel = (s: any) => {
|
||||||
|
const map: Record<number, string> = { 0: '正常', 1: '已取消', 2: '已结束' }
|
||||||
|
return map[toNum(s)] ?? '未知'
|
||||||
|
}
|
||||||
|
const statusTagType = (s: any) => {
|
||||||
|
const map: Record<number, string> = { 0: 'success', 1: 'danger', 2: 'info' }
|
||||||
|
return map[toNum(s)] ?? 'info'
|
||||||
|
}
|
||||||
|
const isDeleted = (row: CourseItem) => row.deletedAt != null
|
||||||
|
|
||||||
|
// ---- Methods ----
|
||||||
|
async function fetchTypes() {
|
||||||
|
try {
|
||||||
|
const res: any = await getAllGroupCourseTypes()
|
||||||
|
const map: Record<number, string> = {}
|
||||||
|
if (Array.isArray(res)) {
|
||||||
|
res.forEach((t: any) => {
|
||||||
|
if (t.id != null && t.typeName) map[t.id] = t.typeName
|
||||||
|
})
|
||||||
|
}
|
||||||
|
typeMap.value = map
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchStats() {
|
||||||
|
try {
|
||||||
|
// 未删除的课程(用于统计)
|
||||||
|
const res: any = await getAllGroupCourses(false)
|
||||||
|
const courses: CourseItem[] = Array.isArray(res) ? res : []
|
||||||
|
statsNonDeleted.value = {
|
||||||
|
total: courses.length,
|
||||||
|
normal: courses.filter((m) => toNum(m.status) === 0).length,
|
||||||
|
cancelled: courses.filter((m) => toNum(m.status) === 1).length,
|
||||||
|
ended: courses.filter((m) => toNum(m.status) === 2).length,
|
||||||
|
deleted: 0,
|
||||||
|
}
|
||||||
|
// 同时获取已删除课程数
|
||||||
|
const allRes: any = await getAllGroupCourses(true)
|
||||||
|
const allCoursesData: CourseItem[] = Array.isArray(allRes) ? allRes : []
|
||||||
|
statsNonDeleted.value.deleted = allCoursesData.filter((m) => m.deletedAt != null).length
|
||||||
|
} catch {
|
||||||
|
statsNonDeleted.value = { total: 0, normal: 0, cancelled: 0, ended: 0, deleted: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchCoverUrls() {
|
||||||
|
const newMap: Record<number, string> = {}
|
||||||
|
for (const course of allCourses.value) {
|
||||||
|
if (course.coverImage) {
|
||||||
|
try {
|
||||||
|
const res = await getPresignedUrl(course.coverImage)
|
||||||
|
if (res.code === 200 && res.data?.presignedUrl) {
|
||||||
|
newMap[course.id] = res.data.presignedUrl
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore individual failures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
coverUrlMap.value = newMap
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadData() {
|
||||||
|
loading.value = true
|
||||||
|
await fetchStats()
|
||||||
|
// 根据筛选状态加载数据
|
||||||
|
if (statusFilter.value === 3) {
|
||||||
|
try {
|
||||||
|
const res: any = await getAllGroupCourses(true)
|
||||||
|
allCourses.value = (Array.isArray(res) ? res : []).filter((m: CourseItem) => m.deletedAt != null)
|
||||||
|
} catch {
|
||||||
|
allCourses.value = []
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const res: any = await getAllGroupCourses(false)
|
||||||
|
allCourses.value = Array.isArray(res) ? res : []
|
||||||
|
} catch {
|
||||||
|
allCourses.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await fetchCoverUrls()
|
||||||
|
loading.value = false
|
||||||
|
applyPage()
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFilters(): CourseItem[] {
|
||||||
|
let data = [...allCourses.value]
|
||||||
|
|
||||||
|
// keyword filter (course name fuzzy)
|
||||||
|
if (keyword.value) {
|
||||||
|
const kw = keyword.value.toLowerCase()
|
||||||
|
data = data.filter((item) =>
|
||||||
|
(item.courseName || '').toLowerCase().includes(kw)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// type filter
|
||||||
|
if (typeFilter.value != null) {
|
||||||
|
data = data.filter((item) => item.courseType === typeFilter.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// status filter(值 3 为"已删除",已在 loadData 数据源层处理,此处跳过)
|
||||||
|
if (statusFilter.value != null && statusFilter.value !== 3) {
|
||||||
|
data = data.filter((item) => toNum(item.status) === statusFilter.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// date range filter
|
||||||
|
if (dateRange.value) {
|
||||||
|
const [start, end] = dateRange.value
|
||||||
|
if (start) {
|
||||||
|
data = data.filter((item) => item.startTime && item.startTime >= `${start}T00:00:00`)
|
||||||
|
}
|
||||||
|
if (end) {
|
||||||
|
data = data.filter((item) => item.startTime && item.startTime <= `${end}T23:59:59`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// time period filter
|
||||||
|
if (timePeriod.value) {
|
||||||
|
data = data.filter((item) => {
|
||||||
|
if (!item.startTime) return false
|
||||||
|
const hour = new Date(item.startTime).getHours()
|
||||||
|
switch (timePeriod.value) {
|
||||||
|
case 'morning':
|
||||||
|
return hour >= 6 && hour < 12
|
||||||
|
case 'afternoon':
|
||||||
|
return hour >= 12 && hour < 18
|
||||||
|
case 'evening':
|
||||||
|
return hour >= 18
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// sorting
|
||||||
|
if (sortMode.value === 'priceAsc') {
|
||||||
|
data.sort((a, b) => (a.storedValueAmount ?? 0) - (b.storedValueAmount ?? 0))
|
||||||
|
} else if (sortMode.value === 'priceDesc') {
|
||||||
|
data.sort((a, b) => (b.storedValueAmount ?? 0) - (a.storedValueAmount ?? 0))
|
||||||
|
} else if (sortMode.value === 'remainingMost') {
|
||||||
|
data.sort((a, b) => {
|
||||||
|
const remainA = (a.maxMembers ?? 0) - (a.currentMembers ?? 0)
|
||||||
|
const remainB = (b.maxMembers ?? 0) - (b.currentMembers ?? 0)
|
||||||
|
return remainB - remainA
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// default: id descending
|
||||||
|
data.sort((a, b) => (b.id ?? 0) - (a.id ?? 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyPage() {
|
||||||
|
const filtered = applyFilters()
|
||||||
|
total.value = filtered.length
|
||||||
|
const start = currentPage.value * pageSize.value
|
||||||
|
list.value = filtered.slice(start, start + pageSize.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSearch() {
|
||||||
|
currentPage.value = 0
|
||||||
|
loadData()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFilters() {
|
||||||
|
const wasDeleted = statusFilter.value === 3
|
||||||
|
keyword.value = ''
|
||||||
|
typeFilter.value = null
|
||||||
|
statusFilter.value = null
|
||||||
|
dateRange.value = null
|
||||||
|
timePeriod.value = null
|
||||||
|
sortMode.value = 'default'
|
||||||
|
currentPage.value = 0
|
||||||
|
if (wasDeleted) {
|
||||||
|
loadData()
|
||||||
|
} else {
|
||||||
|
applyPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// watch sortMode to re-paginate
|
||||||
|
watch(sortMode, () => {
|
||||||
|
currentPage.value = 0
|
||||||
|
applyPage()
|
||||||
|
})
|
||||||
|
|
||||||
|
// 切换“已删除”筛选时重新加载数据
|
||||||
|
watch(statusFilter, (newVal, oldVal) => {
|
||||||
|
if (newVal === 3 || oldVal === 3) {
|
||||||
|
currentPage.value = 0
|
||||||
|
loadData()
|
||||||
|
} else {
|
||||||
|
currentPage.value = 0
|
||||||
|
applyPage()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---- Create / Edit ----
|
||||||
|
function openCreate() {
|
||||||
|
isEdit.value = false
|
||||||
|
adminPassword.value = ''
|
||||||
|
pendingCoverFile.value = null
|
||||||
|
coverPreviewUrl.value = ''
|
||||||
|
Object.assign(form, {
|
||||||
|
id: 0,
|
||||||
|
courseName: '',
|
||||||
|
coachId: null,
|
||||||
|
courseType: null,
|
||||||
|
startTime: '',
|
||||||
|
endTime: '',
|
||||||
|
maxMembers: 20,
|
||||||
|
currentMembers: 0,
|
||||||
|
status: 0,
|
||||||
|
location: '',
|
||||||
|
coverImage: '',
|
||||||
|
description: '',
|
||||||
|
storedValueAmount: 0,
|
||||||
|
})
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: CourseItem) {
|
||||||
|
isEdit.value = true
|
||||||
|
adminPassword.value = ''
|
||||||
|
pendingCoverFile.value = null
|
||||||
|
coverPreviewUrl.value = ''
|
||||||
|
form.id = row.id
|
||||||
|
form.courseName = row.courseName || ''
|
||||||
|
form.coachId = row.coachId ?? null
|
||||||
|
form.courseType = toNum(row.courseType)
|
||||||
|
form.maxMembers = row.maxMembers ?? 20
|
||||||
|
form.currentMembers = row.currentMembers ?? 0
|
||||||
|
form.status = toNum(row.status)
|
||||||
|
form.location = row.location || ''
|
||||||
|
form.coverImage = row.coverImage || ''
|
||||||
|
form.description = row.description || ''
|
||||||
|
form.storedValueAmount = row.storedValueAmount ?? 0
|
||||||
|
form.startTime = row.startTime ? formatDate(row.startTime, 'YYYY-MM-DD HH:mm:ss') : ''
|
||||||
|
form.endTime = row.endTime ? formatDate(row.endTime, 'YYYY-MM-DD HH:mm:ss') : ''
|
||||||
|
dialogVisible.value = true
|
||||||
|
// 如果有已有封面,获取预签名URL用于预览
|
||||||
|
if (form.coverImage) {
|
||||||
|
getPresignedUrl(form.coverImage).then((res) => {
|
||||||
|
if (res.code === 200 && res.data?.presignedUrl) {
|
||||||
|
coverPreviewUrl.value = res.data.presignedUrl
|
||||||
|
}
|
||||||
|
}).catch(() => {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onUploadChange(uploadFile: any) {
|
||||||
|
const rawFile = uploadFile?.raw || uploadFile
|
||||||
|
if (rawFile) {
|
||||||
|
pendingCoverFile.value = rawFile
|
||||||
|
if (coverPreviewUrl.value) URL.revokeObjectURL(coverPreviewUrl.value)
|
||||||
|
coverPreviewUrl.value = URL.createObjectURL(rawFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImgError(e: Event) {
|
||||||
|
const img = e.target as HTMLImageElement
|
||||||
|
img.style.display = 'none'
|
||||||
|
const fallback = img.nextElementSibling as HTMLElement | null
|
||||||
|
if (fallback) fallback.style.display = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDialogClosed() {
|
||||||
|
Object.assign(form, { startTime: '', endTime: '' })
|
||||||
|
adminPassword.value = ''
|
||||||
|
if (coverPreviewUrl.value) {
|
||||||
|
URL.revokeObjectURL(coverPreviewUrl.value)
|
||||||
|
coverPreviewUrl.value = ''
|
||||||
|
}
|
||||||
|
pendingCoverFile.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
const body: any = { ...form }
|
||||||
|
delete body.id
|
||||||
|
if (body.startTime) body.startTime = new Date(body.startTime).toISOString()
|
||||||
|
if (body.endTime) body.endTime = new Date(body.endTime).toISOString()
|
||||||
|
|
||||||
|
if (isEdit.value) {
|
||||||
|
if (!adminPassword.value) {
|
||||||
|
ElMessage.warning('请输入管理员密码')
|
||||||
|
saving.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// upload cover if user selected a new one
|
||||||
|
if (pendingCoverFile.value) {
|
||||||
|
const res: any = await uploadImage(pendingCoverFile.value)
|
||||||
|
if (res.code === 200) {
|
||||||
|
body.coverImage = res.data.ossKey
|
||||||
|
} else {
|
||||||
|
ElMessage.error(res.message || '封面上传失败')
|
||||||
|
saving.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await updateGroupCourse(form.id, body, { params: { adminPassword: adminPassword.value } })
|
||||||
|
} else {
|
||||||
|
if (pendingCoverFile.value) {
|
||||||
|
const res: any = await uploadImage(pendingCoverFile.value)
|
||||||
|
if (res.code === 200) {
|
||||||
|
body.coverImage = res.data.ossKey
|
||||||
|
} else {
|
||||||
|
ElMessage.error(res.message || '封面上传失败')
|
||||||
|
saving.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await createGroupCourse(body)
|
||||||
|
}
|
||||||
|
ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
|
||||||
|
dialogVisible.value = false
|
||||||
|
loadData()
|
||||||
|
} catch {
|
||||||
|
ElMessage.error('操作失败')
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(row: CourseItem) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除团课"${row.courseName}"吗?`, '确认删除', { type: 'warning' })
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认删除', '管理员验证', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确认删除',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
})
|
||||||
|
if (!pwd) return
|
||||||
|
await deleteGroupCourse(row.id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('已删除')
|
||||||
|
loadData()
|
||||||
|
} catch (e: any) {
|
||||||
|
if (e !== 'cancel' && e?.message !== 'cancel') {
|
||||||
|
// error already shown by axios interceptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRestore(row: CourseItem) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要恢复团课"${row.courseName}"为已取消状态吗?`, '确认恢复', { type: 'info' })
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认恢复', '管理员验证', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确认恢复',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
})
|
||||||
|
if (!pwd) return
|
||||||
|
await restoreGroupCourse(row.id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('已恢复')
|
||||||
|
loadData()
|
||||||
|
} catch (e: any) {
|
||||||
|
if (e !== 'cancel' && e?.message !== 'cancel') {
|
||||||
|
// error already shown by axios interceptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchTypes()
|
||||||
|
loadData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom: 16px">团课列表</h2>
|
||||||
|
|
||||||
|
<!-- Stats -->
|
||||||
|
<el-row :gutter="16" style="margin-bottom: 16px">
|
||||||
|
<el-col :span="4" v-for="s in [
|
||||||
|
{ label: '团课总数', value: stats.total, color: '#1890ff' },
|
||||||
|
{ label: '正常进行', value: stats.normal, color: '#52c41a' },
|
||||||
|
{ label: '已取消', value: stats.cancelled, color: '#ff4d4f' },
|
||||||
|
{ label: '已结束', value: stats.ended, color: '#909399' },
|
||||||
|
{ label: '已删除', value: stats.deleted, color: '#fa8c16' },
|
||||||
|
]" :key="s.label">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align: center">
|
||||||
|
<div style="font-size: 26px; font-weight: bold" :style="{ color: s.color }">
|
||||||
|
{{ s.value }}
|
||||||
|
</div>
|
||||||
|
<div style="color: var(--text-secondary); margin-top: 4px; font-size: 13px">{{ s.label }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Search -->
|
||||||
|
<el-card class="search-card">
|
||||||
|
<el-form inline>
|
||||||
|
<el-form-item label="课程名称">
|
||||||
|
<el-input
|
||||||
|
v-model="keyword"
|
||||||
|
placeholder="请输入课程名称"
|
||||||
|
clearable
|
||||||
|
style="width: 180px"
|
||||||
|
@keyup.enter="handleSearch"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="课程类型">
|
||||||
|
<el-select v-model="typeFilter" placeholder="全部" clearable style="width: 130px">
|
||||||
|
<el-option
|
||||||
|
v-for="(name, id) in typeMap"
|
||||||
|
:key="id"
|
||||||
|
:label="name"
|
||||||
|
:value="Number(id)"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-select v-model="statusFilter" placeholder="全部" clearable style="width: 100px">
|
||||||
|
<el-option label="正常" :value="0" />
|
||||||
|
<el-option label="已取消" :value="1" />
|
||||||
|
<el-option label="已结束" :value="2" />
|
||||||
|
<el-option label="已删除" :value="3" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="日期范围">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="dateRange"
|
||||||
|
type="daterange"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="开始日期"
|
||||||
|
end-placeholder="结束日期"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width: 230px"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="时间段">
|
||||||
|
<el-select v-model="timePeriod" placeholder="全部" clearable style="width: 100px">
|
||||||
|
<el-option label="早晨" value="morning" />
|
||||||
|
<el-option label="下午" value="afternoon" />
|
||||||
|
<el-option label="夜晚" value="evening" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="handleSearch">搜索</el-button>
|
||||||
|
<el-button @click="resetFilters">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px">
|
||||||
|
<el-button type="primary" @click="openCreate" v-permission="'business:groupCourse:create'">+ 新增团课</el-button>
|
||||||
|
|
||||||
|
<div style="display: flex; align-items: center; gap: 10px">
|
||||||
|
<span style="color: var(--text-secondary); font-size: 13px">排序:</span>
|
||||||
|
<el-select v-model="sortMode" style="width: 180px" size="default">
|
||||||
|
<el-option label="默认排序(ID倒序)" value="default" />
|
||||||
|
<el-option label="价格从低到高" value="priceAsc" />
|
||||||
|
<el-option label="价格从高到低" value="priceDesc" />
|
||||||
|
<el-option label="剩余名额最多" value="remainingMost" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="list" v-loading="loading" stripe highlight-current-row>
|
||||||
|
<el-table-column prop="id" label="团课ID" width="110" align="center" />
|
||||||
|
|
||||||
|
<el-table-column prop="courseName" label="课程名称" min-width="150" show-overflow-tooltip />
|
||||||
|
|
||||||
|
<el-table-column label="课程类型" width="110">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ typeMap[row.courseType] || row.courseType || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="封面" width="72" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<template v-if="row.coverImage && coverUrlMap[row.id]">
|
||||||
|
<img
|
||||||
|
:src="coverUrlMap[row.id]"
|
||||||
|
style="width: 56px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #dcdfe6"
|
||||||
|
@error="handleImgError"
|
||||||
|
/>
|
||||||
|
<span style="display: none; color: #c0c4cc; font-size: 18px">✕</span>
|
||||||
|
</template>
|
||||||
|
<span v-else style="color: #c0c4cc; font-size: 18px">✕</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="上课时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.startTime ? formatDate(row.startTime, 'MM-DD HH:mm') : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="下课时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.endTime ? formatDate(row.endTime, 'MM-DD HH:mm') : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column prop="location" label="上课地点" min-width="120" show-overflow-tooltip />
|
||||||
|
|
||||||
|
<el-table-column label="报名/上限" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span :style="{ color: row.currentMembers >= row.maxMembers ? '#ff4d4f' : '' }">
|
||||||
|
{{ row.currentMembers ?? 0 }}/{{ row.maxMembers ?? 0 }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="储值消耗" width="100" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.storedValueAmount != null ? '¥' + Number(row.storedValueAmount).toFixed(2) : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="状态" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag v-if="isDeleted(row)" type="warning" size="small">已删除</el-tag>
|
||||||
|
<el-tag v-else :type="statusTagType(row.status)" size="small">
|
||||||
|
{{ statusLabel(row.status) }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="创建时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.createdAt ? formatDate(row.createdAt, 'YYYY-MM-DD HH:mm') : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="操作" width="140" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'business:groupCourse:edit'">编辑</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="isDeleted(row)"
|
||||||
|
type="success"
|
||||||
|
link
|
||||||
|
@click="handleRestore(row)"
|
||||||
|
v-permission="'business:groupCourse:edit'"
|
||||||
|
>恢复</el-button>
|
||||||
|
<el-button v-else type="danger" link @click="handleDelete(row)" v-permission="'business:groupCourse:delete'">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div style="margin-top: 16px; display: flex; justify-content: space-between; align-items: center">
|
||||||
|
<span style="color: var(--text-secondary); font-size: 13px">
|
||||||
|
共 {{ total }} 条记录
|
||||||
|
</span>
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="displayPage"
|
||||||
|
:page-size="pageSize"
|
||||||
|
:total="total"
|
||||||
|
layout="prev, pager, next, sizes"
|
||||||
|
:page-sizes="[10, 20, 50, 100]"
|
||||||
|
@size-change="(s: number) => { pageSize = s; currentPage = 0; applyPage() }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Create / Edit Dialog -->
|
||||||
|
<el-dialog
|
||||||
|
v-model="dialogVisible"
|
||||||
|
:title="isEdit ? '编辑团课' : '新增团课'"
|
||||||
|
width="580px"
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
@closed="handleDialogClosed"
|
||||||
|
>
|
||||||
|
<el-form :model="form" label-width="100px">
|
||||||
|
<el-form-item label="课程名称" required>
|
||||||
|
<el-input v-model="form.courseName" placeholder="请输入课程名称" maxlength="50" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="课程类型" required>
|
||||||
|
<el-select v-model="form.courseType" placeholder="请选择课程类型" style="width: 100%">
|
||||||
|
<el-option
|
||||||
|
v-for="(name, id) in typeMap"
|
||||||
|
:key="id"
|
||||||
|
:label="name"
|
||||||
|
:value="Number(id)"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="上课时间">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="form.startTime"
|
||||||
|
type="datetime"
|
||||||
|
placeholder="选择上课时间"
|
||||||
|
value-format="YYYY-MM-DD HH:mm:ss"
|
||||||
|
style="width: 100%"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="下课时间">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="form.endTime"
|
||||||
|
type="datetime"
|
||||||
|
placeholder="选择下课时间"
|
||||||
|
value-format="YYYY-MM-DD HH:mm:ss"
|
||||||
|
style="width: 100%"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="上课地点">
|
||||||
|
<el-input v-model="form.location" placeholder="请输入上课地点" maxlength="100" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-row :gutter="16">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-form-item label="最大人数">
|
||||||
|
<el-input-number v-model="form.maxMembers" :min="1" style="width: 100%" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-form-item label="已报名人数">
|
||||||
|
<el-input-number v-model="form.currentMembers" :min="0" :max="form.maxMembers" style="width: 100%" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-select v-model="form.status" style="width: 100%">
|
||||||
|
<el-option label="正常" :value="0" />
|
||||||
|
<el-option label="已取消" :value="1" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="课程描述">
|
||||||
|
<el-input
|
||||||
|
v-model="form.description"
|
||||||
|
type="textarea"
|
||||||
|
:rows="3"
|
||||||
|
placeholder="请输入课程描述"
|
||||||
|
maxlength="500"
|
||||||
|
show-word-limit
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="封面图片">
|
||||||
|
<el-upload
|
||||||
|
:auto-upload="false"
|
||||||
|
:show-file-list="false"
|
||||||
|
accept="image/*"
|
||||||
|
:on-change="onUploadChange"
|
||||||
|
>
|
||||||
|
<template #trigger>
|
||||||
|
<el-button type="primary">选择封面图片</el-button>
|
||||||
|
</template>
|
||||||
|
</el-upload>
|
||||||
|
<div v-if="coverPreviewUrl" style="margin-top: 8px">
|
||||||
|
<a :href="coverPreviewUrl" target="_blank" :title="coverPreviewUrl">
|
||||||
|
<img
|
||||||
|
:src="coverPreviewUrl"
|
||||||
|
style="width: 180px; height: 100px; object-fit: cover; border-radius: 6px; border: 1px solid #dcdfe6"
|
||||||
|
@error="handleImgError"
|
||||||
|
/>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="储值卡额度">
|
||||||
|
<el-input-number v-model="form.storedValueAmount" :min="0" :precision="2" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item v-if="isEdit" label="管理员密码" required>
|
||||||
|
<el-input
|
||||||
|
v-model="adminPassword"
|
||||||
|
type="password"
|
||||||
|
placeholder="修改团课信息需要验证管理员密码"
|
||||||
|
show-password
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import {
|
||||||
|
getAllRecommendations,
|
||||||
|
createRecommendation,
|
||||||
|
updateRecommendation,
|
||||||
|
deleteRecommendation,
|
||||||
|
enableRecommendation,
|
||||||
|
disableRecommendation,
|
||||||
|
} from '@/api/modules/groupCourseRecommend'
|
||||||
|
import { searchGroupCourses } from '@/api/modules/groupCourse'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
// ---- Types ----
|
||||||
|
interface RecommendItem {
|
||||||
|
id: number
|
||||||
|
courseId: number
|
||||||
|
recommendTitle: string
|
||||||
|
recommendContent: string
|
||||||
|
recommendReason: string
|
||||||
|
priority: number
|
||||||
|
isActive: boolean
|
||||||
|
groupCourse?: {
|
||||||
|
id: number
|
||||||
|
courseName: string
|
||||||
|
startTime: string
|
||||||
|
endTime: string
|
||||||
|
location: string
|
||||||
|
maxMembers: number
|
||||||
|
currentMembers: number
|
||||||
|
status: number
|
||||||
|
}
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- State ----
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<RecommendItem[]>([])
|
||||||
|
const sortMode = ref<'priorityDesc' | 'priorityAsc' | 'idAsc' | 'idDesc'>('idAsc')
|
||||||
|
|
||||||
|
const sortOptions: { label: string; value: string; sortBy: string; sortOrder: string }[] = [
|
||||||
|
{ label: '优先级 高→低', value: 'priorityDesc', sortBy: 'priority', sortOrder: 'desc' },
|
||||||
|
{ label: '优先级 低→高', value: 'priorityAsc', sortBy: 'priority', sortOrder: 'asc' },
|
||||||
|
{ label: 'ID 升序', value: 'idAsc', sortBy: 'id', sortOrder: 'asc' },
|
||||||
|
{ label: 'ID 降序', value: 'idDesc', sortBy: 'id', sortOrder: 'desc' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const editId = ref<number | null>(null)
|
||||||
|
const saving = ref(false)
|
||||||
|
|
||||||
|
// course search state
|
||||||
|
interface CourseOption {
|
||||||
|
id: number
|
||||||
|
courseName: string
|
||||||
|
}
|
||||||
|
const courseOptions = ref<CourseOption[]>([])
|
||||||
|
const courseSearchLoading = ref(false)
|
||||||
|
|
||||||
|
async function searchCourses(keyword: string) {
|
||||||
|
courseSearchLoading.value = true
|
||||||
|
try {
|
||||||
|
const res: any = await searchGroupCourses({ courseName: keyword, page: 0, size: 50 })
|
||||||
|
const content = Array.isArray(res?.data?.content) ? res.data.content
|
||||||
|
: Array.isArray(res?.content) ? res.content
|
||||||
|
: Array.isArray(res) ? res
|
||||||
|
: []
|
||||||
|
courseOptions.value = content.map((c: any) => ({ id: c.id, courseName: c.courseName }))
|
||||||
|
} catch {
|
||||||
|
courseOptions.value = []
|
||||||
|
} finally {
|
||||||
|
courseSearchLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onCourseFocus() {
|
||||||
|
if (courseOptions.value.length === 0) {
|
||||||
|
searchCourses('')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const form = reactive({
|
||||||
|
courseId: null as number | null,
|
||||||
|
recommendTitle: '',
|
||||||
|
recommendContent: '',
|
||||||
|
recommendReason: '',
|
||||||
|
priority: 0,
|
||||||
|
isActive: true,
|
||||||
|
adminPassword: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const option = sortOptions.find((o) => o.value === sortMode.value)!
|
||||||
|
const res = await getAllRecommendations({ sortBy: option.sortBy, sortOrder: option.sortOrder })
|
||||||
|
list.value = Array.isArray(res) ? res : []
|
||||||
|
} catch {
|
||||||
|
list.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSortChange() {
|
||||||
|
fetchData()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(row: RecommendItem) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm('确定删除该推荐?', '提示', { type: 'warning' })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认删除', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确认删除',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await deleteRecommendation(row.id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
fetchData()
|
||||||
|
} catch {
|
||||||
|
ElMessage.warning('操作已取消')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
isEdit.value = false
|
||||||
|
editId.value = null
|
||||||
|
courseOptions.value = []
|
||||||
|
Object.assign(form, { courseId: null, recommendTitle: '', recommendContent: '', recommendReason: '', priority: 0, isActive: true, adminPassword: '' })
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: RecommendItem) {
|
||||||
|
isEdit.value = true
|
||||||
|
editId.value = row.id
|
||||||
|
// pre-load current course for display
|
||||||
|
if (row.groupCourse) {
|
||||||
|
courseOptions.value = [{ id: row.courseId, courseName: row.groupCourse.courseName }]
|
||||||
|
} else {
|
||||||
|
courseOptions.value = []
|
||||||
|
}
|
||||||
|
Object.assign(form, {
|
||||||
|
courseId: row.courseId,
|
||||||
|
recommendTitle: row.recommendTitle || '',
|
||||||
|
recommendContent: row.recommendContent || '',
|
||||||
|
recommendReason: row.recommendReason || '',
|
||||||
|
priority: row.priority,
|
||||||
|
isActive: row.isActive,
|
||||||
|
adminPassword: '',
|
||||||
|
})
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
if (form.courseId == null) {
|
||||||
|
ElMessage.warning('请选择团课')
|
||||||
|
saving.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const { adminPassword, ...payload } = form
|
||||||
|
if (isEdit.value) {
|
||||||
|
if (!adminPassword) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
saving.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await updateRecommendation(editId.value!, payload, { params: { adminPassword } })
|
||||||
|
ElMessage.success('更新成功')
|
||||||
|
} else {
|
||||||
|
await createRecommendation(payload)
|
||||||
|
ElMessage.success('创建成功')
|
||||||
|
}
|
||||||
|
dialogVisible.value = false
|
||||||
|
fetchData()
|
||||||
|
} catch {
|
||||||
|
// handled by interceptor
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleStatus(row: RecommendItem) {
|
||||||
|
try {
|
||||||
|
if (row.isActive) {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认禁用', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确认禁用',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await disableRecommendation(row.id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('已禁用')
|
||||||
|
} else {
|
||||||
|
await enableRecommendation(row.id)
|
||||||
|
ElMessage.success('已启用')
|
||||||
|
}
|
||||||
|
fetchData()
|
||||||
|
} catch {
|
||||||
|
ElMessage.warning('操作已取消')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => fetchData())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="recommend-page">
|
||||||
|
<h2 style="margin-bottom:16px">推荐团课管理</h2>
|
||||||
|
|
||||||
|
<!-- Filter & Action bar -->
|
||||||
|
<el-card class="filter-card" shadow="never">
|
||||||
|
<div class="filter-row">
|
||||||
|
<div class="filter-left">
|
||||||
|
<el-select v-model="sortMode" placeholder="排序方式" style="width:180px" @change="onSortChange">
|
||||||
|
<el-option
|
||||||
|
v-for="opt in sortOptions"
|
||||||
|
:key="opt.value"
|
||||||
|
:label="opt.label"
|
||||||
|
:value="opt.value"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
<div class="filter-right">
|
||||||
|
<el-button type="primary" @click="openCreate" v-permission="'business:groupCourseRecommend:create'">新增推荐</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<el-card shadow="never">
|
||||||
|
<el-table :data="list" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||||
|
<el-table-column label="团课" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div>
|
||||||
|
<div style="font-weight:500;font-size:13px">
|
||||||
|
{{ row.groupCourse?.courseName || `课程 #${row.courseId}` }}
|
||||||
|
</div>
|
||||||
|
<div style="color:#909399;font-size:12px">ID: {{ row.courseId }}</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="recommendTitle" label="推荐标题" width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="recommendContent" label="推荐内容" min-width="200" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="recommendReason" label="推荐理由" width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column label="优先级" width="90" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag
|
||||||
|
:type="row.priority >= 80 ? 'danger' : row.priority >= 50 ? 'warning' : row.priority >= 20 ? '' : 'info'"
|
||||||
|
size="small"
|
||||||
|
>{{ row.priority }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="90" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.isActive ? 'success' : 'info'" size="small">
|
||||||
|
{{ row.isActive ? '启用' : '禁用' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="240" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'business:groupCourseRecommend:edit'">编辑</el-button>
|
||||||
|
<el-button
|
||||||
|
:type="row.isActive ? 'warning' : 'success'"
|
||||||
|
link
|
||||||
|
@click="toggleStatus(row)"
|
||||||
|
v-permission="'business:groupCourseRecommend:edit'"
|
||||||
|
>
|
||||||
|
{{ row.isActive ? '禁用' : '启用' }}
|
||||||
|
</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)" v-permission="'business:groupCourseRecommend:delete'">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div v-if="list.length === 0 && !loading" style="color:#909399;font-size:13px;text-align:center;padding:40px">
|
||||||
|
暂无推荐数据
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Create / Edit dialog -->
|
||||||
|
<el-dialog v-model="dialogVisible" :title="isEdit ? '编辑推荐' : '新增推荐'" width="540px" :close-on-click-modal="false" @closed="form.adminPassword = ''">
|
||||||
|
<el-form :model="form" label-width="100px">
|
||||||
|
<el-form-item label="选择团课" required>
|
||||||
|
<el-select
|
||||||
|
v-model="form.courseId"
|
||||||
|
placeholder="输入关键字搜索团课"
|
||||||
|
filterable
|
||||||
|
remote
|
||||||
|
:remote-method="searchCourses"
|
||||||
|
:loading="courseSearchLoading"
|
||||||
|
@focus="onCourseFocus"
|
||||||
|
style="width:100%"
|
||||||
|
value-key="id"
|
||||||
|
>
|
||||||
|
<el-option
|
||||||
|
v-for="item in courseOptions"
|
||||||
|
:key="item.id"
|
||||||
|
:label="`${item.courseName} (ID: ${item.id})`"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="推荐标题">
|
||||||
|
<el-input v-model="form.recommendTitle" placeholder="如:本周热门" maxlength="100" show-word-limit />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="推荐内容">
|
||||||
|
<el-input v-model="form.recommendContent" type="textarea" :rows="2" placeholder="推荐描述文案" maxlength="500" show-word-limit />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="推荐理由">
|
||||||
|
<el-input v-model="form.recommendReason" placeholder="如:教练专业、课程丰富" maxlength="200" show-word-limit />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="优先级">
|
||||||
|
<el-input-number v-model="form.priority" :min="0" :max="9999" />
|
||||||
|
<span style="margin-left:8px;color:#909399;font-size:12px">(数值越大越靠前)</span>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="启用">
|
||||||
|
<el-switch v-model="form.isActive" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item v-if="isEdit" label="验证密码" required>
|
||||||
|
<el-input v-model="form.adminPassword" type="password" placeholder="请输入验证密码" show-password />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.recommend-page {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,727 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, computed, onMounted } from 'vue'
|
||||||
|
import {
|
||||||
|
getAllGroupCourseTypes,
|
||||||
|
createGroupCourseType,
|
||||||
|
updateGroupCourseType,
|
||||||
|
deleteGroupCourseType,
|
||||||
|
getCategories,
|
||||||
|
getLabelsByTypeId,
|
||||||
|
addLabelsToType,
|
||||||
|
removeLabelFromType,
|
||||||
|
clearTypeLabels,
|
||||||
|
getAllLabels,
|
||||||
|
createLabel,
|
||||||
|
updateLabel,
|
||||||
|
deleteLabel,
|
||||||
|
} from '@/api/modules/groupCourseType'
|
||||||
|
import { searchGroupCourses } from '@/api/modules/groupCourse'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { formatDate } from '@/utils/format'
|
||||||
|
|
||||||
|
// ---- Types ----
|
||||||
|
interface TypeItem {
|
||||||
|
id: number
|
||||||
|
typeName: string
|
||||||
|
baseDifficulty: number
|
||||||
|
calculatedDifficulty: number
|
||||||
|
difficultyLevel: string
|
||||||
|
description: string
|
||||||
|
category: string
|
||||||
|
labels?: LabelItem[]
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LabelItem {
|
||||||
|
id: number
|
||||||
|
labelName: string
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CourseItem {
|
||||||
|
id: number
|
||||||
|
courseName: string
|
||||||
|
startTime: string
|
||||||
|
endTime: string
|
||||||
|
maxMembers: number
|
||||||
|
currentMembers: number
|
||||||
|
status: number
|
||||||
|
location: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- State ----
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<TypeItem[]>([])
|
||||||
|
const categories = ref<string[]>([])
|
||||||
|
const categoryFilter = ref('')
|
||||||
|
const keyword = ref('')
|
||||||
|
const sortMode = ref<'default' | 'nameAsc' | 'nameDesc' | 'difficultyAsc' | 'difficultyDesc'>('default')
|
||||||
|
|
||||||
|
// per-type label cache for reactive table update
|
||||||
|
const labelCache = ref<Record<number, LabelItem[]>>({})
|
||||||
|
|
||||||
|
function getTypeLabels(row: TypeItem): LabelItem[] {
|
||||||
|
return labelCache.value[row.id] ?? row.labels ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
// filtered + sorted list
|
||||||
|
const filteredList = computed(() => {
|
||||||
|
let result = list.value
|
||||||
|
if (categoryFilter.value) {
|
||||||
|
result = result.filter((item) => item.category === categoryFilter.value)
|
||||||
|
}
|
||||||
|
if (keyword.value) {
|
||||||
|
const kw = keyword.value.toLowerCase()
|
||||||
|
result = result.filter(
|
||||||
|
(item) =>
|
||||||
|
item.typeName.toLowerCase().includes(kw) ||
|
||||||
|
item.description?.toLowerCase().includes(kw),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// sort (default: by id asc for stable order)
|
||||||
|
const mode = sortMode.value
|
||||||
|
if (mode === 'nameAsc') {
|
||||||
|
result = [...result].sort((a, b) => a.typeName.localeCompare(b.typeName, 'zh'))
|
||||||
|
} else if (mode === 'nameDesc') {
|
||||||
|
result = [...result].sort((a, b) => b.typeName.localeCompare(a.typeName, 'zh'))
|
||||||
|
} else if (mode === 'difficultyAsc') {
|
||||||
|
result = [...result].sort((a, b) => a.baseDifficulty - b.baseDifficulty)
|
||||||
|
} else if (mode === 'difficultyDesc') {
|
||||||
|
result = [...result].sort((a, b) => b.baseDifficulty - a.baseDifficulty)
|
||||||
|
} else {
|
||||||
|
// default: stable sort by id
|
||||||
|
result = [...result].sort((a, b) => a.id - b.id)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---- Type CRUD dialog ----
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const editId = ref<number | null>(null)
|
||||||
|
const saving = ref(false)
|
||||||
|
const form = reactive({
|
||||||
|
typeName: '',
|
||||||
|
category: '',
|
||||||
|
baseDifficulty: 1,
|
||||||
|
description: '',
|
||||||
|
adminPassword: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await getAllGroupCourseTypes()
|
||||||
|
const arr = Array.isArray(res) ? (res as TypeItem[]) : []
|
||||||
|
list.value = arr
|
||||||
|
// fetch labels for each type in parallel
|
||||||
|
if (arr.length > 0) {
|
||||||
|
const labelResults = await Promise.allSettled(
|
||||||
|
arr.map((item) => getLabelsByTypeId(item.id)),
|
||||||
|
)
|
||||||
|
const cache: Record<number, LabelItem[]> = {}
|
||||||
|
labelResults.forEach((result, i) => {
|
||||||
|
if (result.status === 'fulfilled' && Array.isArray(result.value)) {
|
||||||
|
cache[arr[i].id] = result.value as LabelItem[]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
labelCache.value = cache
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
list.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchCategories() {
|
||||||
|
try {
|
||||||
|
const res = await getCategories()
|
||||||
|
categories.value = Array.isArray(res) ? res : []
|
||||||
|
} catch {
|
||||||
|
categories.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(id: number) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm('确定删除该类型?', '提示', { type: 'warning' })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认删除', '管理员验证', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确认删除',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
})
|
||||||
|
if (!pwd) return
|
||||||
|
await deleteGroupCourseType(id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
fetchData()
|
||||||
|
} catch (e: any) {
|
||||||
|
if (e !== 'cancel' && e?.message !== 'cancel') {
|
||||||
|
// error handled by interceptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
isEdit.value = false
|
||||||
|
editId.value = null
|
||||||
|
Object.assign(form, { typeName: '', category: '', baseDifficulty: 1, description: '', adminPassword: '' })
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: TypeItem) {
|
||||||
|
isEdit.value = true
|
||||||
|
editId.value = row.id
|
||||||
|
Object.assign(form, {
|
||||||
|
typeName: row.typeName,
|
||||||
|
category: row.category,
|
||||||
|
baseDifficulty: row.baseDifficulty,
|
||||||
|
description: row.description || '',
|
||||||
|
adminPassword: '',
|
||||||
|
})
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
const { adminPassword, ...payload } = form
|
||||||
|
if (isEdit.value) {
|
||||||
|
if (!adminPassword) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
saving.value = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await updateGroupCourseType(editId.value!, payload, { params: { adminPassword } })
|
||||||
|
ElMessage.success('更新成功')
|
||||||
|
} else {
|
||||||
|
await createGroupCourseType(payload)
|
||||||
|
ElMessage.success('创建成功')
|
||||||
|
}
|
||||||
|
dialogVisible.value = false
|
||||||
|
fetchData()
|
||||||
|
} catch {
|
||||||
|
// error handled by interceptor
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Label management per type ----
|
||||||
|
const labelDialogVisible = ref(false)
|
||||||
|
const labelTypeId = ref<number | null>(null)
|
||||||
|
const labelTypeName = ref('')
|
||||||
|
const typeLabels = ref<LabelItem[]>([])
|
||||||
|
const allLabels = ref<LabelItem[]>([])
|
||||||
|
const labelLoading = ref(false)
|
||||||
|
|
||||||
|
const unassignedLabels = computed(() => {
|
||||||
|
const assignedIds = new Set(typeLabels.value.map((l) => l.id))
|
||||||
|
return allLabels.value.filter((l) => !assignedIds.has(l.id))
|
||||||
|
})
|
||||||
|
|
||||||
|
async function openLabelDialog(row: TypeItem) {
|
||||||
|
labelTypeId.value = row.id
|
||||||
|
labelTypeName.value = row.typeName
|
||||||
|
labelDialogVisible.value = true
|
||||||
|
labelLoading.value = true
|
||||||
|
try {
|
||||||
|
const [tLabels, aLabels] = await Promise.all([getLabelsByTypeId(row.id), getAllLabels()])
|
||||||
|
typeLabels.value = Array.isArray(tLabels) ? tLabels : []
|
||||||
|
allLabels.value = Array.isArray(aLabels) ? aLabels : []
|
||||||
|
} catch {
|
||||||
|
typeLabels.value = []
|
||||||
|
allLabels.value = []
|
||||||
|
} finally {
|
||||||
|
labelLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAddLabel(labelId: number) {
|
||||||
|
if (labelTypeId.value == null) return
|
||||||
|
try {
|
||||||
|
await addLabelsToType(labelTypeId.value, [labelId])
|
||||||
|
const tLabels = await getLabelsByTypeId(labelTypeId.value)
|
||||||
|
const arr = Array.isArray(tLabels) ? (tLabels as LabelItem[]) : []
|
||||||
|
typeLabels.value = arr
|
||||||
|
labelCache.value = { ...labelCache.value, [labelTypeId.value]: arr }
|
||||||
|
ElMessage.success('标签已添加')
|
||||||
|
} catch {
|
||||||
|
// handled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRemoveLabel(labelId: number) {
|
||||||
|
if (labelTypeId.value == null) return
|
||||||
|
try {
|
||||||
|
await removeLabelFromType(labelTypeId.value, labelId)
|
||||||
|
const updated = typeLabels.value.filter((l) => l.id !== labelId)
|
||||||
|
typeLabels.value = updated
|
||||||
|
labelCache.value = { ...labelCache.value, [labelTypeId.value]: updated }
|
||||||
|
ElMessage.success('标签已移除')
|
||||||
|
} catch {
|
||||||
|
// handled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleClearLabels() {
|
||||||
|
if (labelTypeId.value == null) return
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm('确定清空该类型的所有标签?', '提示', { type: 'warning' })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await clearTypeLabels(labelTypeId.value)
|
||||||
|
typeLabels.value = []
|
||||||
|
labelCache.value = { ...labelCache.value, [labelTypeId.value]: [] }
|
||||||
|
ElMessage.success('标签已清空')
|
||||||
|
} catch {
|
||||||
|
// handled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Global label CRUD ----
|
||||||
|
const globalLabelDialogVisible = ref(false)
|
||||||
|
const globalLabelForm = reactive({ id: null as number | null, labelName: '', color: '#1890ff' })
|
||||||
|
const globalLabelIsEdit = ref(false)
|
||||||
|
const globalLabelSaving = ref(false)
|
||||||
|
|
||||||
|
const presetColors = [
|
||||||
|
'#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
|
||||||
|
'#13c2c2', '#eb2f96', '#fa541c', '#2f54eb', '#a0d911',
|
||||||
|
]
|
||||||
|
|
||||||
|
async function fetchAllLabels() {
|
||||||
|
try {
|
||||||
|
const res = await getAllLabels()
|
||||||
|
allLabels.value = Array.isArray(res) ? res : []
|
||||||
|
} catch {
|
||||||
|
allLabels.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openGlobalLabelDialog() {
|
||||||
|
fetchAllLabels()
|
||||||
|
globalLabelDialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreateLabel() {
|
||||||
|
globalLabelIsEdit.value = false
|
||||||
|
Object.assign(globalLabelForm, { id: null, labelName: '', color: '#1890ff' })
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditLabel(row: LabelItem) {
|
||||||
|
globalLabelIsEdit.value = true
|
||||||
|
Object.assign(globalLabelForm, { id: row.id, labelName: row.labelName, color: row.color })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveLabel() {
|
||||||
|
globalLabelSaving.value = true
|
||||||
|
try {
|
||||||
|
if (globalLabelIsEdit.value && globalLabelForm.id) {
|
||||||
|
await updateLabel(globalLabelForm.id, { labelName: globalLabelForm.labelName, color: globalLabelForm.color })
|
||||||
|
ElMessage.success('标签更新成功')
|
||||||
|
} else {
|
||||||
|
await createLabel({ labelName: globalLabelForm.labelName, color: globalLabelForm.color })
|
||||||
|
ElMessage.success('标签创建成功')
|
||||||
|
}
|
||||||
|
await fetchAllLabels()
|
||||||
|
openCreateLabel()
|
||||||
|
} catch {
|
||||||
|
// handled
|
||||||
|
} finally {
|
||||||
|
globalLabelSaving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteLabel(row: LabelItem) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定删除标签 "${row.labelName}"?`, '提示', { type: 'warning' })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await deleteLabel(row.id)
|
||||||
|
ElMessage.success('标签已删除')
|
||||||
|
await fetchAllLabels()
|
||||||
|
} catch {
|
||||||
|
// handled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Difficulty tag type ----
|
||||||
|
function difficultyTagType(level: string) {
|
||||||
|
const map: Record<string, string> = { '初级': 'success', '中级': 'warning', '中高级': 'warning', '高级': 'danger', '专家级': 'danger' }
|
||||||
|
return map[level] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Type detail dialog ----
|
||||||
|
const detailDialogVisible = ref(false)
|
||||||
|
const detailType = ref<TypeItem | null>(null)
|
||||||
|
const detailCourses = ref<CourseItem[]>([])
|
||||||
|
const detailLoading = ref(false)
|
||||||
|
|
||||||
|
const statusLabel = (s: number) => {
|
||||||
|
const map: Record<number, string> = { 0: '正常', 1: '已取消', 2: '已结束' }
|
||||||
|
return map[s] ?? '未知'
|
||||||
|
}
|
||||||
|
const statusTagType = (s: number): any => {
|
||||||
|
const map: Record<number, string> = { 0: 'success', 1: 'warning', 2: 'info' }
|
||||||
|
return map[s] ?? 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openDetailDialog(row: TypeItem) {
|
||||||
|
detailType.value = row
|
||||||
|
detailDialogVisible.value = true
|
||||||
|
detailLoading.value = true
|
||||||
|
try {
|
||||||
|
const res: any = await searchGroupCourses({ courseType: row.id, page: 0, size: 100 })
|
||||||
|
if (res?.data) {
|
||||||
|
detailCourses.value = Array.isArray(res.data.content) ? res.data.content : []
|
||||||
|
} else if (Array.isArray(res)) {
|
||||||
|
detailCourses.value = res
|
||||||
|
} else if (res?.content) {
|
||||||
|
detailCourses.value = res.content
|
||||||
|
} else {
|
||||||
|
detailCourses.value = []
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
detailCourses.value = []
|
||||||
|
} finally {
|
||||||
|
detailLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Lifecycle ----
|
||||||
|
onMounted(() => {
|
||||||
|
fetchData()
|
||||||
|
fetchCategories()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="groupcourse-type-page">
|
||||||
|
<h2 style="margin-bottom:16px">类型管理</h2>
|
||||||
|
|
||||||
|
<!-- Filter & Action bar -->
|
||||||
|
<el-card class="filter-card" shadow="never">
|
||||||
|
<div class="filter-row">
|
||||||
|
<div class="filter-left">
|
||||||
|
<el-input v-model="keyword" placeholder="搜索类型名称或描述" clearable style="width:260px" />
|
||||||
|
<el-select v-model="categoryFilter" placeholder="全部分类" clearable style="width:180px">
|
||||||
|
<el-option v-for="cat in categories" :key="cat" :label="cat" :value="cat" />
|
||||||
|
</el-select>
|
||||||
|
<el-select v-model="sortMode" placeholder="默认排序" style="width:150px">
|
||||||
|
<el-option label="默认排序" value="default" />
|
||||||
|
<el-option label="名称 A→Z" value="nameAsc" />
|
||||||
|
<el-option label="名称 Z→A" value="nameDesc" />
|
||||||
|
<el-option label="难度 低→高" value="difficultyAsc" />
|
||||||
|
<el-option label="难度 高→低" value="difficultyDesc" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
<div class="filter-right">
|
||||||
|
<el-button type="primary" @click="openCreate" v-permission="'business:groupCourseType:create'">新增类型</el-button>
|
||||||
|
<el-button @click="openGlobalLabelDialog" v-permission="'business:groupCourseType:edit'">管理标签</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Type table -->
|
||||||
|
<el-card shadow="never">
|
||||||
|
<el-table :data="filteredList" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||||
|
<el-table-column prop="typeName" label="类型名称" width="160">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button link type="primary" @click="openDetailDialog(row)">
|
||||||
|
{{ row.typeName }}
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="category" label="分类" width="140" />
|
||||||
|
<el-table-column label="难度" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div style="display:flex;align-items:center;gap:8px">
|
||||||
|
<el-tag :type="difficultyTagType(row.difficultyLevel)" size="small">
|
||||||
|
{{ row.difficultyLevel || '-' }}
|
||||||
|
</el-tag>
|
||||||
|
<span style="color:#909399;font-size:12px">{{ row.baseDifficulty }}/10</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="标签" min-width="220">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div style="display:flex;align-items:center;flex-wrap:wrap;gap:6px">
|
||||||
|
<template v-if="getTypeLabels(row).length > 0">
|
||||||
|
<el-tag
|
||||||
|
v-for="lbl in getTypeLabels(row)"
|
||||||
|
:key="lbl.id"
|
||||||
|
:color="lbl.color"
|
||||||
|
effect="dark"
|
||||||
|
size="small"
|
||||||
|
>{{ lbl.labelName }}</el-tag>
|
||||||
|
</template>
|
||||||
|
<span v-else style="color:#c0c4cc;font-size:12px">-</span>
|
||||||
|
<el-button link type="primary" size="small" style="margin-left:4px" @click="openLabelDialog(row)">
|
||||||
|
编辑
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="description" label="描述" min-width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column label="操作" width="180" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'business:groupCourseType:edit'">编辑</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row.id)" v-permission="'business:groupCourseType:delete'">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div v-if="keyword || categoryFilter || sortMode !== 'default'" style="margin-top:12px;color:#909399;font-size:12px">
|
||||||
|
共 {{ filteredList.length }} 条结果
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Type create / edit dialog -->
|
||||||
|
<el-dialog v-model="dialogVisible" :title="isEdit ? '编辑类型' : '新增类型'" width="520px" :close-on-click-modal="false" @closed="form.adminPassword = ''">
|
||||||
|
<el-form :model="form" label-width="90px">
|
||||||
|
<el-form-item label="类型名称" required>
|
||||||
|
<el-input v-model="form.typeName" placeholder="请输入类型名称" maxlength="50" show-word-limit />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="分类">
|
||||||
|
<el-select v-model="form.category" placeholder="选择或输入分类" filterable allow-create style="width:100%">
|
||||||
|
<el-option v-for="cat in categories" :key="cat" :label="cat" :value="cat" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="基础难度">
|
||||||
|
<el-input-number v-model="form.baseDifficulty" :min="1" :max="10" />
|
||||||
|
<span style="margin-left:8px;color:#909399;font-size:12px">(1-10,2以下为初级,9以上为专家级)</span>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="描述">
|
||||||
|
<el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入类型描述" maxlength="200" show-word-limit />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item v-if="isEdit" label="验证密码" required>
|
||||||
|
<el-input v-model="form.adminPassword" type="password" placeholder="请输入验证密码" show-password />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- Label management dialog (per type) -->
|
||||||
|
<el-dialog v-model="labelDialogVisible" :title="`标签管理 - ${labelTypeName}`" width="600px" :close-on-click-modal="false">
|
||||||
|
<div v-loading="labelLoading">
|
||||||
|
<div style="margin-bottom:20px">
|
||||||
|
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
|
||||||
|
<strong>已分配标签</strong>
|
||||||
|
<el-button v-if="typeLabels.length" type="danger" size="small" plain @click="handleClearLabels">清空全部</el-button>
|
||||||
|
</div>
|
||||||
|
<div v-if="typeLabels.length === 0" style="color:#909399;font-size:13px">暂无标签</div>
|
||||||
|
<div v-else style="display:flex;flex-wrap:wrap;gap:8px">
|
||||||
|
<el-tag
|
||||||
|
v-for="label in typeLabels"
|
||||||
|
:key="label.id"
|
||||||
|
:color="label.color"
|
||||||
|
closable
|
||||||
|
effect="dark"
|
||||||
|
@close="handleRemoveLabel(label.id)"
|
||||||
|
>
|
||||||
|
{{ label.labelName }}
|
||||||
|
</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-divider />
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<strong style="display:block;margin-bottom:8px">可选标签</strong>
|
||||||
|
<div v-if="unassignedLabels.length === 0" style="color:#909399;font-size:13px">
|
||||||
|
所有标签已分配,可在下方"管理标签"中新建
|
||||||
|
</div>
|
||||||
|
<div v-else style="display:flex;flex-wrap:wrap;gap:8px">
|
||||||
|
<el-tag
|
||||||
|
v-for="label in unassignedLabels"
|
||||||
|
:key="label.id"
|
||||||
|
:color="label.color"
|
||||||
|
effect="plain"
|
||||||
|
style="cursor:pointer"
|
||||||
|
@click="handleAddLabel(label.id)"
|
||||||
|
>
|
||||||
|
+ {{ label.labelName }}
|
||||||
|
</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="labelDialogVisible = false">关闭</el-button>
|
||||||
|
<el-button type="primary" @click="labelDialogVisible = false; openGlobalLabelDialog()">管理全部标签</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- Global label CRUD dialog -->
|
||||||
|
<el-dialog v-model="globalLabelDialogVisible" title="标签管理" width="650px" :close-on-click-modal="false">
|
||||||
|
<div style="display:flex;gap:20px">
|
||||||
|
<div style="flex:1">
|
||||||
|
<div style="font-weight:600;margin-bottom:8px">所有标签</div>
|
||||||
|
<div v-if="allLabels.length === 0" style="color:#909399;font-size:13px">暂无标签</div>
|
||||||
|
<div v-else style="display:flex;flex-wrap:wrap;gap:6px">
|
||||||
|
<el-tag
|
||||||
|
v-for="label in allLabels"
|
||||||
|
:key="label.id"
|
||||||
|
:color="label.color"
|
||||||
|
effect="dark"
|
||||||
|
style="cursor:pointer"
|
||||||
|
@click="openEditLabel(label)"
|
||||||
|
>
|
||||||
|
{{ label.labelName }}
|
||||||
|
<span style="margin-left:2px;opacity:0.7;font-size:11px">(编辑)</span>
|
||||||
|
</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="width:260px;border-left:1px solid #ebeef5;padding-left:20px">
|
||||||
|
<div style="font-weight:600;margin-bottom:12px">
|
||||||
|
{{ globalLabelIsEdit ? '编辑标签' : '新建标签' }}
|
||||||
|
</div>
|
||||||
|
<el-form :model="globalLabelForm" label-width="70px" size="small">
|
||||||
|
<el-form-item label="名称" required>
|
||||||
|
<el-input v-model="globalLabelForm.labelName" placeholder="标签名称" maxlength="50" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="颜色">
|
||||||
|
<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px">
|
||||||
|
<div
|
||||||
|
v-for="c in presetColors"
|
||||||
|
:key="c"
|
||||||
|
:style="{ background: c, width: '22px', height: '22px', borderRadius: '4px', cursor: 'pointer', border: globalLabelForm.color === c ? '2px solid #303133' : '2px solid transparent' }"
|
||||||
|
@click="globalLabelForm.color = c"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<el-color-picker v-model="globalLabelForm.color" show-alpha />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" :loading="globalLabelSaving" @click="handleSaveLabel">
|
||||||
|
{{ globalLabelIsEdit ? '更新' : '创建' }}
|
||||||
|
</el-button>
|
||||||
|
<el-button v-if="globalLabelIsEdit" @click="openCreateLabel">新建</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<div v-if="globalLabelIsEdit && globalLabelForm.id" style="margin-top:8px">
|
||||||
|
<el-button type="danger" size="small" plain @click="handleDeleteLabel(globalLabelForm as any)">
|
||||||
|
删除此标签
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="globalLabelDialogVisible = false">关闭</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- Type detail dialog -->
|
||||||
|
<el-dialog v-model="detailDialogVisible" :title="detailType?.typeName ?? '类型详情'" width="750px" :close-on-click-modal="false">
|
||||||
|
<div v-if="detailType">
|
||||||
|
<!-- Type info -->
|
||||||
|
<el-descriptions :column="3" border size="small" style="margin-bottom:20px">
|
||||||
|
<el-descriptions-item label="ID">{{ detailType.id }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="分类">{{ detailType.category || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="难度">
|
||||||
|
<el-tag :type="difficultyTagType(detailType.difficultyLevel)" size="small">
|
||||||
|
{{ detailType.difficultyLevel }}
|
||||||
|
</el-tag>
|
||||||
|
<span style="margin-left:4px;color:#909399">({{ detailType.baseDifficulty }}/10)</span>
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="描述" :span="3">{{ detailType.description || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="标签" :span="3">
|
||||||
|
<template v-if="getTypeLabels(detailType).length > 0">
|
||||||
|
<el-tag
|
||||||
|
v-for="lbl in getTypeLabels(detailType)"
|
||||||
|
:key="lbl.id"
|
||||||
|
:color="lbl.color"
|
||||||
|
effect="dark"
|
||||||
|
size="small"
|
||||||
|
style="margin-right:6px"
|
||||||
|
>{{ lbl.labelName }}</el-tag>
|
||||||
|
</template>
|
||||||
|
<span v-else style="color:#c0c4cc">-</span>
|
||||||
|
</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
|
||||||
|
<!-- Courses -->
|
||||||
|
<div style="font-weight:600;margin-bottom:10px">
|
||||||
|
该类型下的团课
|
||||||
|
<span style="font-weight:400;color:#909399;font-size:13px;margin-left:4px">
|
||||||
|
({{ detailCourses.length }})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<el-table :data="detailCourses" v-loading="detailLoading" stripe size="small" max-height="300">
|
||||||
|
<el-table-column prop="id" label="ID" width="60" align="center" />
|
||||||
|
<el-table-column prop="courseName" label="课程名称" width="160" />
|
||||||
|
<el-table-column label="上课时间" width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div style="font-size:12px">
|
||||||
|
<div>{{ formatDate(row.startTime) }}</div>
|
||||||
|
<div style="color:#909399">{{ formatDate(row.endTime) }}</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="location" label="地点" width="120" />
|
||||||
|
<el-table-column label="人数" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span :style="{ color: row.currentMembers >= row.maxMembers ? '#f56c6c' : '' }">
|
||||||
|
{{ row.currentMembers }} / {{ row.maxMembers }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="90" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="statusTagType(row.status as number)" size="small">{{ statusLabel(row.status as number) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div v-if="!detailLoading && detailCourses.length === 0" style="color:#909399;font-size:13px;text-align:center;padding:20px">
|
||||||
|
暂无团课
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="detailDialogVisible = false">关闭</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.groupcourse-type-page {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
|
||||||
|
const formRef = ref()
|
||||||
|
const form = reactive({
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
})
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const rules = {
|
||||||
|
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||||
|
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLogin() {
|
||||||
|
const valid = await formRef.value?.validate().catch(() => false)
|
||||||
|
if (!valid) return
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await userStore.login(form)
|
||||||
|
ElMessage.success('登录成功')
|
||||||
|
router.push('/dashboard')
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.response?.data?.message || '登录失败')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="login-container">
|
||||||
|
<div class="login-card">
|
||||||
|
<h2 class="login-title">CUIT Gym 管理系统</h2>
|
||||||
|
<el-form ref="formRef" :model="form" :rules="rules" label-width="0" size="large">
|
||||||
|
<el-form-item prop="username">
|
||||||
|
<el-input v-model="form.username" placeholder="用户名" prefix-icon="User" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item prop="password">
|
||||||
|
<el-input v-model="form.password" type="password" placeholder="密码" prefix-icon="Lock" @keyup.enter="handleLogin" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" :loading="loading" style="width: 100%" @click="handleLogin">
|
||||||
|
登 录
|
||||||
|
</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.login-container {
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
}
|
||||||
|
.login-card {
|
||||||
|
width: 400px;
|
||||||
|
padding: 40px;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
.login-title {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 32px;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, computed, onMounted, watch } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { getAllMembers, getMemberDetail, updateMember } from '@/api/modules/member'
|
||||||
|
import { formatDate } from '@/utils/format'
|
||||||
|
|
||||||
|
// ---- Types ----
|
||||||
|
interface MemberItem {
|
||||||
|
id: number
|
||||||
|
memberNo: string
|
||||||
|
nickname: string
|
||||||
|
phone: string
|
||||||
|
gender: number
|
||||||
|
avatar: string | null
|
||||||
|
lastLoginAt: string | null
|
||||||
|
createdAt: string | null
|
||||||
|
updatedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
type SortField = 'createdAt' | 'memberNo' | 'nickname'
|
||||||
|
type SortDir = 'desc' | 'asc'
|
||||||
|
|
||||||
|
interface SortOption {
|
||||||
|
label: string
|
||||||
|
field: SortField
|
||||||
|
dir: SortDir
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- State ----
|
||||||
|
const loading = ref(false)
|
||||||
|
const rawList = ref<MemberItem[]>([])
|
||||||
|
const detailVisible = ref(false)
|
||||||
|
const detailLoading = ref(false)
|
||||||
|
const detail = ref<any>(null)
|
||||||
|
|
||||||
|
const keyword = ref('')
|
||||||
|
const genderFilter = ref<number | null>(null)
|
||||||
|
const sortBy = ref<SortOption>({ label: '注册时间(新→旧)', field: 'createdAt', dir: 'desc' })
|
||||||
|
const currentPage = ref(1)
|
||||||
|
const pageSize = ref(12)
|
||||||
|
|
||||||
|
const sortOptions: SortOption[] = [
|
||||||
|
{ label: '注册时间(新→旧)', field: 'createdAt', dir: 'desc' },
|
||||||
|
{ label: '注册时间(旧→新)', field: 'createdAt', dir: 'asc' },
|
||||||
|
{ label: '会员编号', field: 'memberNo', dir: 'asc' },
|
||||||
|
{ label: '昵称', field: 'nickname', dir: 'asc' },
|
||||||
|
]
|
||||||
|
|
||||||
|
// ---- Edit state ----
|
||||||
|
const editVisible = ref(false)
|
||||||
|
const editSaving = ref(false)
|
||||||
|
const editFormRef = ref()
|
||||||
|
const editForm = reactive({
|
||||||
|
id: 0,
|
||||||
|
memberNo: '',
|
||||||
|
nickname: '',
|
||||||
|
gender: null as number | null,
|
||||||
|
birthday: '',
|
||||||
|
address: '',
|
||||||
|
adminPassword: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---- Computed ----
|
||||||
|
const filteredList = computed(() => {
|
||||||
|
let items = rawList.value.filter((m) => {
|
||||||
|
if (keyword.value) {
|
||||||
|
const kw = keyword.value.toLowerCase()
|
||||||
|
const match =
|
||||||
|
m.nickname?.toLowerCase().includes(kw) ||
|
||||||
|
m.memberNo?.toLowerCase().includes(kw) ||
|
||||||
|
m.phone?.includes(kw)
|
||||||
|
if (!match) return false
|
||||||
|
}
|
||||||
|
if (genderFilter.value !== null && m.gender !== genderFilter.value) return false
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
// Sort
|
||||||
|
const { field, dir } = sortBy.value
|
||||||
|
items = [...items].sort((a, b) => {
|
||||||
|
let va: any = a[field] ?? ''
|
||||||
|
let vb: any = b[field] ?? ''
|
||||||
|
if (field === 'createdAt') {
|
||||||
|
va = va ? new Date(va).getTime() : 0
|
||||||
|
vb = vb ? new Date(vb).getTime() : 0
|
||||||
|
} else {
|
||||||
|
va = String(va).toLowerCase()
|
||||||
|
vb = String(vb).toLowerCase()
|
||||||
|
}
|
||||||
|
return dir === 'desc' ? vb - va : va > vb ? 1 : va < vb ? -1 : 0
|
||||||
|
})
|
||||||
|
|
||||||
|
return items
|
||||||
|
})
|
||||||
|
|
||||||
|
const totalFiltered = computed(() => filteredList.value.length)
|
||||||
|
|
||||||
|
const pagedList = computed(() => {
|
||||||
|
const start = (currentPage.value - 1) * pageSize.value
|
||||||
|
return filteredList.value.slice(start, start + pageSize.value)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---- Methods ----
|
||||||
|
function genderLabel(val: number) {
|
||||||
|
const map: Record<number, string> = { 0: '未知', 1: '男', 2: '女' }
|
||||||
|
return map[val] ?? '未知'
|
||||||
|
}
|
||||||
|
|
||||||
|
function phoneDisplay(phone: string | null | undefined) {
|
||||||
|
if (!phone) return '-'
|
||||||
|
// 后端已脱敏,直接显示
|
||||||
|
return phone
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchAll() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
// 拉取较大页面的数据一次,后续在前端做筛选排序分页
|
||||||
|
const res = await getAllMembers({ pageNum: 1, pageSize: 500 })
|
||||||
|
rawList.value = Array.isArray(res) ? res : []
|
||||||
|
} catch {
|
||||||
|
rawList.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function viewDetail(id: number) {
|
||||||
|
detailLoading.value = true
|
||||||
|
detail.value = null
|
||||||
|
detailVisible.value = true
|
||||||
|
try {
|
||||||
|
const res = await getMemberDetail(id)
|
||||||
|
detail.value = res || null
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || '获取会员详情失败')
|
||||||
|
detailVisible.value = false
|
||||||
|
} finally {
|
||||||
|
detailLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSearch() {
|
||||||
|
currentPage.value = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFilters() {
|
||||||
|
keyword.value = ''
|
||||||
|
genderFilter.value = null
|
||||||
|
sortBy.value = sortOptions[0]
|
||||||
|
currentPage.value = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: MemberItem) {
|
||||||
|
editForm.id = row.id
|
||||||
|
editForm.memberNo = row.memberNo || ''
|
||||||
|
editForm.nickname = row.nickname || ''
|
||||||
|
editForm.gender = row.gender ?? null
|
||||||
|
editForm.birthday = ''
|
||||||
|
editForm.address = ''
|
||||||
|
editForm.adminPassword = ''
|
||||||
|
editVisible.value = true
|
||||||
|
|
||||||
|
// 异步获取详情填充更多字段
|
||||||
|
getMemberDetail(row.id).then((res: any) => {
|
||||||
|
if (res) {
|
||||||
|
if (res.birthday) {
|
||||||
|
editForm.birthday = typeof res.birthday === 'string'
|
||||||
|
? res.birthday.substring(0, 10)
|
||||||
|
: res.birthday
|
||||||
|
}
|
||||||
|
editForm.address = res.address || ''
|
||||||
|
}
|
||||||
|
}).catch(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doEdit() {
|
||||||
|
editSaving.value = true
|
||||||
|
try {
|
||||||
|
const payload: any = {
|
||||||
|
adminPassword: editForm.adminPassword,
|
||||||
|
nickname: editForm.nickname,
|
||||||
|
}
|
||||||
|
if (editForm.gender !== null) {
|
||||||
|
payload.gender = editForm.gender === 1 ? 'MALE' : editForm.gender === 2 ? 'FEMALE' : 'UNKNOWN'
|
||||||
|
}
|
||||||
|
if (editForm.birthday) {
|
||||||
|
payload.birthday = editForm.birthday
|
||||||
|
}
|
||||||
|
if (editForm.address) {
|
||||||
|
payload.address = editForm.address
|
||||||
|
}
|
||||||
|
|
||||||
|
const res: any = await updateMember(editForm.id, payload)
|
||||||
|
// 双重校验:后端可能以 200 返回业务错误码
|
||||||
|
if (res && res.code && res.code >= 400) {
|
||||||
|
ElMessage.error(res.message || '修改失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ElMessage.success('修改成功')
|
||||||
|
editVisible.value = false
|
||||||
|
fetchAll()
|
||||||
|
} catch (e: any) {
|
||||||
|
// axios 拦截器已处理 4xx/5xx,此处兜底
|
||||||
|
const msg = e?.response?.data?.message || e?.message || '修改失败'
|
||||||
|
ElMessage.error(msg)
|
||||||
|
} finally {
|
||||||
|
editSaving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// reset page when filters change
|
||||||
|
watch([keyword, genderFilter, sortBy], () => {
|
||||||
|
currentPage.value = 1
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchAll()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom: 16px">会员管理</h2>
|
||||||
|
|
||||||
|
<!-- Stats -->
|
||||||
|
<el-row :gutter="16" style="margin-bottom: 16px">
|
||||||
|
<el-col :span="6" v-for="s in [
|
||||||
|
{ label: '会员总数', value: rawList.length, color: '#1890ff' },
|
||||||
|
{ label: '筛选结果', value: totalFiltered, color: '#52c41a' },
|
||||||
|
{ label: '男性', value: rawList.filter(m => m.gender === 1).length, color: '#722ed1' },
|
||||||
|
{ label: '女性', value: rawList.filter(m => m.gender === 2).length, color: '#faad14' },
|
||||||
|
]" :key="s.label">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align: center">
|
||||||
|
<div style="font-size: 26px; font-weight: bold" :style="{ color: s.color }">
|
||||||
|
{{ s.value.toLocaleString() }}
|
||||||
|
</div>
|
||||||
|
<div style="color: var(--text-secondary); margin-top: 4px; font-size: 13px">{{ s.label }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Search -->
|
||||||
|
<el-card class="search-card">
|
||||||
|
<el-form inline>
|
||||||
|
<el-form-item label="关键词">
|
||||||
|
<el-input
|
||||||
|
v-model="keyword"
|
||||||
|
placeholder="会员编号 / 昵称 / 手机号"
|
||||||
|
clearable
|
||||||
|
style="width: 260px"
|
||||||
|
@keyup.enter="handleSearch"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="性别">
|
||||||
|
<el-select v-model="genderFilter" placeholder="全部" clearable style="width: 100px">
|
||||||
|
<el-option label="男" :value="1" />
|
||||||
|
<el-option label="女" :value="2" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="排序方式">
|
||||||
|
<el-select v-model="sortBy" value-key="label" style="width: 190px">
|
||||||
|
<el-option v-for="opt in sortOptions" :key="opt.label" :label="opt.label" :value="opt" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="handleSearch">搜索</el-button>
|
||||||
|
<el-button @click="resetFilters">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="pagedList" v-loading="loading" stripe highlight-current-row>
|
||||||
|
<el-table-column type="index" label="#" width="50" />
|
||||||
|
|
||||||
|
<el-table-column label="头像" width="64" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-avatar :size="36" :src="row.avatar">
|
||||||
|
<template #default>
|
||||||
|
<span style="font-size: 14px">{{ (row.nickname || '?')[0] }}</span>
|
||||||
|
</template>
|
||||||
|
</el-avatar>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column prop="memberNo" label="会员编号" width="140" />
|
||||||
|
|
||||||
|
<el-table-column prop="nickname" label="昵称" min-width="120" />
|
||||||
|
|
||||||
|
<el-table-column label="手机号" width="140">
|
||||||
|
<template #default="{ row }">{{ phoneDisplay(row.phone) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="性别" width="70" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.gender === 1 ? '' : row.gender === 2 ? 'danger' : 'info'" size="small">
|
||||||
|
{{ genderLabel(row.gender) }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="最近登录" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.lastLoginAt ? formatDate(row.lastLoginAt) : '从未登录' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="注册时间" width="170" sortable>
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.createdAt ? formatDate(row.createdAt, 'YYYY-MM-DD HH:mm') : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="操作" width="150" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="viewDetail(row.id)">详情</el-button>
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'business:member:edit'">编辑</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div style="margin-top: 16px; display: flex; justify-content: space-between; align-items: center">
|
||||||
|
<span style="color: var(--text-secondary); font-size: 13px">
|
||||||
|
共 {{ totalFiltered }} 条记录
|
||||||
|
</span>
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="currentPage"
|
||||||
|
:page-size="pageSize"
|
||||||
|
:total="totalFiltered"
|
||||||
|
layout="prev, pager, next, sizes"
|
||||||
|
:page-sizes="[8, 12, 20, 50]"
|
||||||
|
@size-change="(s: number) => { pageSize = s; currentPage = 1 }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Detail Dialog -->
|
||||||
|
<el-dialog v-model="detailVisible" title="会员详情" width="640px" @closed="detail = null">
|
||||||
|
<div v-loading="detailLoading" style="min-height: 200px">
|
||||||
|
<el-descriptions v-if="detail" :column="2" border>
|
||||||
|
<el-descriptions-item label="会员编号">{{ detail.memberNo || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="昵称">{{ detail.nickname || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="手机号">{{ detail.phone || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="性别">{{ detail.genderDesc || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="生日">{{ detail.birthday || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="关注状态">
|
||||||
|
<el-tag :type="detail.subscribed ? 'success' : 'info'" size="small">
|
||||||
|
{{ detail.subscribed ? '已关注' : '未关注' }}
|
||||||
|
</el-tag>
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="地址" :span="2">{{ detail.address || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="有效卡数量">{{ detail.activeCardCount ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="失效卡数量">{{ detail.inactiveCardCount ?? 0 }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="注册时间">
|
||||||
|
{{ detail.createdAt ? formatDate(detail.createdAt) : '-' }}
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="最近登录">
|
||||||
|
{{ detail.lastLoginAt ? formatDate(detail.lastLoginAt) : '-' }}
|
||||||
|
</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
<el-empty v-else-if="!detailLoading" description="暂未获取到会员信息" />
|
||||||
|
</div>
|
||||||
|
</el-dialog>
|
||||||
|
<!-- Edit Dialog -->
|
||||||
|
<el-dialog v-model="editVisible" title="编辑会员信息" width="520px" @closed="editForm.adminPassword = ''">
|
||||||
|
<el-form ref="editFormRef" :model="editForm" label-width="100px">
|
||||||
|
<el-form-item label="会员编号">
|
||||||
|
<el-input :model-value="editForm.memberNo" disabled />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="昵称" required>
|
||||||
|
<el-input v-model="editForm.nickname" placeholder="请输入昵称" maxlength="30" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="性别">
|
||||||
|
<el-select v-model="editForm.gender" placeholder="请选择" clearable style="width:100%">
|
||||||
|
<el-option label="男" :value="1" />
|
||||||
|
<el-option label="女" :value="2" />
|
||||||
|
<el-option label="未知" :value="0" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="生日">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="editForm.birthday"
|
||||||
|
type="date"
|
||||||
|
placeholder="请选择生日"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width:100%"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="地址">
|
||||||
|
<el-input v-model="editForm.address" placeholder="请输入地址" maxlength="100" />
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<el-divider content-position="left" style="margin: 8px 0 16px">
|
||||||
|
<span style="color: var(--el-color-danger); font-size: 13px">身份验证</span>
|
||||||
|
</el-divider>
|
||||||
|
|
||||||
|
<el-form-item label="管理员密码" required>
|
||||||
|
<el-input
|
||||||
|
v-model="editForm.adminPassword"
|
||||||
|
type="password"
|
||||||
|
placeholder="请输入当前管理员密码以确认修改"
|
||||||
|
show-password
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="editVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="editSaving" @click="doEdit">确认修改</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,441 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, computed, onMounted } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import {
|
||||||
|
listMemberCards,
|
||||||
|
createMemberCard,
|
||||||
|
updateMemberCard,
|
||||||
|
deleteMemberCard,
|
||||||
|
} from '@/api/modules/memberCard'
|
||||||
|
import { formatDate } from '@/utils/format'
|
||||||
|
|
||||||
|
interface CardItem {
|
||||||
|
id: number
|
||||||
|
memberCardId: number
|
||||||
|
memberCardName: string
|
||||||
|
memberCardType: string
|
||||||
|
memberCardPrice: number
|
||||||
|
memberCardValidityDays: number
|
||||||
|
memberCardTotalTimes: number
|
||||||
|
memberCardAmount: number
|
||||||
|
memberCardStatus: number
|
||||||
|
extraConfig: string | null
|
||||||
|
createdAt: string | null
|
||||||
|
updatedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- State ----
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<CardItem[]>([])
|
||||||
|
const total = ref(0)
|
||||||
|
|
||||||
|
// filters
|
||||||
|
const keyword = ref('')
|
||||||
|
const typeFilter = ref<string | null>(null)
|
||||||
|
const statusFilter = ref<number | null>(null)
|
||||||
|
const currentPage = ref(0)
|
||||||
|
const pageSize = ref(10)
|
||||||
|
|
||||||
|
const displayPage = computed({
|
||||||
|
get: () => currentPage.value + 1,
|
||||||
|
set: (val: number) => {
|
||||||
|
currentPage.value = val - 1
|
||||||
|
fetchData()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// dialogs
|
||||||
|
const createVisible = ref(false)
|
||||||
|
const editVisible = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
|
||||||
|
const createForm = reactive({
|
||||||
|
memberCardName: '',
|
||||||
|
memberCardType: '',
|
||||||
|
memberCardPrice: 0,
|
||||||
|
memberCardTotalTimes: 0,
|
||||||
|
memberCardValidityDays: 30,
|
||||||
|
memberCardAmount: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const editForm = reactive({
|
||||||
|
id: 0,
|
||||||
|
memberCardName: '',
|
||||||
|
memberCardType: '',
|
||||||
|
memberCardPrice: 0,
|
||||||
|
memberCardTotalTimes: 0,
|
||||||
|
memberCardValidityDays: 30,
|
||||||
|
memberCardAmount: 0,
|
||||||
|
memberCardStatus: 1,
|
||||||
|
adminPassword: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---- Computed ----
|
||||||
|
const typeLabel = (t: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
TIME_CARD: '时长卡',
|
||||||
|
COUNT_CARD: '次卡',
|
||||||
|
STORED_VALUE_CARD: '储值卡',
|
||||||
|
}
|
||||||
|
return map[t] ?? t
|
||||||
|
}
|
||||||
|
|
||||||
|
const typeTagEffect = (t: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
TIME_CARD: '',
|
||||||
|
COUNT_CARD: 'success',
|
||||||
|
STORED_VALUE_CARD: 'warning',
|
||||||
|
}
|
||||||
|
return map[t] ?? 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusLabel = (s: number) => (s === 1 ? '上架' : '下架')
|
||||||
|
|
||||||
|
// ---- Methods ----
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const params: any = {
|
||||||
|
page: currentPage.value,
|
||||||
|
size: pageSize.value,
|
||||||
|
}
|
||||||
|
if (keyword.value) params.name = keyword.value
|
||||||
|
if (typeFilter.value) params.type = typeFilter.value
|
||||||
|
if (statusFilter.value !== null) params.status = statusFilter.value
|
||||||
|
|
||||||
|
const res: any = await listMemberCards(params)
|
||||||
|
if (Array.isArray(res)) {
|
||||||
|
list.value = res
|
||||||
|
total.value = res.length
|
||||||
|
} else {
|
||||||
|
list.value = []
|
||||||
|
total.value = 0
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
list.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSearch() {
|
||||||
|
currentPage.value = 0
|
||||||
|
fetchData()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFilters() {
|
||||||
|
keyword.value = ''
|
||||||
|
typeFilter.value = null
|
||||||
|
statusFilter.value = null
|
||||||
|
currentPage.value = 0
|
||||||
|
fetchData()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Create ----
|
||||||
|
function openCreate() {
|
||||||
|
createForm.memberCardName = ''
|
||||||
|
createForm.memberCardType = ''
|
||||||
|
createForm.memberCardPrice = 0
|
||||||
|
createForm.memberCardTotalTimes = 0
|
||||||
|
createForm.memberCardValidityDays = 30
|
||||||
|
createForm.memberCardAmount = 0
|
||||||
|
createVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doCreate() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
await createMemberCard(createForm)
|
||||||
|
ElMessage.success('创建成功')
|
||||||
|
createVisible.value = false
|
||||||
|
fetchData()
|
||||||
|
} catch {
|
||||||
|
ElMessage.error('创建失败')
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Edit ----
|
||||||
|
function openEdit(row: CardItem) {
|
||||||
|
editForm.id = row.id || row.memberCardId
|
||||||
|
editForm.memberCardName = row.memberCardName || ''
|
||||||
|
editForm.memberCardType = row.memberCardType || ''
|
||||||
|
editForm.memberCardPrice = row.memberCardPrice ?? 0
|
||||||
|
editForm.memberCardTotalTimes = row.memberCardTotalTimes ?? 0
|
||||||
|
editForm.memberCardValidityDays = row.memberCardValidityDays ?? 30
|
||||||
|
editForm.memberCardAmount = row.memberCardAmount ?? 0
|
||||||
|
editForm.memberCardStatus = row.memberCardStatus ?? 1
|
||||||
|
editForm.adminPassword = ''
|
||||||
|
editVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doEdit() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
// strip adminPassword from body, pass as query param
|
||||||
|
const { adminPassword, ...body } = editForm
|
||||||
|
const res: any = await updateMemberCard(editForm.id, body, { adminPassword })
|
||||||
|
if (res && res.code && res.code >= 400) {
|
||||||
|
ElMessage.error(res.message || '修改失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ElMessage.success('修改成功')
|
||||||
|
editVisible.value = false
|
||||||
|
fetchData()
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data?.message || e?.message || '修改失败'
|
||||||
|
ElMessage.error(msg)
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Delete ----
|
||||||
|
async function doDelete(row: CardItem) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除会员卡"${row.memberCardName}"吗?`, '确认删除', {
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
const { value: adminPassword } = await ElMessageBox.prompt('请输入管理员密码以确认删除', '身份验证', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确认删除',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
inputValidator: (val) => (!val || !val.trim() ? '密码不能为空' : true),
|
||||||
|
})
|
||||||
|
const res: any = await deleteMemberCard(row.id || row.memberCardId, { adminPassword })
|
||||||
|
if (res && res.code && res.code >= 400) {
|
||||||
|
ElMessage.error(res.message || '删除失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ElMessage.success('已删除')
|
||||||
|
fetchData()
|
||||||
|
} catch {
|
||||||
|
// cancelled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom: 16px">会员卡管理</h2>
|
||||||
|
|
||||||
|
<!-- Stats -->
|
||||||
|
<el-row :gutter="16" style="margin-bottom: 16px">
|
||||||
|
<el-col :span="6" v-for="s in [
|
||||||
|
{ label: '上架卡种', value: list.filter(m => m.memberCardStatus === 1).length, color: '#52c41a' },
|
||||||
|
{ label: '下架卡种', value: list.filter(m => m.memberCardStatus !== 1).length, color: '#ff4d4f' },
|
||||||
|
{ label: '时长卡', value: list.filter(m => m.memberCardType === 'TIME_CARD').length, color: '#1890ff' },
|
||||||
|
{ label: '次卡', value: list.filter(m => m.memberCardType === 'COUNT_CARD').length, color: '#722ed1' },
|
||||||
|
]" :key="s.label">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div style="text-align: center">
|
||||||
|
<div style="font-size: 26px; font-weight: bold" :style="{ color: s.color }">
|
||||||
|
{{ s.value }}
|
||||||
|
</div>
|
||||||
|
<div style="color: var(--text-secondary); margin-top: 4px; font-size: 13px">{{ s.label }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Search -->
|
||||||
|
<el-card class="search-card">
|
||||||
|
<el-form inline>
|
||||||
|
<el-form-item label="关键词">
|
||||||
|
<el-input
|
||||||
|
v-model="keyword"
|
||||||
|
placeholder="卡片名称"
|
||||||
|
clearable
|
||||||
|
style="width: 200px"
|
||||||
|
@keyup.enter="handleSearch"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="类型">
|
||||||
|
<el-select v-model="typeFilter" placeholder="全部" clearable style="width: 120px">
|
||||||
|
<el-option label="时长卡" value="TIME_CARD" />
|
||||||
|
<el-option label="次卡" value="COUNT_CARD" />
|
||||||
|
<el-option label="储值卡" value="STORED_VALUE_CARD" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-select v-model="statusFilter" placeholder="全部" clearable style="width: 100px">
|
||||||
|
<el-option label="上架" :value="1" />
|
||||||
|
<el-option label="下架" :value="0" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="handleSearch">搜索</el-button>
|
||||||
|
<el-button @click="resetFilters">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<el-button type="primary" @click="openCreate" style="margin-top: 8px" v-permission="'business:memberCard:create'">
|
||||||
|
+ 新增会员卡类型
|
||||||
|
</el-button>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="list" v-loading="loading" stripe highlight-current-row>
|
||||||
|
<el-table-column type="index" label="#" width="50" />
|
||||||
|
|
||||||
|
<el-table-column prop="memberCardName" label="卡片名称" min-width="140" />
|
||||||
|
|
||||||
|
<el-table-column label="类型" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="typeTagEffect(row.memberCardType)" size="small">
|
||||||
|
{{ typeLabel(row.memberCardType) }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="价格" width="100" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.memberCardPrice != null ? '¥' + Number(row.memberCardPrice).toLocaleString() : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="有效期(天)" width="100" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.memberCardValidityDays ?? '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="总次数" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.memberCardTotalTimes ?? '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="储值面额" width="100" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.memberCardAmount != null ? '¥' + Number(row.memberCardAmount).toLocaleString() : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="状态" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.memberCardStatus === 1 ? 'success' : 'danger'" size="small">
|
||||||
|
{{ statusLabel(row.memberCardStatus) }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="创建时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.createdAt ? formatDate(row.createdAt, 'YYYY-MM-DD HH:mm') : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="操作" width="160" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'business:memberCard:edit'">编辑</el-button>
|
||||||
|
<el-button type="danger" link @click="doDelete(row)" v-permission="'business:memberCard:delete'">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div style="margin-top: 16px; display: flex; justify-content: space-between; align-items: center">
|
||||||
|
<span style="color: var(--text-secondary); font-size: 13px">
|
||||||
|
共 {{ list.length }} 条记录
|
||||||
|
</span>
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="displayPage"
|
||||||
|
:page-size="pageSize"
|
||||||
|
:total="total"
|
||||||
|
layout="prev, pager, next"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Create Dialog -->
|
||||||
|
<el-dialog v-model="createVisible" title="新增会员卡" width="520px">
|
||||||
|
<el-form :model="createForm" label-width="110px">
|
||||||
|
<el-form-item label="卡片名称" required>
|
||||||
|
<el-input v-model="createForm.memberCardName" placeholder="请输入卡片名称" maxlength="30" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="卡片类型" required>
|
||||||
|
<el-select v-model="createForm.memberCardType" placeholder="请选择" style="width: 100%">
|
||||||
|
<el-option label="时长卡" value="TIME_CARD" />
|
||||||
|
<el-option label="次卡" value="COUNT_CARD" />
|
||||||
|
<el-option label="储值卡" value="STORED_VALUE_CARD" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="价格" required>
|
||||||
|
<el-input-number v-model="createForm.memberCardPrice" :min="0" :precision="2" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="有效期(天)">
|
||||||
|
<el-input-number v-model="createForm.memberCardValidityDays" :min="1" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="总次数">
|
||||||
|
<el-input-number v-model="createForm.memberCardTotalTimes" :min="0" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="储值面额">
|
||||||
|
<el-input-number v-model="createForm.memberCardAmount" :min="0" :precision="2" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="createVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="doCreate">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- Edit Dialog -->
|
||||||
|
<el-dialog v-model="editVisible" title="编辑会员卡" width="520px" @closed="editForm.adminPassword = ''">
|
||||||
|
<el-form :model="editForm" label-width="110px">
|
||||||
|
<el-form-item label="卡片名称" required>
|
||||||
|
<el-input v-model="editForm.memberCardName" placeholder="请输入卡片名称" maxlength="30" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="卡片类型" required>
|
||||||
|
<el-select v-model="editForm.memberCardType" placeholder="请选择" style="width: 100%">
|
||||||
|
<el-option label="时长卡" value="TIME_CARD" />
|
||||||
|
<el-option label="次卡" value="COUNT_CARD" />
|
||||||
|
<el-option label="储值卡" value="STORED_VALUE_CARD" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="价格" required>
|
||||||
|
<el-input-number v-model="editForm.memberCardPrice" :min="0" :precision="2" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="有效期(天)">
|
||||||
|
<el-input-number v-model="editForm.memberCardValidityDays" :min="1" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="总次数">
|
||||||
|
<el-input-number v-model="editForm.memberCardTotalTimes" :min="0" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="储值面额">
|
||||||
|
<el-input-number v-model="editForm.memberCardAmount" :min="0" :precision="2" style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-switch
|
||||||
|
v-model="editForm.memberCardStatus"
|
||||||
|
:active-value="1"
|
||||||
|
:inactive-value="0"
|
||||||
|
active-text="上架"
|
||||||
|
inactive-text="下架"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<el-divider content-position="left" style="margin: 8px 0 16px">
|
||||||
|
<span style="color: var(--el-color-danger); font-size: 13px">身份验证</span>
|
||||||
|
</el-divider>
|
||||||
|
|
||||||
|
<el-form-item label="管理员密码" required>
|
||||||
|
<el-input
|
||||||
|
v-model="editForm.adminPassword"
|
||||||
|
type="password"
|
||||||
|
placeholder="请输入当前管理员密码以确认修改"
|
||||||
|
show-password
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="editVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="doEdit">保存</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted, computed } from 'vue'
|
||||||
|
import { getOperationLogsByPage, exportOperationLogs } from '@/api/modules/operationLog'
|
||||||
|
import { formatDate } from '@/utils/format'
|
||||||
|
import { download } from '@/api/request'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<any[]>([])
|
||||||
|
const total = ref(0)
|
||||||
|
|
||||||
|
const filters = reactive({
|
||||||
|
page: 0,
|
||||||
|
size: 10,
|
||||||
|
keyword: '',
|
||||||
|
username: '',
|
||||||
|
operation: '',
|
||||||
|
method: '',
|
||||||
|
status: '',
|
||||||
|
startTime: '',
|
||||||
|
endTime: '',
|
||||||
|
sort: 'createdAt',
|
||||||
|
order: 'desc',
|
||||||
|
})
|
||||||
|
|
||||||
|
const currentPage = computed({
|
||||||
|
get: () => filters.page + 1,
|
||||||
|
set: (val: number) => { filters.page = val - 1 }
|
||||||
|
})
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await getOperationLogsByPage(filters)
|
||||||
|
if (res?.content) {
|
||||||
|
list.value = res.content
|
||||||
|
total.value = res.totalElements || 0
|
||||||
|
} else if (Array.isArray(res)) {
|
||||||
|
list.value = res
|
||||||
|
total.value = res.length
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
list.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
Object.assign(filters, {
|
||||||
|
page: 0,
|
||||||
|
keyword: '',
|
||||||
|
username: '',
|
||||||
|
operation: '',
|
||||||
|
method: '',
|
||||||
|
status: '',
|
||||||
|
startTime: '',
|
||||||
|
endTime: '',
|
||||||
|
})
|
||||||
|
fetchData()
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePageChange(page: number) {
|
||||||
|
filters.page = page - 1
|
||||||
|
fetchData()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleExport() {
|
||||||
|
try {
|
||||||
|
await download('/api/logs/operation/export', filters, '操作日志.xlsx')
|
||||||
|
ElMessage.success('导出成功')
|
||||||
|
} catch {
|
||||||
|
ElMessage.error('导出失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDuration(ms: number | null) {
|
||||||
|
if (ms == null) return '-'
|
||||||
|
if (ms < 1000) return ms + 'ms'
|
||||||
|
return (ms / 1000).toFixed(2) + 's'
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { fetchData() })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom:16px">操作日志</h2>
|
||||||
|
|
||||||
|
<!-- Filter -->
|
||||||
|
<el-card class="search-card" shadow="never">
|
||||||
|
<el-form :model="filters" inline>
|
||||||
|
<el-form-item label="操作人">
|
||||||
|
<el-input v-model="filters.username" placeholder="用户名" clearable style="width:140px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="操作">
|
||||||
|
<el-input v-model="filters.operation" placeholder="操作描述" clearable style="width:160px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="请求方式">
|
||||||
|
<el-input v-model="filters.method" placeholder="GET /api/..." clearable style="width:180px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-select v-model="filters.status" placeholder="全部" clearable style="width:100px">
|
||||||
|
<el-option label="成功" value="0" />
|
||||||
|
<el-option label="失败" value="1" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="开始时间">
|
||||||
|
<el-date-picker v-model="filters.startTime" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="开始" style="width:180px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="结束时间">
|
||||||
|
<el-date-picker v-model="filters.endTime" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="结束" style="width:180px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="fetchData">查询</el-button>
|
||||||
|
<el-button @click="handleReset">重置</el-button>
|
||||||
|
<el-button @click="handleExport">导出日志</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<el-card shadow="never">
|
||||||
|
<el-table :data="list" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||||
|
<el-table-column prop="username" label="操作人" width="110" />
|
||||||
|
<el-table-column prop="operation" label="操作" width="180" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="method" label="请求地址" min-width="240" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="ip" label="IP" width="140" />
|
||||||
|
<el-table-column label="状态" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.status === '0' ? 'success' : 'danger'" size="small">
|
||||||
|
{{ row.status === '0' ? '成功' : '失败' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="耗时" width="80" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatDuration(row.duration) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="时间" width="170" align="center">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.createdAt ? formatDate(row.createdAt) : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div v-if="list.length === 0 && !loading" style="color:#909399;font-size:13px;text-align:center;padding:60px">
|
||||||
|
暂无操作日志
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:16px;text-align:right" v-if="total > 0">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="currentPage"
|
||||||
|
:page-size="filters.size"
|
||||||
|
:total="total"
|
||||||
|
layout="prev,pager,next,total"
|
||||||
|
@current-change="handlePageChange"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.search-card {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,427 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted, computed } from 'vue'
|
||||||
|
import { getRolesByPage, createRole, updateRole, deleteRole, getRolePermissions, assignPermissionsToRole, getAllPermissions } from '@/api/modules/role'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const list = ref<any[]>([])
|
||||||
|
const total = ref(0)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const permVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const editId = ref<number | null>(null)
|
||||||
|
const allPermissions = ref<any[]>([])
|
||||||
|
const selectedPermIds = ref<number[]>([])
|
||||||
|
const systemCollapsed = ref(true)
|
||||||
|
const collapsedGroups = ref<Record<string, boolean>>({})
|
||||||
|
|
||||||
|
// 内置超级管理员角色(id=1: '超级管理员', roleKey='admin')
|
||||||
|
const isBuiltinRole = (row: any) => row?.id === 1
|
||||||
|
|
||||||
|
function toggleGroup(label: string) {
|
||||||
|
collapsedGroups.value[label] = !collapsedGroups.value[label]
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleGroupAll(group: { label: string; items: any[] }) {
|
||||||
|
const ids = group.items.map((p: any) => p.id)
|
||||||
|
const allSelected = ids.every((id: number) => selectedPermIds.value.includes(id))
|
||||||
|
if (allSelected) {
|
||||||
|
selectedPermIds.value = selectedPermIds.value.filter((id: number) => !ids.includes(id))
|
||||||
|
} else {
|
||||||
|
const toAdd = ids.filter((id: number) => !selectedPermIds.value.includes(id))
|
||||||
|
selectedPermIds.value = [...selectedPermIds.value, ...toAdd]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isGroupAllSelected(group: { items: any[] }) {
|
||||||
|
if (group.items.length === 0) return false
|
||||||
|
return group.items.every((p: any) => selectedPermIds.value.includes(p.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
function isGroupPartialSelected(group: { items: any[] }) {
|
||||||
|
if (group.items.length === 0) return false
|
||||||
|
const some = group.items.some((p: any) => selectedPermIds.value.includes(p.id))
|
||||||
|
return some && !isGroupAllSelected(group)
|
||||||
|
}
|
||||||
|
|
||||||
|
const permCategories: { label: string; prefix: string }[] = [
|
||||||
|
{ label: '会员管理', prefix: 'business:member:' },
|
||||||
|
{ label: '会员卡管理', prefix: 'business:memberCard:' },
|
||||||
|
{ label: '团课管理', prefix: 'business:groupCourse:' },
|
||||||
|
{ label: '团课类型管理', prefix: 'business:groupCourseType:' },
|
||||||
|
{ label: '团课推荐管理', prefix: 'business:groupCourseRecommend:' },
|
||||||
|
{ label: '团课预约管理', prefix: 'business:groupCourseBooking:' },
|
||||||
|
{ label: '签到管理', prefix: 'business:checkIn:' },
|
||||||
|
{ label: '数据统计', prefix: 'business:dataCount:' },
|
||||||
|
{ label: '员工管理', prefix: 'business:employee:' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const systemPermCategories: { label: string; prefix: string }[] = [
|
||||||
|
{ label: '用户管理', prefix: 'system:user:' },
|
||||||
|
{ label: '角色管理', prefix: 'system:role:' },
|
||||||
|
{ label: '权限管理', prefix: 'system:permission:' },
|
||||||
|
{ label: '菜单管理', prefix: 'system:menu:' },
|
||||||
|
{ label: '字典管理', prefix: 'system:dict:' },
|
||||||
|
{ label: '配置管理', prefix: 'system:config:' },
|
||||||
|
{ label: '日志管理', prefix: 'system:log:' },
|
||||||
|
{ label: '文件管理', prefix: 'system:file:' },
|
||||||
|
{ label: '公告管理', prefix: 'system:notice:' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const businessPerms = computed(() => {
|
||||||
|
return permCategories.map(cat => ({
|
||||||
|
label: cat.label,
|
||||||
|
items: allPermissions.value.filter((p: any) => p.permissionCode?.startsWith(cat.prefix)),
|
||||||
|
})).filter(g => g.items.length > 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
const systemPerms = computed(() => {
|
||||||
|
return systemPermCategories.map(cat => ({
|
||||||
|
label: cat.label,
|
||||||
|
items: allPermissions.value.filter((p: any) => p.permissionCode?.startsWith(cat.prefix)),
|
||||||
|
})).filter(g => g.items.length > 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
const page = reactive({ page: 0, size: 10, sort: 'id', order: 'asc' })
|
||||||
|
const currentPage = computed({
|
||||||
|
get: () => page.page + 1,
|
||||||
|
set: (val: number) => { page.page = val - 1 }
|
||||||
|
})
|
||||||
|
const form = reactive({ roleName: '', roleKey: '', roleSort: 0, status: 1 })
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await getRolesByPage(page)
|
||||||
|
if (res?.content) { list.value = res.content; total.value = res.totalElements || 0 }
|
||||||
|
else if (Array.isArray(res)) { list.value = res; total.value = res.length }
|
||||||
|
} catch { list.value = [] } finally { loading.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(row: any) {
|
||||||
|
if (isBuiltinRole(row)) {
|
||||||
|
ElMessage.warning('超级管理员角色不可删除')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认删除', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
}).catch(() => {})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await deleteRole(row.id, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
fetchData()
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data || e?.message || '删除失败'
|
||||||
|
ElMessage.error(typeof msg === 'string' ? msg : '删除失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
isEdit.value = false
|
||||||
|
editId.value = null
|
||||||
|
Object.assign(form, { roleName: '', roleKey: '', roleSort: 0, status: 1 })
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: any) {
|
||||||
|
if (isBuiltinRole(row)) {
|
||||||
|
ElMessage.warning('超级管理员角色不可编辑')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isEdit.value = true
|
||||||
|
editId.value = row.id
|
||||||
|
Object.assign(form, row)
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSave() {
|
||||||
|
if (isEdit.value && isBuiltinRole(form)) {
|
||||||
|
ElMessage.warning('超级管理员角色不可编辑')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (isEdit.value) {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认编辑', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
}).catch(() => {})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await updateRole(editId.value!, form, { params: { adminPassword: pwd } })
|
||||||
|
} else {
|
||||||
|
await createRole(form)
|
||||||
|
}
|
||||||
|
ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
|
||||||
|
dialogVisible.value = false
|
||||||
|
fetchData()
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data || e?.message || '操作失败'
|
||||||
|
ElMessage.error(typeof msg === 'string' ? msg : '操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAssignPerms(row: any) {
|
||||||
|
if (isBuiltinRole(row)) {
|
||||||
|
ElMessage.warning('超级管理员角色的权限不可被修改')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const perms = await getAllPermissions()
|
||||||
|
allPermissions.value = Array.isArray(perms) ? perms : []
|
||||||
|
try {
|
||||||
|
const rolePerms = await getRolePermissions(row.id)
|
||||||
|
selectedPermIds.value = Array.isArray(rolePerms) ? rolePerms.map((p: any) => p.id) : []
|
||||||
|
} catch { selectedPermIds.value = [] }
|
||||||
|
editId.value = row.id
|
||||||
|
permVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAssignPerms() {
|
||||||
|
const { value: pwd } = await ElMessageBox.prompt('请输入管理员密码以确认分配权限', '验证密码', {
|
||||||
|
inputType: 'password',
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
}).catch(() => {})
|
||||||
|
if (!pwd) {
|
||||||
|
ElMessage.warning('请输入验证密码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await assignPermissionsToRole(editId.value!, selectedPermIds.value, { params: { adminPassword: pwd } })
|
||||||
|
ElMessage.success('分配成功')
|
||||||
|
permVisible.value = false
|
||||||
|
} catch (e: any) {
|
||||||
|
const msg = e?.response?.data || e?.message || '分配失败'
|
||||||
|
ElMessage.error(typeof msg === 'string' ? msg : '分配失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => fetchData())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 style="margin-bottom:16px">角色管理</h2>
|
||||||
|
<el-card class="search-card"><el-button type="primary" @click="openCreate" v-permission="'system:role:create'">新增角色</el-button></el-card>
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="list" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||||
|
<el-table-column label="角色信息" min-width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div style="display:flex;align-items:center;gap:8px">
|
||||||
|
<span style="font-weight:500">{{ row.roleName }}</span>
|
||||||
|
<span v-if="isBuiltinRole(row)" style="font-size:12px;color:#e6a23c">★ 内置</span>
|
||||||
|
<el-tag v-if="isBuiltinRole(row)" type="warning" size="small" effect="dark" style="margin-left:auto">内置</el-tag>
|
||||||
|
</div>
|
||||||
|
<div style="font-size:12px;color:#909399;margin-top:2px;font-family:monospace">{{ row.roleKey }}</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="roleSort" label="排序" width="70" align="center" />
|
||||||
|
<el-table-column label="状态" width="80" align="center">
|
||||||
|
<template #default="{ row }"><el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">{{ row.status === 1 ? '启用' : '禁用' }}</el-tag></template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="240" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="openEdit(row)" v-permission="'system:role:edit'">编辑</el-button>
|
||||||
|
<el-button type="primary" link @click="openAssignPerms(row)" v-permission="'system:role:assign'">分配权限</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)" v-permission="'system:role:delete'">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div style="margin-top:16px;text-align:right">
|
||||||
|
<el-pagination v-model:current-page="currentPage" :page-size="page.size" :total="total" layout="prev,pager,next,total" @current-change="fetchData" />
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-dialog v-model="dialogVisible" :title="isEdit ? '编辑角色' : '新增角色'" width="500px" :close-on-click-modal="false">
|
||||||
|
<el-form :model="form" label-width="90px">
|
||||||
|
<el-form-item label="角色名称"><el-input v-model="form.roleName" placeholder="请输入角色名称" /></el-form-item>
|
||||||
|
<el-form-item label="角色标识"><el-input v-model="form.roleKey" placeholder="如: admin" /></el-form-item>
|
||||||
|
<el-form-item label="排序"><el-input-number v-model="form.roleSort" :min="0" style="width:100%" /></el-form-item>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSave">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<el-dialog v-model="permVisible" title="分配权限" width="720px" :close-on-click-modal="false">
|
||||||
|
<div v-if="allPermissions.length === 0" style="color:#909399;text-align:center;padding:40px">暂无可用权限</div>
|
||||||
|
<template v-else>
|
||||||
|
<!-- 业务权限 -->
|
||||||
|
<div style="font-weight:600;font-size:14px;color:#303133;margin-bottom:12px">业务权限</div>
|
||||||
|
<el-checkbox-group v-model="selectedPermIds">
|
||||||
|
<div class="perm-scroll" style="max-height:320px;overflow-y:auto;padding-right:4px;margin-bottom:16px">
|
||||||
|
<div v-for="group in businessPerms" :key="group.label" class="perm-group">
|
||||||
|
<div class="perm-group-header" @click="toggleGroup(group.label)">
|
||||||
|
<span class="perm-group-arrow" :class="{ expanded: !collapsedGroups[group.label] }">▶</span>
|
||||||
|
<span class="perm-group-label">{{ group.label }}</span>
|
||||||
|
<span class="perm-group-count">{{ group.items.length }}</span>
|
||||||
|
<span class="perm-group-toggle" @click.stop="toggleGroupAll(group)">
|
||||||
|
{{ isGroupAllSelected(group) ? '取消全选' : '全选' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div v-show="!collapsedGroups[group.label]">
|
||||||
|
<div
|
||||||
|
v-for="perm in group.items" :key="perm.id"
|
||||||
|
class="perm-item"
|
||||||
|
>
|
||||||
|
<el-checkbox :label="perm.id" />
|
||||||
|
<span class="perm-name">{{ perm.permissionName }}</span>
|
||||||
|
<span class="perm-code">{{ perm.permissionCode }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-checkbox-group>
|
||||||
|
|
||||||
|
<!-- 系统权限 -->
|
||||||
|
<div
|
||||||
|
class="perm-system-header"
|
||||||
|
@click="systemCollapsed = !systemCollapsed"
|
||||||
|
>
|
||||||
|
<span class="perm-group-arrow" :class="{ expanded: !systemCollapsed }">▶</span>
|
||||||
|
<span style="font-weight:600;font-size:14px;color:#303133">系统权限</span>
|
||||||
|
<span style="font-size:12px;color:#c0c4cc;margin-left:6px">非业务相关,谨慎分配</span>
|
||||||
|
</div>
|
||||||
|
<div v-show="!systemCollapsed" class="perm-scroll" style="max-height:240px;overflow-y:auto;padding-right:4px">
|
||||||
|
<el-checkbox-group v-model="selectedPermIds">
|
||||||
|
<div v-for="group in systemPerms" :key="group.label" class="perm-group">
|
||||||
|
<div class="perm-group-header" @click="toggleGroup(group.label)">
|
||||||
|
<span class="perm-group-arrow" :class="{ expanded: !collapsedGroups[group.label] }">▶</span>
|
||||||
|
<span class="perm-group-label">{{ group.label }}</span>
|
||||||
|
<span class="perm-group-count">{{ group.items.length }}</span>
|
||||||
|
<span class="perm-group-toggle" @click.stop="toggleGroupAll(group)">
|
||||||
|
{{ isGroupAllSelected(group) ? '取消全选' : '全选' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div v-show="!collapsedGroups[group.label]">
|
||||||
|
<div
|
||||||
|
v-for="perm in group.items" :key="perm.id"
|
||||||
|
class="perm-item"
|
||||||
|
>
|
||||||
|
<el-checkbox :label="perm.id" />
|
||||||
|
<span class="perm-name">{{ perm.permissionName }}</span>
|
||||||
|
<span class="perm-code">{{ perm.permissionCode }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-checkbox-group>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="permVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleAssignPerms">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.search-card { margin-bottom: 16px; }
|
||||||
|
|
||||||
|
/* 权限弹窗 */
|
||||||
|
.perm-group {
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
.perm-group-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 7px 10px;
|
||||||
|
background: #f5f7fa;
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.perm-group-header:hover {
|
||||||
|
background: #ebeef5;
|
||||||
|
}
|
||||||
|
.perm-group-arrow {
|
||||||
|
font-size: 10px;
|
||||||
|
color: #909399;
|
||||||
|
transition: transform 0.2s;
|
||||||
|
display: inline-block;
|
||||||
|
width: 12px;
|
||||||
|
}
|
||||||
|
.perm-group-arrow.expanded {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
}
|
||||||
|
.perm-group-label {
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
.perm-group-count {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #c0c4cc;
|
||||||
|
background: #e9ecf1;
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 0 7px;
|
||||||
|
line-height: 18px;
|
||||||
|
}
|
||||||
|
.perm-group-toggle {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #409eff;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
.perm-group-toggle:hover {
|
||||||
|
color: #66b1ff;
|
||||||
|
}
|
||||||
|
.perm-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 5px 10px 5px 28px;
|
||||||
|
border-bottom: 1px solid #f5f5f5;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.perm-item:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
.perm-name {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
.perm-code {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #909399;
|
||||||
|
font-family: 'SF Mono', 'Menlo', 'Consolas', monospace;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
.perm-system-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
background: #fdf6ec;
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
.perm-system-header:hover {
|
||||||
|
background: #faead7;
|
||||||
|
}
|
||||||
|
.perm-scroll::-webkit-scrollbar {
|
||||||
|
width: 5px;
|
||||||
|
}
|
||||||
|
.perm-scroll::-webkit-scrollbar-thumb {
|
||||||
|
background: #dcdfe6;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||||
|
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||||
|
"exclude": ["src/**/__tests__/*"],
|
||||||
|
"compilerOptions": {
|
||||||
|
// Extra safety for array and object lookups, but may have false positives.
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
|
||||||
|
// Path mapping for cleaner imports.
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
},
|
||||||
|
|
||||||
|
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||||
|
// Specified here to keep it out of the root directory.
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.node.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.app.json"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
|
||||||
|
{
|
||||||
|
"extends": "@tsconfig/node24/tsconfig.json",
|
||||||
|
"include": [
|
||||||
|
"vite.config.*",
|
||||||
|
"vitest.config.*",
|
||||||
|
"cypress.config.*",
|
||||||
|
"playwright.config.*",
|
||||||
|
"eslint.config.*"
|
||||||
|
],
|
||||||
|
"compilerOptions": {
|
||||||
|
// Most tools use transpilation instead of Node.js's native type-stripping.
|
||||||
|
// Bundler mode provides a smoother developer experience.
|
||||||
|
"module": "preserve",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
|
||||||
|
// Include Node.js types and avoid accidentally including other `@types/*` packages.
|
||||||
|
"types": ["node"],
|
||||||
|
|
||||||
|
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||||
|
// Specified here to keep it out of the root directory.
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { fileURLToPath, URL } from 'node:url'
|
||||||
|
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import vueDevTools from 'vite-plugin-vue-devtools'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [
|
||||||
|
vue(),
|
||||||
|
vueDevTools(),
|
||||||
|
],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:8084',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
AccessKey ID
|
||||||
|
LTAI5t9wHCiH68Xjxg64Xx4Y
|
||||||
|
|
||||||
|
AccessKey Secret
|
||||||
|
isAfz1IFGAnV13LOIrVg19aPhY8aRq
|
||||||
Reference in New Issue
Block a user