Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf7e2560b5 | ||
|
|
fa94f52b53 | ||
|
|
566e949588 | ||
|
|
e61fa6de00 | ||
|
|
f1614c7d45 | ||
|
|
886e2748d5 | ||
|
|
1a5aa9b3ef | ||
|
|
0140bb0cc8 |
+43
@@ -194,4 +194,47 @@ public class CheckInHandler {
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.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")
|
||||
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
|
||||
*/
|
||||
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.util.RedisUtil;
|
||||
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.MemberCardRecord;
|
||||
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.MemberCardRecordRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -47,6 +49,7 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
private final MemberCardRepository memberCardRepository;
|
||||
private final SignInRecordRepository signInRecordRepository;
|
||||
private final IGroupCourseBookingService groupCourseBookingService;
|
||||
private final IMemberRepository memberRepository;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@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() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
||||
|
||||
+10
@@ -59,6 +59,16 @@ public class SignInRecordVO {
|
||||
*/
|
||||
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) {
|
||||
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("endTime", endTime)
|
||||
.map(row -> row.get(0, Long.class))
|
||||
@@ -37,7 +37,7 @@ public class DataStatisticsDao {
|
||||
* 统计总会员数
|
||||
*/
|
||||
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))
|
||||
.one();
|
||||
}
|
||||
|
||||
+5
@@ -4,6 +4,8 @@ import cn.novalon.gym.manage.datacount.domain.*;
|
||||
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -25,6 +27,8 @@ import java.time.format.DateTimeFormatter;
|
||||
@Tag(name = "数据统计", description = "数据统计相关操作")
|
||||
public class DataStatisticsHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DataStatisticsHandler.class);
|
||||
|
||||
@Autowired
|
||||
private IDataStatisticsService dataStatisticsService;
|
||||
|
||||
@@ -35,6 +39,7 @@ public class DataStatisticsHandler {
|
||||
return dataStatisticsService.getStatisticsSummaryWithCache(query)
|
||||
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
||||
.onErrorResume(e -> {
|
||||
log.error("获取综合统计数据失败", e);
|
||||
StatisticsSummary errorSummary = StatisticsSummary.builder()
|
||||
.statDate(LocalDateTime.now().toLocalDate().toString())
|
||||
.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.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -22,7 +23,9 @@ import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -173,9 +176,25 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
||||
|
||||
@Override
|
||||
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
|
||||
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query);
|
||||
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query);
|
||||
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query);
|
||||
String statDate = query.getStartTime() != null
|
||||
? query.getStartTime().toLocalDate().toString()
|
||||
: 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)
|
||||
.map(tuple -> StatisticsSummary.builder()
|
||||
@@ -188,21 +207,75 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public reactor.core.publisher.Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
||||
public Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
||||
// 历史统计数据查询(从Redis缓存中获取)
|
||||
String cacheKey = buildCacheKey(query);
|
||||
return redisUtil.get(cacheKey, String.class)
|
||||
.flatMapMany(json -> {
|
||||
try {
|
||||
java.util.List<DataStatistics> stats = objectMapper.readValue(json,
|
||||
objectMapper.getTypeFactory().constructCollectionType(java.util.List.class, DataStatistics.class));
|
||||
return reactor.core.publisher.Flux.fromIterable(stats);
|
||||
List<DataStatistics> stats = objectMapper.readValue(json,
|
||||
objectMapper.getTypeFactory().constructCollectionType(List.class, DataStatistics.class));
|
||||
return Flux.fromIterable(stats);
|
||||
} catch (Exception 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
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package cn.novalon.gym.manage.groupcourse.dao;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.entity.BannerEntity;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
import org.springframework.data.r2dbc.repository.Query;
|
||||
import org.springframework.data.r2dbc.repository.R2dbcRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Repository
|
||||
public interface BannerDao extends R2dbcRepository<BannerEntity, Long> {
|
||||
|
||||
Mono<BannerEntity> findByIdAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<BannerEntity> findAllByDeletedAtIsNull();
|
||||
|
||||
Flux<BannerEntity> findAllByDeletedAtIsNull(Sort sort);
|
||||
|
||||
Flux<BannerEntity> findByIsActiveTrueAndDeletedAtIsNull();
|
||||
|
||||
Flux<BannerEntity> findByIsActiveTrueAndDeletedAtIsNull(Sort sort);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE banner SET is_active = :isActive, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||
Mono<Integer> updateActiveStatus(Long id, Boolean isActive, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE banner SET deleted_at = :deletedAt WHERE id = :id")
|
||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||
}
|
||||
+24
@@ -40,10 +40,18 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
|
||||
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
|
||||
@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);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_course SET status = '0', current_members = 0, start_time = start_time + INTERVAL '7 days', end_time = end_time + INTERVAL '7 days', updated_at = :updatedAt WHERE is_recurring = TRUE AND status = '2' AND end_time <= NOW() AND deleted_at IS NULL")
|
||||
Mono<Integer> renewRecurringCourses(LocalDateTime updatedAt);
|
||||
|
||||
Flux<GroupCourseEntity> findByCourseTypeAndDeletedAtIsNull(Long courseType);
|
||||
|
||||
/**
|
||||
@@ -92,6 +100,11 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 常态化团课筛选
|
||||
if (query.getIsRecurring() != null) {
|
||||
conditions.add("is_recurring = :isRecurring");
|
||||
}
|
||||
|
||||
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||
|
||||
// 5. 价格排序 / 6. 剩余名额最多排序
|
||||
@@ -141,6 +154,9 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
if (query.getEndDate() != null) {
|
||||
spec = spec.bind("endDate", query.getEndDate());
|
||||
}
|
||||
if (query.getIsRecurring() != null) {
|
||||
spec = spec.bind("isRecurring", query.getIsRecurring());
|
||||
}
|
||||
spec = spec.bind("limit", size);
|
||||
spec = spec.bind("offset", offset);
|
||||
|
||||
@@ -165,6 +181,7 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
entity.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||
entity.setUpdatedAt(row.get("updated_at", LocalDateTime.class));
|
||||
entity.setDeletedAt(row.get("deleted_at", LocalDateTime.class));
|
||||
entity.setIsRecurring(row.get("is_recurring", Boolean.class));
|
||||
return entity;
|
||||
}).all();
|
||||
}
|
||||
@@ -207,6 +224,10 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
}
|
||||
}
|
||||
|
||||
if (query.getIsRecurring() != null) {
|
||||
conditions.add("is_recurring = :isRecurring");
|
||||
}
|
||||
|
||||
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||
|
||||
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||
@@ -223,6 +244,9 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
if (query.getEndDate() != null) {
|
||||
spec = spec.bind("endDate", query.getEndDate());
|
||||
}
|
||||
if (query.getIsRecurring() != null) {
|
||||
spec = spec.bind("isRecurring", query.getIsRecurring());
|
||||
}
|
||||
|
||||
return spec.map((row, meta) -> row.get(0, Long.class)).one();
|
||||
}
|
||||
|
||||
+4
@@ -29,4 +29,8 @@ public interface GroupCourseTypeDao extends R2dbcRepository<GroupCourseTypeEntit
|
||||
@Modifying
|
||||
@Query("UPDATE group_course_type SET deleted_at = :deletedAt WHERE id = :id")
|
||||
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);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package cn.novalon.gym.manage.groupcourse.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
public class Banner extends BaseDomain {
|
||||
|
||||
@Schema(description = "背景图URL", example = "https://example.com/banner.jpg")
|
||||
private String imageUrl;
|
||||
|
||||
@Schema(description = "主标题", example = "突破自我")
|
||||
private String title;
|
||||
|
||||
@Schema(description = "副标题", example = "超越极限")
|
||||
private String subtitle;
|
||||
|
||||
@Schema(description = "简介", example = "科学训练 · 遇见更好的自己")
|
||||
private String description;
|
||||
|
||||
@Schema(description = "排序(数值越大越靠前)", example = "10")
|
||||
private Integer sortOrder;
|
||||
|
||||
@Schema(description = "是否启用", example = "true")
|
||||
private Boolean isActive;
|
||||
|
||||
public String getImageUrl() { return imageUrl; }
|
||||
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
|
||||
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
|
||||
public String getSubtitle() { return subtitle; }
|
||||
public void setSubtitle(String subtitle) { this.subtitle = subtitle; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
|
||||
|
||||
public Boolean getIsActive() { return isActive; }
|
||||
public void setIsActive(Boolean isActive) { this.isActive = isActive; }
|
||||
}
|
||||
+12
@@ -60,6 +60,10 @@ public class GroupCourse extends BaseDomain{
|
||||
@Schema(description = "二维码路径", example = "D:\\Games\\exmp\\image\\abc123_20260618120000.png")
|
||||
private String qrCodePath;
|
||||
|
||||
//是否常态化团课
|
||||
@Schema(description = "是否常态化团课", example = "true")
|
||||
private Boolean isRecurring;
|
||||
|
||||
public String getCourseName() {
|
||||
return courseName;
|
||||
}
|
||||
@@ -163,4 +167,12 @@ public class GroupCourse extends BaseDomain{
|
||||
public void setQrCodePath(String qrCodePath) {
|
||||
this.qrCodePath = qrCodePath;
|
||||
}
|
||||
|
||||
public Boolean getIsRecurring() {
|
||||
return isRecurring;
|
||||
}
|
||||
|
||||
public void setIsRecurring(Boolean isRecurring) {
|
||||
this.isRecurring = isRecurring;
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -40,6 +40,9 @@ public class GroupCourseQueryDto {
|
||||
@Schema(description = "每页大小", example = "10")
|
||||
private Integer size = 10;
|
||||
|
||||
@Schema(description = "是否常态化团课筛选:null-不过滤, true-仅常态化, false-仅非常态化", example = "true")
|
||||
private Boolean isRecurring;
|
||||
|
||||
// ===== Getters and Setters =====
|
||||
|
||||
public String getCourseName() {
|
||||
@@ -113,4 +116,12 @@ public class GroupCourseQueryDto {
|
||||
public void setSize(Integer size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public Boolean getIsRecurring() {
|
||||
return isRecurring;
|
||||
}
|
||||
|
||||
public void setIsRecurring(Boolean isRecurring) {
|
||||
this.isRecurring = isRecurring;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package cn.novalon.gym.manage.groupcourse.entity;
|
||||
|
||||
import cn.novalon.gym.manage.db.entity.BaseEntity;
|
||||
import org.springframework.data.relational.core.mapping.Column;
|
||||
import org.springframework.data.relational.core.mapping.Table;
|
||||
|
||||
@Table("banner")
|
||||
public class BannerEntity extends BaseEntity {
|
||||
|
||||
@Column("image_url")
|
||||
private String imageUrl;
|
||||
|
||||
@Column("title")
|
||||
private String title;
|
||||
|
||||
@Column("subtitle")
|
||||
private String subtitle;
|
||||
|
||||
@Column("description")
|
||||
private String description;
|
||||
|
||||
@Column("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@Column("is_active")
|
||||
private Boolean isActive;
|
||||
|
||||
public String getImageUrl() { return imageUrl; }
|
||||
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
|
||||
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
|
||||
public String getSubtitle() { return subtitle; }
|
||||
public void setSubtitle(String subtitle) { this.subtitle = subtitle; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
|
||||
|
||||
public Boolean getIsActive() { return isActive; }
|
||||
public void setIsActive(Boolean isActive) { this.isActive = isActive; }
|
||||
}
|
||||
+12
@@ -62,6 +62,10 @@ public class GroupCourseEntity extends BaseEntity {
|
||||
@Column("qr_code_path")
|
||||
private String qrCodePath;
|
||||
|
||||
//是否常态化团课
|
||||
@Column("is_recurring")
|
||||
private Boolean isRecurring;
|
||||
|
||||
public String getCourseName() {
|
||||
return courseName;
|
||||
}
|
||||
@@ -165,4 +169,12 @@ public class GroupCourseEntity extends BaseEntity {
|
||||
public void setQrCodePath(String qrCodePath) {
|
||||
this.qrCodePath = qrCodePath;
|
||||
}
|
||||
|
||||
public Boolean getIsRecurring() {
|
||||
return isRecurring;
|
||||
}
|
||||
|
||||
public void setIsRecurring(Boolean isRecurring) {
|
||||
this.isRecurring = isRecurring;
|
||||
}
|
||||
}
|
||||
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package cn.novalon.gym.manage.groupcourse.handler;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.domain.Banner;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IBannerService;
|
||||
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.tags.Tag;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@Tag(name = "轮播图管理", description = "轮播图相关操作")
|
||||
public class BannerHandler {
|
||||
|
||||
private final IBannerService bannerService;
|
||||
private final ISysUserService sysUserService;
|
||||
private final AuthUtil authUtil;
|
||||
|
||||
public BannerHandler(IBannerService bannerService,
|
||||
ISysUserService sysUserService,
|
||||
AuthUtil authUtil) {
|
||||
this.bannerService = bannerService;
|
||||
this.sysUserService = sysUserService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有轮播图", description = "获取系统中所有轮播图列表,支持按排序字段排序")
|
||||
public Mono<ServerResponse> getAllBanners(ServerRequest request) {
|
||||
String sortBy = request.queryParam("sortBy").orElse("sortOrder");
|
||||
String sortOrder = request.queryParam("sortOrder").orElse("desc");
|
||||
|
||||
return ServerResponse.ok()
|
||||
.body(bannerService.findAll(sortBy, sortOrder), Banner.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有启用的轮播图", description = "获取系统中所有已启用的轮播图列表")
|
||||
public Mono<ServerResponse> getAllActiveBanners(ServerRequest request) {
|
||||
return ServerResponse.ok()
|
||||
.body(bannerService.findAllActive(), Banner.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "根据ID获取轮播图", description = "根据ID获取轮播图详情")
|
||||
public Mono<ServerResponse> getBannerById(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return bannerService.findById(id)
|
||||
.flatMap(banner -> ServerResponse.ok().bodyValue(banner))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
}
|
||||
|
||||
@Operation(summary = "创建轮播图", description = "创建新的轮播图记录")
|
||||
public Mono<ServerResponse> createBanner(ServerRequest request) {
|
||||
return request.bodyToMono(Banner.class)
|
||||
.flatMap(banner -> {
|
||||
if (banner.getImageUrl() == null || banner.getImageUrl().isBlank()) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "背景图不能为空");
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
if (banner.getTitle() == null || banner.getTitle().isBlank()) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "主标题不能为空");
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
|
||||
return bannerService.create(banner)
|
||||
.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> updateBanner(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 request.bodyToMono(Banner.class)
|
||||
.flatMap(banner -> bannerService.update(id, banner)
|
||||
.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> deleteBanner(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 bannerService.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> enableBanner(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
|
||||
return bannerService.enable(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);
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "禁用轮播图", description = "禁用指定轮播图,需验证管理员密码")
|
||||
public Mono<ServerResponse> disableBanner(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 bannerService.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);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
+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)
|
||||
.flatMap(body -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Integer> labelIdsInt = (List<Integer>) body.get("labelIds");
|
||||
Object labelIdsObj = body.get("labelIds");
|
||||
|
||||
if (labelIdsInt == null || labelIdsInt.isEmpty()) {
|
||||
if (!(labelIdsObj instanceof List)) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "labelIds不能为空");
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
|
||||
List<Long> labelIds = labelIdsInt.stream()
|
||||
.map(Integer::longValue)
|
||||
List<?> rawList = (List<?>) labelIdsObj;
|
||||
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());
|
||||
|
||||
return courseLabelService.addLabelsToType(typeId, labelIds)
|
||||
|
||||
+27
@@ -177,4 +177,31 @@ public class GroupCourseBookingHandler {
|
||||
response.put("message", message);
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码签到(二维码扫一扫签到)
|
||||
* 用户扫描团课签到二维码后,更新预约记录状态为 2(已出席)
|
||||
*/
|
||||
@Operation(summary = "扫码签到", description = "用户扫描团课二维码签到,更新预约状态为已出席")
|
||||
public Mono<ServerResponse> qrSignIn(ServerRequest request) {
|
||||
Long courseId = Long.valueOf(request.pathVariable("courseId"));
|
||||
|
||||
return request.bodyToMono(Map.class)
|
||||
.flatMap(body -> {
|
||||
if (body.get("memberId") == null) {
|
||||
return buildErrorResponse("请提供会员ID");
|
||||
}
|
||||
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||
|
||||
return bookingService.qrSignIn(courseId, memberId)
|
||||
.flatMap(booking -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", true);
|
||||
response.put("message", "签到成功");
|
||||
response.put("data", booking);
|
||||
return ServerResponse.ok().bodyValue(response);
|
||||
})
|
||||
.onErrorResume(error -> buildErrorResponse(error.getMessage()));
|
||||
});
|
||||
}
|
||||
}
|
||||
+162
-32
@@ -7,15 +7,25 @@ import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseDetail;
|
||||
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||
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.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.client.j2se.MatrixToImageWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
import com.google.zxing.qrcode.QRCodeWriter;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Validator;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 reactor.core.scheduler.Schedulers;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -26,15 +36,21 @@ public class GroupCourseHandler {
|
||||
private final Validator validator;
|
||||
private final RedisUtil redisUtil;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ISysUserService sysUserService;
|
||||
private final AuthUtil authUtil;
|
||||
|
||||
public GroupCourseHandler(IGroupCourseService groupCourseService,
|
||||
Validator validator,
|
||||
RedisUtil redisUtil,
|
||||
ObjectMapper objectMapper){
|
||||
ObjectMapper objectMapper,
|
||||
ISysUserService sysUserService,
|
||||
AuthUtil authUtil){
|
||||
this.groupCourseService = groupCourseService;
|
||||
this.validator = validator;
|
||||
this.redisUtil = redisUtil;
|
||||
this.objectMapper = objectMapper;
|
||||
this.sysUserService = sysUserService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表")
|
||||
@@ -114,25 +130,43 @@ public class GroupCourseHandler {
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新团课", description = "更新指定团课信息")
|
||||
@Operation(summary = "更新团课", description = "更新指定团课信息,需验证管理员密码")
|
||||
public Mono<ServerResponse> updateGroupCourse(ServerRequest request) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
|
||||
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);
|
||||
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 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 +231,78 @@ public class GroupCourseHandler {
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "删除团课", description = "删除指定团课(软删除)")
|
||||
@Operation(summary = "删除团课", description = "删除指定团课(软删除),需验证管理员密码")
|
||||
public Mono<ServerResponse> deleteGroupCourse(ServerRequest request) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
|
||||
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);
|
||||
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.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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -289,4 +379,44 @@ public class GroupCourseHandler {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "获取团课签到二维码", description = "根据团课ID生成签到二维码(base64)")
|
||||
public Mono<ServerResponse> getCourseQRCode(ServerRequest request) {
|
||||
Long courseId = Long.valueOf(request.pathVariable("id"));
|
||||
|
||||
return groupCourseService.findById(courseId)
|
||||
.flatMap(course -> {
|
||||
return Mono.fromCallable(() -> {
|
||||
String qrContent = "{\"courseId\":" + course.getId()
|
||||
+ ",\"courseName\":\"" + escapeJson(course.getCourseName()) + "\"}";
|
||||
|
||||
QRCodeWriter qrCodeWriter = new QRCodeWriter();
|
||||
BitMatrix bitMatrix = qrCodeWriter.encode(qrContent, BarcodeFormat.QR_CODE, 300, 300);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
|
||||
byte[] pngBytes = outputStream.toByteArray();
|
||||
String base64 = Base64.getEncoder().encodeToString(pngBytes);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("base64", "data:image/png;base64," + base64);
|
||||
result.put("courseId", course.getId());
|
||||
result.put("courseName", course.getCourseName());
|
||||
result.put("width", 300);
|
||||
result.put("height", 300);
|
||||
return result;
|
||||
}).subscribeOn(reactor.core.scheduler.Schedulers.boundedElastic());
|
||||
})
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(result))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
}
|
||||
|
||||
private String escapeJson(String s) {
|
||||
if (s == null) return "";
|
||||
return s.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t");
|
||||
}
|
||||
}
|
||||
|
||||
+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.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.tags.Tag;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
@@ -17,9 +20,15 @@ import java.util.Map;
|
||||
public class GroupCourseRecommendHandler {
|
||||
|
||||
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.sysUserService = sysUserService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有团课推荐", description = "获取系统中所有团课推荐列表,支持按优先级排序")
|
||||
@@ -80,20 +89,73 @@ public class GroupCourseRecommendHandler {
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新团课推荐", description = "更新指定团课推荐信息")
|
||||
@Operation(summary = "更新团课推荐", description = "更新指定团课推荐信息,需验证管理员密码")
|
||||
public Mono<ServerResponse> updateRecommendation(ServerRequest request) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||
|
||||
return request.bodyToMono(GroupCourseRecommend.class)
|
||||
.flatMap(recommend -> {
|
||||
return recommendService.update(id, recommend)
|
||||
.flatMap(r -> {
|
||||
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 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<>();
|
||||
response.put("success", true);
|
||||
response.put("message", "团课推荐更新成功");
|
||||
response.put("data", r);
|
||||
response.put("message", "团课推荐删除成功");
|
||||
return ServerResponse.ok().bodyValue(response);
|
||||
})
|
||||
}))
|
||||
.onErrorResume(error -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
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 = "启用指定团课推荐")
|
||||
public Mono<ServerResponse> enableRecommendation(ServerRequest request) {
|
||||
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) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||
|
||||
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);
|
||||
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.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.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.tags.Tag;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
@@ -17,9 +20,15 @@ import java.util.Map;
|
||||
public class GroupCourseTypeHandler {
|
||||
|
||||
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.sysUserService = sysUserService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有团课类型", description = "获取系统中所有团课类型列表")
|
||||
@@ -92,21 +101,76 @@ public class GroupCourseTypeHandler {
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新团课类型", description = "更新指定团课类型信息")
|
||||
@Operation(summary = "更新团课类型", description = "更新指定团课类型信息,需验证管理员密码")
|
||||
public Mono<ServerResponse> updateGroupCourseType(ServerRequest request) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
|
||||
return request.bodyToMono(GroupCourseType.class)
|
||||
.flatMap(groupCourseType -> {
|
||||
groupCourseType.setId(id);
|
||||
return groupCourseTypeService.update(id, groupCourseType)
|
||||
.flatMap(type -> {
|
||||
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 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<>();
|
||||
response.put("success", true);
|
||||
response.put("message", "团课类型更新成功");
|
||||
response.put("data", type);
|
||||
response.put("message", "团课类型删除成功");
|
||||
return ServerResponse.ok().bodyValue(response);
|
||||
})
|
||||
}))
|
||||
.onErrorResume(error -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package cn.novalon.gym.manage.groupcourse.repository;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.domain.Banner;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface IBannerRepository {
|
||||
|
||||
Mono<Banner> findById(Long id);
|
||||
|
||||
Flux<Banner> findAll();
|
||||
|
||||
Flux<Banner> findAll(String sortBy, String sortOrder);
|
||||
|
||||
Flux<Banner> findAllActive();
|
||||
|
||||
Mono<Banner> save(Banner banner);
|
||||
|
||||
Mono<Banner> update(Banner banner);
|
||||
|
||||
Mono<Void> deleteById(Long id);
|
||||
|
||||
Mono<Banner> updateActiveStatus(Long id, Boolean isActive);
|
||||
}
|
||||
+2
@@ -27,6 +27,8 @@ public interface IGroupCourseRepository {
|
||||
|
||||
Mono<Void> deleteById(Long id);
|
||||
|
||||
Mono<GroupCourse> restoreById(Long id);
|
||||
|
||||
Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta);
|
||||
|
||||
Flux<GroupCourse> findByCourseType(Long courseType);
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package cn.novalon.gym.manage.groupcourse.repository.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.BannerDao;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.Banner;
|
||||
import cn.novalon.gym.manage.groupcourse.entity.BannerEntity;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IBannerRepository;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Repository
|
||||
public class BannerRepository implements IBannerRepository {
|
||||
|
||||
private final BannerDao bannerDao;
|
||||
private final R2dbcEntityTemplate r2dbcEntityTemplate;
|
||||
|
||||
public BannerRepository(BannerDao bannerDao, R2dbcEntityTemplate r2dbcEntityTemplate) {
|
||||
this.bannerDao = bannerDao;
|
||||
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> findById(Long id) {
|
||||
return bannerDao.findByIdAndDeletedAtIsNull(id)
|
||||
.map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Banner> findAll() {
|
||||
return bannerDao.findAllByDeletedAtIsNull()
|
||||
.map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Banner> findAll(String sortBy, String sortOrder) {
|
||||
Sort.Direction direction = "asc".equalsIgnoreCase(sortOrder)
|
||||
? Sort.Direction.ASC
|
||||
: Sort.Direction.DESC;
|
||||
Sort sort = Sort.by(direction, sortBy);
|
||||
return bannerDao.findAllByDeletedAtIsNull(sort)
|
||||
.map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Banner> findAllActive() {
|
||||
return bannerDao.findByIsActiveTrueAndDeletedAtIsNull(Sort.by(Sort.Direction.DESC, "sortOrder"))
|
||||
.map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> save(Banner banner) {
|
||||
BannerEntity entity = toEntity(banner);
|
||||
entity.setCreatedAt(LocalDateTime.now());
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
if (entity.getSortOrder() == null) {
|
||||
entity.setSortOrder(0);
|
||||
}
|
||||
if (entity.getIsActive() == null) {
|
||||
entity.setIsActive(true);
|
||||
}
|
||||
|
||||
return bannerDao.save(entity)
|
||||
.map(this::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> update(Banner banner) {
|
||||
BannerEntity entity = toEntity(banner);
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
|
||||
return r2dbcEntityTemplate.update(entity)
|
||||
.then(findById(banner.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> deleteById(Long id) {
|
||||
return bannerDao.softDelete(id, LocalDateTime.now())
|
||||
.then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> updateActiveStatus(Long id, Boolean isActive) {
|
||||
return bannerDao.updateActiveStatus(id, isActive, LocalDateTime.now())
|
||||
.flatMap(updated -> {
|
||||
if (updated > 0) {
|
||||
return findById(id);
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private Banner toDomain(BannerEntity entity) {
|
||||
if (entity == null) return null;
|
||||
Banner banner = new Banner();
|
||||
BeanUtil.copyProperties(entity, banner);
|
||||
return banner;
|
||||
}
|
||||
|
||||
private BannerEntity toEntity(Banner domain) {
|
||||
if (domain == null) return null;
|
||||
BannerEntity entity = new BannerEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+13
@@ -138,6 +138,7 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
entity.setStatus(0L);
|
||||
entity.setCurrentMembers(0);
|
||||
entity.setIsRecurring(groupCourse.getIsRecurring() != null ? groupCourse.getIsRecurring() : false);
|
||||
|
||||
return groupCourseDao.save(entity)
|
||||
.map(groupCourseConverter::toDomain);
|
||||
@@ -147,6 +148,7 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
public Mono<GroupCourse> update(GroupCourse groupCourse) {
|
||||
GroupCourseEntity entity = groupCourseConverter.toEntity(groupCourse);
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
entity.setIsRecurring(groupCourse.getIsRecurring() != null ? groupCourse.getIsRecurring() : false);
|
||||
|
||||
return r2dbcEntityTemplate.update(entity)
|
||||
.then(findByIdAndDeletedAtIsNull(groupCourse.getId()));
|
||||
@@ -169,6 +171,17 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
.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
|
||||
public Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta) {
|
||||
return groupCourseDao.updateCurrentMembers(id, delta, LocalDateTime.now())
|
||||
|
||||
+14
-15
@@ -105,21 +105,20 @@ public class GroupCourseTypeRepository implements IGroupCourseTypeRepository {
|
||||
return groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId())
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("团课类型不存在")))
|
||||
.flatMap(existing -> {
|
||||
existing.markNotNew();
|
||||
if (groupCourseType.getTypeName() != null) {
|
||||
existing.setTypeName(groupCourseType.getTypeName());
|
||||
}
|
||||
if (groupCourseType.getBaseDifficulty() != null) {
|
||||
existing.setBaseDifficulty(groupCourseType.getBaseDifficulty());
|
||||
}
|
||||
if (groupCourseType.getDescription() != null) {
|
||||
existing.setDescription(groupCourseType.getDescription());
|
||||
}
|
||||
if (groupCourseType.getCategory() != null) {
|
||||
existing.setCategory(groupCourseType.getCategory());
|
||||
}
|
||||
existing.setUpdatedAt(LocalDateTime.now());
|
||||
return groupCourseTypeDao.save(existing);
|
||||
String typeName = groupCourseType.getTypeName() != null
|
||||
? groupCourseType.getTypeName() : existing.getTypeName();
|
||||
Integer baseDifficulty = groupCourseType.getBaseDifficulty() != null
|
||||
? groupCourseType.getBaseDifficulty() : existing.getBaseDifficulty();
|
||||
String description = groupCourseType.getDescription() != null
|
||||
? groupCourseType.getDescription() : existing.getDescription();
|
||||
String category = groupCourseType.getCategory() != null
|
||||
? groupCourseType.getCategory() : existing.getCategory();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
return groupCourseTypeDao.updateFields(
|
||||
groupCourseType.getId(), typeName, baseDifficulty,
|
||||
description, category, now)
|
||||
.then(groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId()));
|
||||
})
|
||||
.map(converter::toGroupCourseType);
|
||||
}
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package cn.novalon.gym.manage.groupcourse.scheduler;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 常态化团课自动续期定时任务
|
||||
*
|
||||
* 功能:定期检查已结束的常态化团课(is_recurring = TRUE 且 status = '2'),
|
||||
* 自动重置状态为正常(status = '0'),并将课程时间推迟一周,重新开始。
|
||||
*
|
||||
* @date 2026-06-29
|
||||
*/
|
||||
@Component
|
||||
public class GroupCourseRecurringScheduler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(GroupCourseRecurringScheduler.class);
|
||||
|
||||
private final GroupCourseDao groupCourseDao;
|
||||
|
||||
public GroupCourseRecurringScheduler(GroupCourseDao groupCourseDao) {
|
||||
this.groupCourseDao = groupCourseDao;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每分钟检查一次,将已结束的常态化团课重置为正常状态,
|
||||
* 并将上课时间/下课时间各推迟一周
|
||||
*/
|
||||
@Scheduled(fixedRate = 60000)
|
||||
public void renewRecurringCourses() {
|
||||
logger.debug("定时任务开始检查常态化团课,续期已结束的课程");
|
||||
|
||||
groupCourseDao.renewRecurringCourses(LocalDateTime.now())
|
||||
.subscribe(
|
||||
count -> {
|
||||
if (count > 0) {
|
||||
logger.info("常态化团课续期完成,更新了 {} 条课程", count);
|
||||
}
|
||||
},
|
||||
error -> logger.error("常态化团课续期定时任务执行失败:{}", error.getMessage(), error)
|
||||
);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.novalon.gym.manage.groupcourse.service;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.domain.Banner;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface IBannerService {
|
||||
|
||||
Mono<Banner> findById(Long id);
|
||||
|
||||
Flux<Banner> findAll();
|
||||
|
||||
Flux<Banner> findAll(String sortBy, String sortOrder);
|
||||
|
||||
Flux<Banner> findAllActive();
|
||||
|
||||
Mono<Banner> create(Banner banner);
|
||||
|
||||
Mono<Banner> update(Long id, Banner banner);
|
||||
|
||||
Mono<Void> delete(Long id);
|
||||
|
||||
Mono<Banner> enable(Long id);
|
||||
|
||||
Mono<Banner> disable(Long id);
|
||||
}
|
||||
+10
@@ -62,4 +62,14 @@ public interface IGroupCourseBookingService {
|
||||
* @return 处理的记录数
|
||||
*/
|
||||
Mono<Integer> processAbsentMembers();
|
||||
|
||||
/**
|
||||
* 扫码签到
|
||||
* 用户扫描团课二维码签到,将预约状态更新为已出席(2)
|
||||
*
|
||||
* @param courseId 团课ID
|
||||
* @param memberId 会员ID
|
||||
* @return 更新后的预约记录
|
||||
*/
|
||||
Mono<GroupCourseBooking> qrSignIn(Long courseId, Long memberId);
|
||||
}
|
||||
+2
@@ -26,6 +26,8 @@ public interface IGroupCourseService {
|
||||
Mono<GroupCourse> signIn(Long courseId, Long memberId);
|
||||
|
||||
Mono<Void> delete(Long id);
|
||||
|
||||
Mono<GroupCourse> restore(Long id);
|
||||
|
||||
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
||||
}
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.domain.Banner;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IBannerRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IBannerService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class BannerService implements IBannerService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BannerService.class);
|
||||
|
||||
private final IBannerRepository bannerRepository;
|
||||
|
||||
public BannerService(IBannerRepository bannerRepository) {
|
||||
this.bannerRepository = bannerRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> findById(Long id) {
|
||||
return bannerRepository.findById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Banner> findAll() {
|
||||
return bannerRepository.findAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Banner> findAll(String sortBy, String sortOrder) {
|
||||
return bannerRepository.findAll(sortBy, sortOrder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Banner> findAllActive() {
|
||||
return bannerRepository.findAllActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> create(Banner banner) {
|
||||
if (banner.getImageUrl() == null || banner.getImageUrl().isBlank()) {
|
||||
return Mono.error(new RuntimeException("背景图不能为空"));
|
||||
}
|
||||
if (banner.getTitle() == null || banner.getTitle().isBlank()) {
|
||||
return Mono.error(new RuntimeException("主标题不能为空"));
|
||||
}
|
||||
|
||||
return bannerRepository.save(banner)
|
||||
.doOnSuccess(r -> logger.info("轮播图创建成功 - id={}, title={}", r.getId(), r.getTitle()))
|
||||
.doOnError(error -> logger.error("轮播图创建失败 - error: {}", error.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> update(Long id, Banner banner) {
|
||||
return bannerRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("轮播图不存在")))
|
||||
.flatMap(existing -> {
|
||||
if (banner.getImageUrl() != null) existing.setImageUrl(banner.getImageUrl());
|
||||
if (banner.getTitle() != null) existing.setTitle(banner.getTitle());
|
||||
if (banner.getSubtitle() != null) existing.setSubtitle(banner.getSubtitle());
|
||||
if (banner.getDescription() != null) existing.setDescription(banner.getDescription());
|
||||
if (banner.getSortOrder() != null) existing.setSortOrder(banner.getSortOrder());
|
||||
if (banner.getIsActive() != null) existing.setIsActive(banner.getIsActive());
|
||||
|
||||
return bannerRepository.update(existing);
|
||||
})
|
||||
.doOnSuccess(r -> logger.info("轮播图更新成功 - id={}", id))
|
||||
.doOnError(error -> logger.error("轮播图更新失败 - id={}, error: {}", id, error.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> delete(Long id) {
|
||||
return bannerRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("轮播图不存在")))
|
||||
.flatMap(banner -> bannerRepository.deleteById(id)
|
||||
.doOnSuccess(v -> logger.info("轮播图删除成功 - id={}", id))
|
||||
.doOnError(error -> logger.error("轮播图删除失败 - id={}, error: {}", id, error.getMessage())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> enable(Long id) {
|
||||
return bannerRepository.updateActiveStatus(id, true)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("轮播图不存在")))
|
||||
.doOnSuccess(r -> logger.info("轮播图启用成功 - id={}", id))
|
||||
.doOnError(error -> logger.error("轮播图启用失败 - id={}, error: {}", id, error.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Banner> disable(Long id) {
|
||||
return bannerRepository.updateActiveStatus(id, false)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("轮播图不存在")))
|
||||
.doOnSuccess(r -> logger.info("轮播图禁用成功 - id={}", id))
|
||||
.doOnError(error -> logger.error("轮播图禁用失败 - id={}, error: {}", id, error.getMessage()));
|
||||
}
|
||||
}
|
||||
+77
-1
@@ -9,6 +9,7 @@ import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.r2dbc.core.DatabaseClient;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -46,6 +47,7 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
private final GroupCourseRedisService redisService;
|
||||
private final BookingReminderEventPublisher bookingReminderEventPublisher;
|
||||
private final BookingSagaHandler bookingSagaHandler;
|
||||
private final DatabaseClient databaseClient;
|
||||
|
||||
// 预约提前时间限制(分钟)
|
||||
private static final long BOOKING_MIN_ADVANCE_MINUTES = 30;
|
||||
@@ -56,12 +58,14 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
IGroupCourseRepository courseRepository,
|
||||
GroupCourseRedisService redisService,
|
||||
BookingReminderEventPublisher bookingReminderEventPublisher,
|
||||
BookingSagaHandler bookingSagaHandler) {
|
||||
BookingSagaHandler bookingSagaHandler,
|
||||
DatabaseClient databaseClient) {
|
||||
this.bookingRepository = bookingRepository;
|
||||
this.courseRepository = courseRepository;
|
||||
this.redisService = redisService;
|
||||
this.bookingReminderEventPublisher = bookingReminderEventPublisher;
|
||||
this.bookingSagaHandler = bookingSagaHandler;
|
||||
this.databaseClient = databaseClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -347,6 +351,78 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
.doOnComplete(() -> logger.debug("查询完成:courseId={}", courseId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GroupCourseBooking> qrSignIn(Long courseId, Long memberId) {
|
||||
logger.info("扫码签到:courseId={}, memberId={}", courseId, memberId);
|
||||
|
||||
return courseRepository.findByIdAndDeletedAtIsNull(courseId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在或已删除")))
|
||||
.flatMap(course -> {
|
||||
// 校验1:团课状态必须为 0(正常)
|
||||
Long status = course.getStatus();
|
||||
if (status == null || status != 0L) {
|
||||
String msg;
|
||||
if (status == null) msg = "课程状态异常";
|
||||
else if (status == 1L) msg = "课程已取消,无法签到";
|
||||
else if (status == 2L) msg = "课程已结束,无法签到";
|
||||
else msg = "课程状态不可签到";
|
||||
return Mono.error(new RuntimeException(msg));
|
||||
}
|
||||
|
||||
// 校验2:用户是否预约了该课程(状态为 0-已预约)
|
||||
return bookingRepository.findValidBooking(courseId, memberId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("您未预约此课程,无法签到")))
|
||||
.flatMap(booking -> {
|
||||
// 校验3:预约状态必须为 0
|
||||
if (!"0".equals(booking.getStatus())) {
|
||||
String msg;
|
||||
if ("1".equals(booking.getStatus())) msg = "预约已取消";
|
||||
else if ("2".equals(booking.getStatus())) msg = "已签到,无需重复签到";
|
||||
else msg = "预约状态异常";
|
||||
return Mono.error(new RuntimeException(msg));
|
||||
}
|
||||
|
||||
// 更新预约状态为 2(已出席)
|
||||
return bookingRepository.updateStatus(booking.getId(), "2")
|
||||
.then(Mono.defer(() -> {
|
||||
// 同步写入签到记录,供仪表盘统计
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime todayStart = now.toLocalDate().atStartOfDay();
|
||||
LocalDateTime todayEnd = todayStart.plusDays(1);
|
||||
|
||||
// 先检查今天是否已有成功签到记录,避免重复
|
||||
return databaseClient.sql(
|
||||
"SELECT sign_in_status FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false AND sign_in_status = 'SUCCESS' ORDER BY sign_in_time DESC LIMIT 1")
|
||||
.bind("memberId", memberId)
|
||||
.bind("startTime", todayStart)
|
||||
.bind("endTime", todayEnd)
|
||||
.map(row -> row.get("sign_in_status", String.class))
|
||||
.one()
|
||||
.flatMap(existing -> {
|
||||
// 已有签到记录,不重复插入
|
||||
return bookingRepository.findById(booking.getId());
|
||||
})
|
||||
.switchIfEmpty(
|
||||
// 无今日签到记录,插入一条
|
||||
databaseClient.sql(
|
||||
"INSERT INTO sign_in_record (member_id, member_card_id, sign_in_time, sign_in_type, sign_in_status, source, created_at, updated_at, is_delete) " +
|
||||
"VALUES (:memberId, :memberCardId, :signInTime, 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', NOW(), NOW(), false)")
|
||||
.bind("memberId", memberId)
|
||||
.bind("memberCardId", booking.getMemberCardRecordId())
|
||||
.bind("signInTime", now)
|
||||
.fetch()
|
||||
.rowsUpdated()
|
||||
.then(bookingRepository.findById(booking.getId()))
|
||||
);
|
||||
}));
|
||||
});
|
||||
})
|
||||
.doOnSuccess(booking -> logger.info("扫码签到成功:bookingId={}, courseId={}, memberId={}",
|
||||
booking.getId(), courseId, memberId))
|
||||
.doOnError(error -> logger.error("扫码签到失败:courseId={}, memberId={}, error={}",
|
||||
courseId, memberId, error.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Integer> processAbsentMembers() {
|
||||
logger.info("开始处理已开始课程但未到场会员的预约记录");
|
||||
|
||||
+16
-5
@@ -347,6 +347,9 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
if (groupCourse.getQrCodePath() != null) {
|
||||
existing.setQrCodePath(groupCourse.getQrCodePath());
|
||||
}
|
||||
if (groupCourse.getIsRecurring() != null) {
|
||||
existing.setIsRecurring(groupCourse.getIsRecurring());
|
||||
}
|
||||
return groupCourseRepository.update(existing);
|
||||
})
|
||||
.doOnSuccess(course -> logger.info("团课更新成功 - id={}", id))
|
||||
@@ -536,14 +539,14 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
|
||||
@Override
|
||||
public Mono<Void> delete(Long id) {
|
||||
// 先查询课程状态,只有已取消的课程才能删除
|
||||
// 已取消或已结束的课程才能删除
|
||||
return groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||
.flatMap(course -> {
|
||||
// 检查课程状态是否为已取消(状态码1)
|
||||
if (course.getStatus() == null || !course.getStatus().equals(CourseStatus.CANCELLED.getValue())) {
|
||||
return Mono.error(new RuntimeException("只有已取消的课程才能删除,当前状态: " +
|
||||
(course.getStatus() != null ? course.getStatus() : "未知")));
|
||||
Long status = course.getStatus();
|
||||
if (status == null || (!status.equals(CourseStatus.CANCELLED.getValue()) && !status.equals(CourseStatus.ENDED.getValue()))) {
|
||||
return Mono.error(new RuntimeException("只有已取消或已结束的课程才能删除,当前状态: " +
|
||||
(status != null ? status : "未知")));
|
||||
}
|
||||
|
||||
// 删除课程
|
||||
@@ -554,6 +557,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
|
||||
public Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query) {
|
||||
logger.info("多条件查询团课 - courseName={}, courseType={}, startDate={}, endDate={}, timePeriod={}, priceSort={}, remainingMost={}",
|
||||
|
||||
+13
-5
@@ -1,6 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||
|
||||
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.service.IGroupCourseTypeService;
|
||||
import org.slf4j.Logger;
|
||||
@@ -9,18 +10,18 @@ import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class GroupCourseTypeService implements IGroupCourseTypeService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(GroupCourseTypeService.class);
|
||||
|
||||
private final IGroupCourseTypeRepository groupCourseTypeRepository;
|
||||
private final IGroupCourseRepository groupCourseRepository;
|
||||
|
||||
public GroupCourseTypeService(IGroupCourseTypeRepository groupCourseTypeRepository) {
|
||||
public GroupCourseTypeService(IGroupCourseTypeRepository groupCourseTypeRepository,
|
||||
IGroupCourseRepository groupCourseRepository) {
|
||||
this.groupCourseTypeRepository = groupCourseTypeRepository;
|
||||
this.groupCourseRepository = groupCourseRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -71,7 +72,14 @@ public class GroupCourseTypeService implements IGroupCourseTypeService {
|
||||
|
||||
@Override
|
||||
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))
|
||||
.doOnError(error -> logger.error("团课类型删除失败 - id={}, error: {}", id, error.getMessage()));
|
||||
}
|
||||
|
||||
+94
-29
@@ -1,14 +1,19 @@
|
||||
package cn.novalon.gym.manage.groupcourse.util;
|
||||
|
||||
import com.aliyun.oss.HttpMethod;
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 阿里云OSS工具类
|
||||
@@ -19,8 +24,8 @@ public class OSSUtil {
|
||||
|
||||
// OSS配置信息
|
||||
private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
|
||||
private static final String ACCESS_KEY_ID = "LTAI5t9TFh9Vayeahz45kZjg";
|
||||
private static final String ACCESS_KEY_SECRET = "zD6NlCeH5UhjBs4vnQVqn8Ksi3CaZz";
|
||||
private static final String ACCESS_KEY_ID = "LTAI5t9wHCiH68Xjxg64Xx4Y";
|
||||
private static final String ACCESS_KEY_SECRET = "isAfz1IFGAnV13LOIrVg19aPhY8aRq";
|
||||
private static final String BUCKET_NAME = "ycc-filesaver";
|
||||
|
||||
// OSS访问地址前缀
|
||||
@@ -28,36 +33,31 @@ public class OSSUtil {
|
||||
|
||||
// 文件存储目录
|
||||
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 fileName 文件名(不含路径)
|
||||
* @return OSS访问地址
|
||||
* @return OSS object key(不含域名前缀)
|
||||
*/
|
||||
public static String uploadToOSS(String localFilePath, String fileName) {
|
||||
OSS ossClient = null;
|
||||
try {
|
||||
// 创建OSS客户端
|
||||
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 ossFilePath = QRCODE_DIR + datePath + "/" + fileName;
|
||||
|
||||
// 创建上传请求
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||
|
||||
// 上传文件
|
||||
ossClient.putObject(putObjectRequest);
|
||||
|
||||
// 构建访问地址
|
||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
||||
|
||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
||||
|
||||
return accessUrl;
|
||||
logger.info("文件上传到OSS成功: localPath={}, ossKey={}", localFilePath, ossFilePath);
|
||||
return ossFilePath;
|
||||
} catch (Exception e) {
|
||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||
@@ -69,34 +69,25 @@ public class OSSUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到阿里云OSS(自定义存储路径)
|
||||
* 上传文件到阿里云OSS(自定义存储路径,文件默认继承Bucket权限)
|
||||
*
|
||||
* @param localFilePath 本地文件路径
|
||||
* @param ossDirectory OSS存储目录
|
||||
* @param fileName 文件名(不含路径)
|
||||
* @return OSS访问地址
|
||||
* @return OSS object key(不含域名前缀)
|
||||
*/
|
||||
public static String uploadToOSS(String localFilePath, String ossDirectory, String fileName) {
|
||||
OSS ossClient = null;
|
||||
try {
|
||||
// 创建OSS客户端
|
||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||
|
||||
// 构建OSS文件路径
|
||||
String ossFilePath = ossDirectory + fileName;
|
||||
|
||||
// 创建上传请求
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||
|
||||
// 上传文件
|
||||
ossClient.putObject(putObjectRequest);
|
||||
|
||||
// 构建访问地址
|
||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
||||
|
||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
||||
|
||||
return accessUrl;
|
||||
logger.info("文件上传到OSS成功: localPath={}, ossKey={}", localFilePath, ossFilePath);
|
||||
return ossFilePath;
|
||||
} catch (Exception e) {
|
||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, 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.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.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
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.util.Map;
|
||||
|
||||
/**
|
||||
* 会员卡管理处理器
|
||||
*
|
||||
@@ -24,9 +29,13 @@ import reactor.core.publisher.Mono;
|
||||
public class MemberCardHandler {
|
||||
|
||||
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.sysUserService = sysUserService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "根据ID查询会员卡类型", description = "查询指定ID的会员卡类型详情")
|
||||
@@ -60,27 +69,72 @@ public class MemberCardHandler {
|
||||
.flatMap(card -> ServerResponse.status(HttpStatus.CREATED).bodyValue(card));
|
||||
}
|
||||
|
||||
@Operation(summary = "更新会员卡类型", description = "更新会员卡类型信息")
|
||||
@Operation(summary = "更新会员卡类型", description = "更新会员卡类型信息,需验证管理员密码")
|
||||
public Mono<ServerResponse> updateMemberCard(ServerRequest request) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(MemberCard.class)
|
||||
.flatMap(card -> {
|
||||
card.setMemberCardId(id);
|
||||
return memberCardService.save(card);
|
||||
})
|
||||
.flatMap(updated -> ServerResponse.ok().bodyValue(updated))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||
|
||||
if (adminPassword == null || adminPassword.isBlank()) {
|
||||
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 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) {
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return memberCardService.logicalDelete(id)
|
||||
.flatMap(rows -> {
|
||||
if (rows > 0) {
|
||||
return ServerResponse.noContent().build();
|
||||
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||
|
||||
if (adminPassword == null || adminPassword.isBlank()) {
|
||||
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;
|
||||
|
||||
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.SearchMemberDto;
|
||||
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.util.AesUtil;
|
||||
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.security.JwtTokenProvider;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -24,6 +24,8 @@ import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 会员信息处理器
|
||||
*
|
||||
@@ -41,6 +43,7 @@ public class MemberHandler {
|
||||
private final WechatAuthService wechatAuthService;
|
||||
private final WechatOfficialService wechatOfficialService;
|
||||
private final AuthUtil authUtil;
|
||||
private final ISysUserService sysUserService;
|
||||
|
||||
@Operation(summary = "获取会员信息", description = "根据当前登录用户获取会员基本信息")
|
||||
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) {
|
||||
|
||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||
@@ -174,14 +177,30 @@ public class MemberHandler {
|
||||
long memberId = NumberUtils.toLong(memberIdStr, 0L);
|
||||
if(memberId <= 0L) throw new IllegalArgumentException("会员ID格式错误");
|
||||
|
||||
// TODO: 补充签到记录
|
||||
log.info("前台编辑会员信息, adminId: {}, memberId: {}", adminId, memberId);
|
||||
|
||||
return request.bodyToMono(UpdateMemberInfoDto.class)
|
||||
.flatMap(updateDto -> memberService.adminUpdateMemberInfo(memberId, updateDto))
|
||||
.flatMap(detail -> ServerResponse.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.bodyValue(detail));
|
||||
return request.bodyToMono(AdminEditMemberDto.class)
|
||||
.flatMap(dto -> {
|
||||
if (dto.getAdminPassword() == null || dto.getAdminPassword().isBlank()) {
|
||||
return ServerResponse.badRequest()
|
||||
.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 = "后台管理员按关键词搜索会员,支持性别筛选和分页")
|
||||
|
||||
+48
-35
@@ -254,45 +254,58 @@ public class MemberServiceImpl implements MemberService {
|
||||
log.debug("从缓存获取会员详情, memberId: {}", memberId);
|
||||
return Mono.just(cached);
|
||||
}
|
||||
return memberRepository.findById(memberId)
|
||||
.zipWith(
|
||||
memberRepository.findCardRecordsWithCardInfoByMemberId(memberId)
|
||||
.collectList(),
|
||||
(baseInfo, cardList) -> {
|
||||
MemberDetailVO memberDetailVO = BeanConvertUtil.toBean(baseInfo, MemberDetailVO.class);
|
||||
// 缓存反序列化异常,查数据库
|
||||
return queryMemberDetailFromDb(memberId, cacheKey);
|
||||
})
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
// 缓存不存在,查数据库
|
||||
return queryMemberDetailFromDb(memberId, cacheKey);
|
||||
}));
|
||||
}
|
||||
|
||||
GenderEnum genderEnum = GenderEnum.fromCode(baseInfo.getGender());
|
||||
memberDetailVO.setGenderDesc(genderEnum.getDesc());
|
||||
private Mono<MemberDetailVO> queryMemberDetailFromDb(Long memberId, String cacheKey) {
|
||||
return memberRepository.findById(memberId)
|
||||
.zipWith(
|
||||
memberRepository.findCardRecordsWithCardInfoByMemberId(memberId)
|
||||
.collectList(),
|
||||
(baseInfo, cardList) -> {
|
||||
MemberDetailVO memberDetailVO = BeanConvertUtil.toBean(baseInfo, MemberDetailVO.class);
|
||||
|
||||
List<MemberCardInfoVO> enrichedCards = cardList.stream()
|
||||
.peek(vo -> {
|
||||
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);
|
||||
GenderEnum genderEnum = GenderEnum.fromCode(baseInfo.getGender());
|
||||
memberDetailVO.setGenderDesc(genderEnum.getDesc());
|
||||
|
||||
long activeCount = enrichedCards.stream()
|
||||
.filter(card -> card.getMemberCardStatus() != null && card.getMemberCardStatus() == 1)
|
||||
.count();
|
||||
memberDetailVO.setActiveCardCount((int) activeCount);
|
||||
memberDetailVO.setInactiveCardCount(enrichedCards.size() - (int) activeCount);
|
||||
List<MemberCardInfoVO> enrichedCards = cardList.stream()
|
||||
.peek(vo -> {
|
||||
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);
|
||||
|
||||
return memberDetailVO;
|
||||
}
|
||||
)
|
||||
.flatMap(vo -> redisUtil.setWithExpire(cacheKey, vo, CACHE_EXPIRE_SECONDS)
|
||||
.then(Mono.just(vo)));
|
||||
});
|
||||
long activeCount = enrichedCards.stream()
|
||||
.filter(card -> card.getMemberCardStatus() != null && card.getMemberCardStatus() == 1)
|
||||
.count();
|
||||
memberDetailVO.setActiveCardCount((int) activeCount);
|
||||
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, "会员不存在");
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package cn.novalon.gym.manage.payment.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 支付记录响应DTO
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "支付记录")
|
||||
public class PaymentRecordResponse {
|
||||
|
||||
@Schema(description = "订单ID")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "订单号")
|
||||
private String orderNo;
|
||||
|
||||
@Schema(description = "用户编号(会员ID)")
|
||||
private Long memberId;
|
||||
|
||||
@Schema(description = "支付方式(ALIPAY/WECHAT)")
|
||||
private String tradeType;
|
||||
|
||||
@Schema(description = "购买内容(商品描述)")
|
||||
private String goodsDesc;
|
||||
|
||||
@Schema(description = "订单类型(MEMBER_CARD/GROUP_COURSE/GOODS)")
|
||||
private String orderType;
|
||||
|
||||
@Schema(description = "支付金额(元)")
|
||||
private BigDecimal transAmt;
|
||||
|
||||
@Schema(description = "支付状态(PENDING/SUCCESS/FAIL/CLOSED)")
|
||||
private String payStatus;
|
||||
|
||||
@Schema(description = "支付时间")
|
||||
private String payTime;
|
||||
|
||||
@Schema(description = "汇付流水号")
|
||||
private String hfSeqId;
|
||||
|
||||
@Schema(description = "创建时间")
|
||||
private String createdAt;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package cn.novalon.gym.manage.payment.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 营业额统计数据
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "营业额统计数据")
|
||||
public class RevenueStatistics {
|
||||
|
||||
@Schema(description = "今日收入(元)")
|
||||
private BigDecimal todayIncome;
|
||||
|
||||
@Schema(description = "今日退款(元)")
|
||||
private BigDecimal todayRefund;
|
||||
|
||||
@Schema(description = "今日订单数")
|
||||
private Long todayOrderCount;
|
||||
|
||||
@Schema(description = "当月收入(元)")
|
||||
private BigDecimal monthIncome;
|
||||
|
||||
@Schema(description = "当月退款(元)")
|
||||
private BigDecimal monthRefund;
|
||||
|
||||
@Schema(description = "当月订单数")
|
||||
private Long monthOrderCount;
|
||||
|
||||
@Schema(description = "当年收入(元)")
|
||||
private BigDecimal yearIncome;
|
||||
|
||||
@Schema(description = "当年退款(元)")
|
||||
private BigDecimal yearRefund;
|
||||
|
||||
@Schema(description = "当年订单数")
|
||||
private Long yearOrderCount;
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package cn.novalon.gym.manage.payment.handler;
|
||||
|
||||
import cn.novalon.gym.manage.payment.dto.ApiResponse;
|
||||
import cn.novalon.gym.manage.payment.service.PaymentService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 支付营业数据 Handler
|
||||
*
|
||||
* @author system
|
||||
* @date 2026-06-29
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@Tag(name = "支付营业数据", description = "营业额统计与支付记录查询")
|
||||
public class PaymentRevenueHandler {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
|
||||
public PaymentRevenueHandler(PaymentService paymentService) {
|
||||
this.paymentService = paymentService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取营业额统计", description = "获取今日、当月、当年的收入和退款情况")
|
||||
public Mono<ServerResponse> getRevenueStatistics(ServerRequest request) {
|
||||
log.info("[Revenue] 查询营业额统计");
|
||||
|
||||
return paymentService.getRevenueStatistics()
|
||||
.flatMap(stats -> ServerResponse.ok()
|
||||
.bodyValue(ApiResponse.success(stats)))
|
||||
.onErrorResume(e -> {
|
||||
log.error("[Revenue] 查询营业额统计失败", e);
|
||||
return ServerResponse.ok()
|
||||
.bodyValue(ApiResponse.error("查询营业额统计失败: " + e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "查询支付记录", description = "分页查询用户支付记录,支持按会员ID、支付状态、支付方式筛选")
|
||||
public Mono<ServerResponse> getPaymentRecords(ServerRequest request) {
|
||||
String memberIdStr = request.queryParam("memberId").orElse(null);
|
||||
Long memberId = null;
|
||||
if (memberIdStr != null && !memberIdStr.isEmpty()) {
|
||||
try {
|
||||
memberId = Long.parseLong(memberIdStr);
|
||||
} catch (NumberFormatException e) {
|
||||
return ServerResponse.ok()
|
||||
.bodyValue(ApiResponse.error("会员ID格式不正确"));
|
||||
}
|
||||
}
|
||||
|
||||
String payStatus = request.queryParam("payStatus").orElse(null);
|
||||
String tradeType = request.queryParam("tradeType").orElse(null);
|
||||
int page = Integer.parseInt(request.queryParam("page").orElse("1"));
|
||||
int pageSize = Integer.parseInt(request.queryParam("pageSize").orElse("20"));
|
||||
|
||||
log.info("[Revenue] 查询支付记录: memberId={}, payStatus={}, tradeType={}, page={}, pageSize={}",
|
||||
memberId, payStatus, tradeType, page, pageSize);
|
||||
|
||||
return paymentService.getPaymentRecords(memberId, payStatus, tradeType, page, pageSize)
|
||||
.flatMap(result -> ServerResponse.ok()
|
||||
.bodyValue(ApiResponse.success(result)))
|
||||
.onErrorResume(e -> {
|
||||
log.error("[Revenue] 查询支付记录失败", e);
|
||||
return ServerResponse.ok()
|
||||
.bodyValue(ApiResponse.error("查询支付记录失败: " + e.getMessage()));
|
||||
});
|
||||
}
|
||||
}
|
||||
+21
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Repository
|
||||
@@ -38,4 +39,24 @@ public interface PaymentOrderRepository extends R2dbcRepository<PaymentOrder, Lo
|
||||
Flux<PaymentOrder> findAllByDeletedAtIsNull();
|
||||
|
||||
Flux<PaymentOrder> findByMemberIdAndDeletedAtIsNull(Long memberId);
|
||||
|
||||
// ===== 营业额统计 =====
|
||||
|
||||
/** 统计指定时间范围内成功支付的金额总和 */
|
||||
@Query("SELECT COALESCE(SUM(trans_amt), 0) FROM payment_order WHERE pay_status = 'SUCCESS' AND pay_time >= :startTime AND pay_time < :endTime AND deleted_at IS NULL")
|
||||
Mono<BigDecimal> sumSuccessAmount(LocalDateTime startTime, LocalDateTime endTime);
|
||||
|
||||
/** 统计指定时间范围内的成功订单数 */
|
||||
@Query("SELECT COUNT(*) FROM payment_order WHERE pay_status = 'SUCCESS' AND pay_time >= :startTime AND pay_time < :endTime AND deleted_at IS NULL")
|
||||
Mono<Long> countSuccessOrders(LocalDateTime startTime, LocalDateTime endTime);
|
||||
|
||||
// ===== 支付记录分页查询 =====
|
||||
|
||||
/** 按条件分页查询支付记录 */
|
||||
@Query("SELECT * FROM payment_order WHERE (:memberId IS NULL OR member_id = :memberId) AND (:payStatus IS NULL OR pay_status = :payStatus) AND (:tradeType IS NULL OR trade_type = :tradeType) AND deleted_at IS NULL ORDER BY created_at DESC LIMIT :limit OFFSET :offset")
|
||||
Flux<PaymentOrder> findPaymentRecords(Long memberId, String payStatus, String tradeType, int limit, int offset);
|
||||
|
||||
/** 按条件统计支付记录总数 */
|
||||
@Query("SELECT COUNT(*) FROM payment_order WHERE (:memberId IS NULL OR member_id = :memberId) AND (:payStatus IS NULL OR pay_status = :payStatus) AND (:tradeType IS NULL OR trade_type = :tradeType) AND deleted_at IS NULL")
|
||||
Mono<Long> countPaymentRecords(Long memberId, String payStatus, String tradeType);
|
||||
}
|
||||
|
||||
+8
@@ -1,7 +1,9 @@
|
||||
package cn.novalon.gym.manage.payment.service;
|
||||
|
||||
import cn.novalon.gym.manage.payment.dto.CreatePaymentRequest;
|
||||
import cn.novalon.gym.manage.payment.dto.PaymentRecordResponse;
|
||||
import cn.novalon.gym.manage.payment.dto.PaymentResponse;
|
||||
import cn.novalon.gym.manage.payment.dto.RevenueStatistics;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@@ -30,4 +32,10 @@ public interface PaymentService {
|
||||
Mono<PaymentResponse> getPendingOrder(Long memberId, String orderType);
|
||||
|
||||
Mono<Boolean> closeOrder(Long memberId, String orderId);
|
||||
|
||||
/** 获取营业额统计(今日/当月/当年) */
|
||||
Mono<RevenueStatistics> getRevenueStatistics();
|
||||
|
||||
/** 分页查询支付记录 */
|
||||
Mono<Map<String, Object>> getPaymentRecords(Long memberId, String payStatus, String tradeType, int page, int pageSize);
|
||||
}
|
||||
+74
@@ -3,7 +3,9 @@ package cn.novalon.gym.manage.payment.service.impl;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import cn.novalon.gym.manage.payment.config.HuifuProperties;
|
||||
import cn.novalon.gym.manage.payment.dto.CreatePaymentRequest;
|
||||
import cn.novalon.gym.manage.payment.dto.PaymentRecordResponse;
|
||||
import cn.novalon.gym.manage.payment.dto.PaymentResponse;
|
||||
import cn.novalon.gym.manage.payment.dto.RevenueStatistics;
|
||||
import cn.novalon.gym.manage.payment.entity.PaymentOrder;
|
||||
import cn.novalon.gym.manage.payment.repository.PaymentOrderRepository;
|
||||
import cn.novalon.gym.manage.payment.service.PaymentNotifyService;
|
||||
@@ -934,4 +936,76 @@ public class PaymentServiceImpl implements PaymentService {
|
||||
})
|
||||
.switchIfEmpty(Mono.just(false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<RevenueStatistics> getRevenueStatistics() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
// 今日
|
||||
LocalDateTime todayStart = now.toLocalDate().atStartOfDay();
|
||||
LocalDateTime todayEnd = todayStart.plusDays(1);
|
||||
// 当月
|
||||
LocalDateTime monthStart = now.toLocalDate().withDayOfMonth(1).atStartOfDay();
|
||||
LocalDateTime monthEnd = monthStart.plusMonths(1);
|
||||
// 当年
|
||||
LocalDateTime yearStart = now.toLocalDate().withDayOfYear(1).atStartOfDay();
|
||||
LocalDateTime yearEnd = yearStart.plusYears(1);
|
||||
|
||||
Mono<BigDecimal> todayIncomeMono = paymentOrderRepository.sumSuccessAmount(todayStart, todayEnd);
|
||||
Mono<Long> todayCountMono = paymentOrderRepository.countSuccessOrders(todayStart, todayEnd);
|
||||
Mono<BigDecimal> monthIncomeMono = paymentOrderRepository.sumSuccessAmount(monthStart, monthEnd);
|
||||
Mono<Long> monthCountMono = paymentOrderRepository.countSuccessOrders(monthStart, monthEnd);
|
||||
Mono<BigDecimal> yearIncomeMono = paymentOrderRepository.sumSuccessAmount(yearStart, yearEnd);
|
||||
Mono<Long> yearCountMono = paymentOrderRepository.countSuccessOrders(yearStart, yearEnd);
|
||||
|
||||
return Mono.zip(todayIncomeMono, todayCountMono, monthIncomeMono, monthCountMono, yearIncomeMono, yearCountMono)
|
||||
.map(tuple -> RevenueStatistics.builder()
|
||||
.todayIncome(tuple.getT1() != null ? tuple.getT1() : BigDecimal.ZERO)
|
||||
.todayRefund(BigDecimal.ZERO) // 退款功能暂未实现
|
||||
.todayOrderCount(tuple.getT2() != null ? tuple.getT2() : 0L)
|
||||
.monthIncome(tuple.getT3() != null ? tuple.getT3() : BigDecimal.ZERO)
|
||||
.monthRefund(BigDecimal.ZERO) // 退款功能暂未实现
|
||||
.monthOrderCount(tuple.getT4() != null ? tuple.getT4() : 0L)
|
||||
.yearIncome(tuple.getT5() != null ? tuple.getT5() : BigDecimal.ZERO)
|
||||
.yearRefund(BigDecimal.ZERO) // 退款功能暂未实现
|
||||
.yearOrderCount(tuple.getT6() != null ? tuple.getT6() : 0L)
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Map<String, Object>> getPaymentRecords(Long memberId, String payStatus, String tradeType, int page, int pageSize) {
|
||||
int offset = (page - 1) * pageSize;
|
||||
|
||||
Mono<List<PaymentRecordResponse>> recordsMono = paymentOrderRepository
|
||||
.findPaymentRecords(memberId, payStatus, tradeType, pageSize, offset)
|
||||
.map(order -> PaymentRecordResponse.builder()
|
||||
.id(order.getId())
|
||||
.orderNo(order.getOrderNo())
|
||||
.memberId(order.getMemberId())
|
||||
.tradeType(order.getTradeType())
|
||||
.goodsDesc(order.getGoodsDesc())
|
||||
.orderType(order.getOrderType())
|
||||
.transAmt(order.getTransAmt())
|
||||
.payStatus(order.getPayStatus())
|
||||
.payTime(order.getPayTime() != null
|
||||
? order.getPayTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
|
||||
: null)
|
||||
.hfSeqId(order.getHfSeqId())
|
||||
.createdAt(order.getCreatedAt() != null
|
||||
? order.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
|
||||
: null)
|
||||
.build())
|
||||
.collectList();
|
||||
|
||||
Mono<Long> totalMono = paymentOrderRepository.countPaymentRecords(memberId, payStatus, tradeType);
|
||||
|
||||
return Mono.zip(recordsMono, totalMono)
|
||||
.map(tuple -> {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("records", tuple.getT1());
|
||||
result.put("total", tuple.getT2());
|
||||
result.put("page", page);
|
||||
result.put("pageSize", pageSize);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
}
|
||||
+37
-4
@@ -7,9 +7,11 @@ import cn.novalon.gym.manage.file.handler.SysFileHandler;
|
||||
import cn.novalon.gym.manage.auth.handler.PhoneAuthHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseBookingHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.BannerHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseRecommendHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseTypeHandler;
|
||||
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.MemberCardRecordHandler;
|
||||
import cn.novalon.gym.manage.member.handler.MemberCardTransactionHandler;
|
||||
@@ -19,6 +21,7 @@ import cn.novalon.gym.manage.member.handler.WechatAuthHandler;
|
||||
import cn.novalon.gym.manage.notify.handler.SysNoticeHandler;
|
||||
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
|
||||
import cn.novalon.gym.manage.payment.handler.PaymentHandler;
|
||||
import cn.novalon.gym.manage.payment.handler.PaymentRevenueHandler;
|
||||
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.config.SysConfigHandler;
|
||||
@@ -79,10 +82,13 @@ public class SystemRouter {
|
||||
GroupCourseRecommendHandler groupCourseRecommendHandler,
|
||||
GroupCourseTypeHandler groupCourseTypeHandler,
|
||||
CourseLabelHandler courseLabelHandler,
|
||||
BannerHandler bannerHandler,
|
||||
CheckInHandler checkInHandler,
|
||||
DataStatisticsHandler dataStatisticsHandler,
|
||||
PhoneAuthHandler phoneAuthHandler,
|
||||
PaymentHandler paymentHandler) {
|
||||
PaymentHandler paymentHandler,
|
||||
PaymentRevenueHandler paymentRevenueHandler,
|
||||
CommonUploadHandler commonUploadHandler) {
|
||||
|
||||
return route()
|
||||
// ========== 诊断路由 ==========
|
||||
@@ -170,6 +176,7 @@ public class SystemRouter {
|
||||
.POST("/api/auth/login", authHandler::login)
|
||||
.POST("/api/auth/register", authHandler::register)
|
||||
.POST("/api/auth/logout", authHandler::logout)
|
||||
.GET("/api/auth/me", authHandler::me)
|
||||
|
||||
// ========== 统计路由 ==========
|
||||
.GET("/api/stats/overview", statsHandler::getOverview)
|
||||
@@ -217,6 +224,10 @@ public class SystemRouter {
|
||||
.GET("/api/files/preview/{fileName}", fileHandler::previewFileByName)
|
||||
.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/{id}", permissionHandler::getPermissionById)
|
||||
@@ -257,8 +268,11 @@ public class SystemRouter {
|
||||
|
||||
// ===== 会员卡类型管理 =====
|
||||
.GET("/api/member-cards/active", memberCardHandler::getActiveCards)
|
||||
.GET("/api/member-cards", memberCardHandler::listMemberCards)
|
||||
.GET("/api/member-cards/{memberCardId}", memberCardHandler::getMemberCardById)
|
||||
.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)
|
||||
@@ -338,13 +352,26 @@ public class SystemRouter {
|
||||
.POST("/api/groupCourse/recommend/{id}/enable", groupCourseRecommendHandler::enableRecommendation)
|
||||
.POST("/api/groupCourse/recommend/{id}/disable", groupCourseRecommendHandler::disableRecommendation)
|
||||
|
||||
// ========== 轮播图路由 ==========
|
||||
.GET("/api/banner/list", bannerHandler::getAllBanners)
|
||||
.GET("/api/banner/active", bannerHandler::getAllActiveBanners)
|
||||
.GET("/api/banner/{id}", bannerHandler::getBannerById)
|
||||
.POST("/api/banner", bannerHandler::createBanner)
|
||||
.PUT("/api/banner/{id}", bannerHandler::updateBanner)
|
||||
.DELETE("/api/banner/{id}", bannerHandler::deleteBanner)
|
||||
.POST("/api/banner/{id}/enable", bannerHandler::enableBanner)
|
||||
.POST("/api/banner/{id}/disable", bannerHandler::disableBanner)
|
||||
|
||||
// ===== 团课课程管理(需要放在具体路由之后)=====
|
||||
.GET("/api/groupCourse/{id}/qrcode", groupCourseHandler::getCourseQRCode)
|
||||
.POST("/api/groupCourse/{courseId}/qrsignin", groupCourseBookingHandler::qrSignIn)
|
||||
.GET("/api/groupCourse/{id}", groupCourseHandler::getGroupCourseById)
|
||||
.GET("/api/groupCourse/{id}/detail", groupCourseHandler::getGroupCourseDetailById)
|
||||
.POST("/api/groupCourse", groupCourseHandler::createGroupCourse)
|
||||
.PUT("/api/groupCourse/{id}", groupCourseHandler::updateGroupCourse)
|
||||
.DELETE("/api/groupCourse/{id}", groupCourseHandler::deleteGroupCourse)
|
||||
.POST("/api/groupCourse/{id}/cancel", groupCourseHandler::cancelGroupCourse)
|
||||
.POST("/api/groupCourse/{id}/restore", groupCourseHandler::restoreGroupCourse)
|
||||
.POST("/api/groupCourse/signin/{memberId}", groupCourseHandler::signIn)
|
||||
.POST("/api/groupCourse/search", groupCourseHandler::searchGroupCourses)
|
||||
|
||||
@@ -354,15 +381,17 @@ public class SystemRouter {
|
||||
.GET("/api/checkIn/qrcode", checkInHandler::getQRCode)
|
||||
|
||||
// ===== 签到记录管理 =====
|
||||
.GET("/api/checkIn/records/export", checkInHandler::exportSignInRecords)
|
||||
.GET("/api/checkIn/records", checkInHandler::getSignInRecords)
|
||||
.GET("/api/checkIn/records/{id}", checkInHandler::getSignInRecordById)
|
||||
|
||||
// ===== 签到统计 =====
|
||||
.GET("/api/checkIn/statistics", checkInHandler::getSignInStatistics)
|
||||
.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)
|
||||
|
||||
// ========================================
|
||||
// ========== 数据统计模块路由 ============
|
||||
@@ -391,6 +420,10 @@ public class SystemRouter {
|
||||
.POST("/api/payment/{orderId}/refund", paymentHandler::refundPayment)
|
||||
.POST("/api/payment/{orderId}/close", paymentHandler::closeOrder)
|
||||
|
||||
// ===== 支付营业数据 =====
|
||||
.GET("/api/payment/revenue/statistics", paymentRevenueHandler::getRevenueStatistics)
|
||||
.GET("/api/payment/revenue/records", paymentRevenueHandler::getPaymentRecords)
|
||||
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,10 @@
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+15
-2
@@ -1,5 +1,8 @@
|
||||
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.Configuration;
|
||||
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
|
||||
@@ -24,13 +27,23 @@ public class RedisConfig {
|
||||
public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(
|
||||
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>newSerializationContext()
|
||||
.key(StringRedisSerializer.UTF_8)
|
||||
.value(new GenericJackson2JsonRedisSerializer())
|
||||
.value(serializer)
|
||||
.hashKey(StringRedisSerializer.UTF_8)
|
||||
.hashValue(new GenericJackson2JsonRedisSerializer())
|
||||
.hashValue(serializer)
|
||||
.build();
|
||||
|
||||
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
-- ============================================
|
||||
-- 团课新增常态化标记
|
||||
-- ============================================
|
||||
|
||||
ALTER TABLE group_course ADD COLUMN IF NOT EXISTS is_recurring BOOLEAN DEFAULT FALSE;
|
||||
|
||||
COMMENT ON COLUMN group_course.is_recurring IS '是否常态化团课:TRUE-是,FALSE-否(默认)';
|
||||
@@ -0,0 +1,36 @@
|
||||
-- ============================================
|
||||
-- 轮播图表
|
||||
-- ============================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS banner (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
image_url TEXT NOT NULL,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
subtitle VARCHAR(100),
|
||||
description TEXT,
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
create_by VARCHAR(50),
|
||||
update_by VARCHAR(50),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_banner_sort_order ON banner(sort_order);
|
||||
CREATE INDEX IF NOT EXISTS idx_banner_is_active ON banner(is_active);
|
||||
CREATE INDEX IF NOT EXISTS idx_banner_deleted_at ON banner(deleted_at);
|
||||
|
||||
COMMENT ON TABLE banner IS '轮播图表';
|
||||
COMMENT ON COLUMN banner.id IS '主键ID';
|
||||
COMMENT ON COLUMN banner.image_url IS '背景图URL';
|
||||
COMMENT ON COLUMN banner.title IS '主标题';
|
||||
COMMENT ON COLUMN banner.subtitle IS '副标题';
|
||||
COMMENT ON COLUMN banner.description IS '简介';
|
||||
COMMENT ON COLUMN banner.sort_order IS '排序(数值越大越靠前)';
|
||||
COMMENT ON COLUMN banner.is_active IS '是否启用';
|
||||
COMMENT ON COLUMN banner.create_by IS '创建人';
|
||||
COMMENT ON COLUMN banner.update_by IS '更新人';
|
||||
COMMENT ON COLUMN banner.created_at IS '创建时间';
|
||||
COMMENT ON COLUMN banner.updated_at IS '更新时间';
|
||||
COMMENT ON COLUMN banner.deleted_at IS '删除时间(软删除)';
|
||||
+181
-101
@@ -9,24 +9,17 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
||||
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.WebFilter;
|
||||
import org.springframework.web.server.WebFilterChain;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||
@@ -37,19 +30,76 @@ public class OperationLogWebFilter implements WebFilter {
|
||||
private final IOperationLogService operationLogService;
|
||||
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 {
|
||||
OPERATION_MAPPING.put("POST:/api/roles", new OperationInfo("角色管理", "创建角色"));
|
||||
OPERATION_MAPPING.put("PUT:/api/roles/", new OperationInfo("角色管理", "更新角色"));
|
||||
OPERATION_MAPPING.put("DELETE:/api/roles/", new OperationInfo("角色管理", "删除角色"));
|
||||
OPERATION_MAPPING.put("POST:/api/users", new OperationInfo("用户管理", "创建用户"));
|
||||
OPERATION_MAPPING.put("PUT:/api/users/", new OperationInfo("用户管理", "更新用户"));
|
||||
OPERATION_MAPPING.put("DELETE:/api/users/", new OperationInfo("用户管理", "删除用户"));
|
||||
OPERATION_MAPPING.put("POST:/api/users/", new OperationInfo("用户管理", "用户操作"));
|
||||
OPERATION_MAPPING.put("POST:/api/menus", new OperationInfo("菜单管理", "创建菜单"));
|
||||
OPERATION_MAPPING.put("PUT:/api/menus/", new OperationInfo("菜单管理", "更新菜单"));
|
||||
OPERATION_MAPPING.put("DELETE:/api/menus/", new OperationInfo("菜单管理", "删除菜单"));
|
||||
// ===== 精确路径匹配 =====
|
||||
PRECISE_MAPPING.put("POST:/api/roles", new OperationInfo("角色管理", "创建角色"));
|
||||
PRECISE_MAPPING.put("POST:/api/users", new OperationInfo("用户管理", "创建用户"));
|
||||
PRECISE_MAPPING.put("POST:/api/menus", new OperationInfo("菜单管理", "创建菜单"));
|
||||
PRECISE_MAPPING.put("POST:/api/auth/login", new OperationInfo("认证", "用户登录"));
|
||||
PRECISE_MAPPING.put("GET:/api/groupCourse/types/categories", new OperationInfo("团课类型", "查询分类"));
|
||||
PRECISE_MAPPING.put("POST:/api/groupCourse/types", new OperationInfo("团课类型", "创建类型"));
|
||||
PRECISE_MAPPING.put("POST:/api/groupCourse", new OperationInfo("团课管理", "创建团课"));
|
||||
PRECISE_MAPPING.put("POST:/api/member", 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) {
|
||||
@@ -61,10 +111,8 @@ public class OperationLogWebFilter implements WebFilter {
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
logger.info("=== OperationLogWebFilter 初始化 ===");
|
||||
logger.info("操作日志映射配置数量: {}", OPERATION_MAPPING.size());
|
||||
OPERATION_MAPPING.forEach((key, value) -> {
|
||||
logger.info(" {} -> {}:{}", key, value.module, value.operation);
|
||||
});
|
||||
logger.info("精确匹配配置数量: {}, 前缀匹配配置数量: {}, 模块映射数量: {}",
|
||||
PRECISE_MAPPING.size(), PREFIX_MAPPING.size(), MODULE_NAMES.size());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -72,103 +120,135 @@ public class OperationLogWebFilter implements WebFilter {
|
||||
ServerHttpRequest request = exchange.getRequest();
|
||||
String method = request.getMethod().name();
|
||||
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) {
|
||||
logger.info("未匹配到操作日志配置,跳过: {} {}", method, path);
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
logger.info("匹配到操作日志配置: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
String ip = IpUtils.getClientIp(request);
|
||||
final OperationInfo finalInfo = operationInfo;
|
||||
|
||||
return Mono.deferContextual(contextView -> {
|
||||
return chain.filter(exchange)
|
||||
.then(Mono.defer(() -> {
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
logger.info("请求处理完成,准备保存操作日志: {} {}, 耗时: {}ms", method, path, duration);
|
||||
|
||||
return ReactiveSecurityContextHolder.getContext()
|
||||
.flatMap(securityContext -> {
|
||||
Object principal = securityContext.getAuthentication().getPrincipal();
|
||||
String username = principal instanceof String ? (String) principal : "system";
|
||||
logger.info("获取到用户名: {}", username);
|
||||
return Mono.just(username);
|
||||
})
|
||||
.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));
|
||||
});
|
||||
});
|
||||
return chain.filter(exchange)
|
||||
.then(Mono.defer(() -> {
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
return getCurrentUsername()
|
||||
.flatMap(username -> saveOperationLog(username, method, path, ip, duration, "0", null, finalInfo));
|
||||
}))
|
||||
.onErrorResume(error -> {
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
logger.error("请求处理失败: {} {}, 错误: {}", method, path, error.getMessage());
|
||||
return getCurrentUsername()
|
||||
.flatMap(username -> saveOperationLog(username, method, path, ip, duration, "1",
|
||||
error.getMessage().substring(0, Math.min(error.getMessage().length(), 500)), finalInfo))
|
||||
.then(Mono.error(error));
|
||||
});
|
||||
}
|
||||
|
||||
private OperationInfo findOperationInfo(String method, String path) {
|
||||
String key = method + ":" + path;
|
||||
if (OPERATION_MAPPING.containsKey(key)) {
|
||||
return OPERATION_MAPPING.get(key);
|
||||
}
|
||||
private boolean isWriteOperation(String method) {
|
||||
return HttpMethod.POST.name().equals(method) ||
|
||||
HttpMethod.PUT.name().equals(method) ||
|
||||
HttpMethod.DELETE.name().equals(method) ||
|
||||
HttpMethod.PATCH.name().equals(method);
|
||||
}
|
||||
|
||||
for (Map.Entry<String, OperationInfo> entry : OPERATION_MAPPING.entrySet()) {
|
||||
String mappingKey = entry.getKey();
|
||||
if (key.startsWith(mappingKey)) {
|
||||
private OperationInfo findPrefixMatch(String key) {
|
||||
for (Map.Entry<String, OperationInfo> entry : PREFIX_MAPPING.entrySet()) {
|
||||
if (key.startsWith(entry.getKey())) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
final String module;
|
||||
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.ServerHttpSecurity;
|
||||
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
|
||||
@EnableWebFluxSecurity
|
||||
@@ -29,6 +34,20 @@ public class SecurityConfig {
|
||||
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
|
||||
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
||||
String[] activeProfiles = environment.getActiveProfiles();
|
||||
@@ -41,6 +60,7 @@ public class SecurityConfig {
|
||||
activeProfiles.length > 0 ? String.join(",", activeProfiles) : "default", isDevOrTest);
|
||||
|
||||
http
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(ServerHttpSecurity.CsrfSpec::disable)
|
||||
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
|
||||
.formLogin(ServerHttpSecurity.FormLoginSpec::disable)
|
||||
|
||||
+2
@@ -53,6 +53,8 @@ public interface ISysUserService {
|
||||
|
||||
Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword);
|
||||
|
||||
Mono<Boolean> verifyPassword(Long userId, String password);
|
||||
|
||||
Mono<Void> updateRoleIdToNullByRoleId(Long roleId);
|
||||
|
||||
Mono<Void> assignRolesToUser(Long userId, java.util.List<Long> roleIds);
|
||||
|
||||
+3
@@ -120,6 +120,9 @@ public class SysPermissionService implements ISysPermissionService {
|
||||
|
||||
@Override
|
||||
public Flux<SysPermission> findByRoleIds(List<Long> roleIds) {
|
||||
if (roleIds == null || roleIds.isEmpty()) {
|
||||
return Flux.empty();
|
||||
}
|
||||
return permissionRepository.findByRoleIds(roleIds);
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -83,7 +83,6 @@ public class SysRoleService implements ISysRoleService {
|
||||
@Override
|
||||
public Mono<SysRole> createRole(CreateRoleCommand command) {
|
||||
SysRole role = new SysRole();
|
||||
role.generateId();
|
||||
role.setRoleName(command.roleName());
|
||||
role.setRoleKey(command.roleKey());
|
||||
role.setRoleSort(command.roleSort());
|
||||
|
||||
+7
-2
@@ -97,7 +97,6 @@ public class SysUserService implements ISysUserService {
|
||||
logger.info("SysUserService.createUser - 用户名: {}, 密码前缀: {}",
|
||||
user.getUsername(),
|
||||
user.getPassword() != null ? user.getPassword().substring(0, 7) : "null");
|
||||
user.generateId();
|
||||
if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")
|
||||
&& !user.getPassword().startsWith("$2b$")) {
|
||||
logger.info("密码不以$2a$或$2b$开头,重新编码");
|
||||
@@ -117,7 +116,6 @@ public class SysUserService implements ISysUserService {
|
||||
@Override
|
||||
public Mono<SysUser> createUser(CreateUserCommand command) {
|
||||
SysUser user = new SysUser();
|
||||
user.generateId();
|
||||
user.setUsername(command.username().getValue());
|
||||
user.setPassword(passwordEncoder.encode(command.password().getValue()));
|
||||
user.setEmail(command.email().getValue());
|
||||
@@ -204,6 +202,13 @@ public class SysUserService implements ISysUserService {
|
||||
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
|
||||
public Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword) {
|
||||
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 java.util.List;
|
||||
|
||||
/**
|
||||
* 认证响应DTO
|
||||
*
|
||||
@@ -20,13 +22,21 @@ public class AuthResponse {
|
||||
@Schema(description = "用户名", example = "admin")
|
||||
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(String token, Long userId, String username) {
|
||||
public AuthResponse(String token, Long userId, String username, List<String> roles, List<String> permissions) {
|
||||
this.token = token;
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.roles = roles;
|
||||
this.permissions = permissions;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
@@ -52,4 +62,20 @@ public class AuthResponse {
|
||||
public void setUsername(String 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.service.ISysUserService;
|
||||
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.IpLocationParser;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -50,6 +52,7 @@ public class SysAuthHandler {
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final ISysLoginLogService loginLogService;
|
||||
private final ISysPermissionService permissionService;
|
||||
private final UserAgentParser userAgentParser;
|
||||
private final IpLocationParser ipLocationParser;
|
||||
|
||||
@@ -60,11 +63,13 @@ public class SysAuthHandler {
|
||||
public SysAuthHandler(ISysUserService userService,
|
||||
@Qualifier("passwordEncoder") PasswordEncoder passwordEncoder,
|
||||
JwtTokenProvider jwtTokenProvider, ISysLoginLogService loginLogService,
|
||||
ISysPermissionService permissionService,
|
||||
UserAgentParser userAgentParser, IpLocationParser ipLocationParser) {
|
||||
this.userService = userService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
this.loginLogService = loginLogService;
|
||||
this.permissionService = permissionService;
|
||||
this.userAgentParser = userAgentParser;
|
||||
this.ipLocationParser = ipLocationParser;
|
||||
|
||||
@@ -126,29 +131,49 @@ public class SysAuthHandler {
|
||||
}
|
||||
|
||||
return userService.getUserRoles(user.getId())
|
||||
.map(role -> role.getRoleKey())
|
||||
.collectList()
|
||||
.flatMap(roleKeys -> {
|
||||
String token = jwtTokenProvider
|
||||
.generateToken(
|
||||
.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 -> {
|
||||
String token = jwtTokenProvider
|
||||
.generateToken(
|
||||
user.getUsername(),
|
||||
user.getId(),
|
||||
roleKeys);
|
||||
logger.info("用户登录成功: username={}, userId={}, roles={}",
|
||||
user.getUsername(),
|
||||
user.getId(),
|
||||
roleKeys);
|
||||
recordLoginLog(loginRequest
|
||||
.getUsername(),
|
||||
clientIp,
|
||||
"0", "登录成功",
|
||||
userAgent);
|
||||
AuthResponse response = new AuthResponse(
|
||||
token,
|
||||
user.getId(),
|
||||
user.getUsername());
|
||||
return ServerResponse.ok()
|
||||
.bodyValue(response);
|
||||
logger.info("用户登录成功: username={}, userId={}, roles={}, permissions={}",
|
||||
user.getUsername(),
|
||||
user.getId(),
|
||||
roleKeys,
|
||||
permCodes.size());
|
||||
recordLoginLog(loginRequest.getUsername(),
|
||||
clientIp,
|
||||
"0", "登录成功",
|
||||
userAgent);
|
||||
AuthResponse response = new AuthResponse(
|
||||
token,
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
roleKeys,
|
||||
permCodes);
|
||||
return ServerResponse.ok()
|
||||
.bodyValue(response);
|
||||
});
|
||||
});
|
||||
})
|
||||
.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) {
|
||||
try {
|
||||
SysLoginLog loginLog = new SysLoginLog();
|
||||
|
||||
+34
-6
@@ -1,7 +1,11 @@
|
||||
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.SysRole;
|
||||
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.tags.Tag;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -22,10 +26,19 @@ import java.util.List;
|
||||
@Tag(name = "权限管理", description = "权限相关操作")
|
||||
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.roleService = roleService;
|
||||
this.userService = userService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有权限", description = "获取系统中所有权限列表")
|
||||
@@ -97,12 +110,27 @@ public class SysPermissionHandler {
|
||||
.body(permissionService.getPermissionsByRoleId(roleId), SysPermission.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表")
|
||||
@Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表,需验证管理员密码,超级管理员角色不可被分配")
|
||||
public Mono<ServerResponse> assignPermissionsToRole(ServerRequest request) {
|
||||
Long roleId = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(AssignPermissionsRequest.class)
|
||||
.flatMap(req -> permissionService.assignPermissionsToRole(roleId, req.permissionIds()))
|
||||
.then(ServerResponse.ok().build());
|
||||
|
||||
return verifyAdminPassword(request)
|
||||
.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) {}
|
||||
|
||||
+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.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.sys.dto.request.RoleCreateRequest;
|
||||
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
||||
@@ -30,12 +32,18 @@ import java.util.Map;
|
||||
@Tag(name = "角色管理", description = "角色相关操作")
|
||||
public class SysRoleHandler {
|
||||
|
||||
private static final Long BUILTIN_ROLE_ID = 1L;
|
||||
|
||||
private final ISysRoleService roleService;
|
||||
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.validator = validator;
|
||||
this.authUtil = authUtil;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有角色", description = "获取系统中所有角色列表")
|
||||
@@ -115,30 +123,39 @@ public class SysRoleHandler {
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新角色", description = "更新角色信息")
|
||||
@Operation(summary = "更新角色", description = "更新角色信息,需验证管理员密码,超级管理员角色不可被编辑")
|
||||
@OperationLog(operation = "更新角色", module = "角色管理")
|
||||
public Mono<ServerResponse> updateRole(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(RoleUpdateRequest.class)
|
||||
.map(req -> UpdateRoleCommand.of(
|
||||
id,
|
||||
req.getRoleName(),
|
||||
req.getRoleKey(),
|
||||
req.getRoleSort(),
|
||||
req.getStatus()
|
||||
))
|
||||
.flatMap(roleService::updateRole)
|
||||
.flatMap(updatedRole -> ServerResponse.ok().bodyValue(updatedRole))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
|
||||
return verifyAdminPassword(request)
|
||||
.flatMap(valid -> {
|
||||
if (!valid) return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||
if (BUILTIN_ROLE_ID.equals(id)) return ServerResponse.badRequest().bodyValue("超级管理员角色不可编辑");
|
||||
return request.bodyToMono(RoleUpdateRequest.class)
|
||||
.map(req -> UpdateRoleCommand.of(
|
||||
id, req.getRoleName(), req.getRoleKey(),
|
||||
req.getRoleSort(), req.getStatus()
|
||||
))
|
||||
.flatMap(roleService::updateRole)
|
||||
.flatMap(updatedRole -> ServerResponse.ok().bodyValue(updatedRole))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "删除角色", description = "逻辑删除角色")
|
||||
@Operation(summary = "删除角色", description = "逻辑删除角色,需验证管理员密码,超级管理员角色不可被删除")
|
||||
@OperationLog(operation = "删除角色", module = "角色管理")
|
||||
public Mono<ServerResponse> deleteRole(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return roleService.logicalDeleteRole(id)
|
||||
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
|
||||
return verifyAdminPassword(request)
|
||||
.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 = "恢复被逻辑删除的角色")
|
||||
@@ -148,4 +165,13 @@ public class SysRoleHandler {
|
||||
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
||||
.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.service.ISysUserService;
|
||||
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||
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.PasswordChangeRequest;
|
||||
@@ -42,10 +43,12 @@ public class SysUserHandler {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SysUserHandler.class);
|
||||
private final ISysUserService userService;
|
||||
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.validator = validator;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有用户", description = "获取系统中所有用户列表")
|
||||
@@ -152,39 +155,63 @@ public class SysUserHandler {
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新用户", description = "更新用户信息")
|
||||
@Operation(summary = "更新用户", description = "更新用户信息,需验证管理员密码,超级管理员不可编辑")
|
||||
@OperationLog(operation = "更新用户", module = "用户管理")
|
||||
public Mono<ServerResponse> updateUser(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(UserUpdateRequest.class)
|
||||
.map(req -> {
|
||||
boolean clearRole = Boolean.TRUE.equals(req.getClearRole()) ||
|
||||
(req.getRoleId() == null && req.getClearRole() != null);
|
||||
return UpdateUserCommand.of(
|
||||
id,
|
||||
null,
|
||||
null,
|
||||
req.getEmail(),
|
||||
req.getRoleId(),
|
||||
req.getStatus(),
|
||||
clearRole
|
||||
);
|
||||
})
|
||||
.flatMap(userService::updateUser)
|
||||
.flatMap(user -> ServerResponse.ok().bodyValue(user))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
|
||||
return verifyAdminPassword(request)
|
||||
.flatMap(valid -> {
|
||||
if (!valid) {
|
||||
return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||
}
|
||||
return userService.findById(id)
|
||||
.flatMap(user -> {
|
||||
if ("admin".equals(user.getUsername())) {
|
||||
return Mono.<ServerResponse>error(new RuntimeException("超级管理员不可编辑"));
|
||||
}
|
||||
return request.bodyToMono(UserUpdateRequest.class)
|
||||
.map(req -> {
|
||||
boolean clearRole = Boolean.TRUE.equals(req.getClearRole()) ||
|
||||
(req.getRoleId() == null && req.getClearRole() != null);
|
||||
return UpdateUserCommand.of(
|
||||
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 = "用户管理")
|
||||
public Mono<ServerResponse> deleteUser(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return userService.findById(id)
|
||||
.flatMap(user -> userService.deleteUser(id)
|
||||
.then(ServerResponse.noContent().build()))
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("User not found")))
|
||||
|
||||
return verifyAdminPassword(request)
|
||||
.flatMap(valid -> {
|
||||
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 -> {
|
||||
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 Mono.error(ex);
|
||||
@@ -258,16 +285,37 @@ public class SysUserHandler {
|
||||
.flatMap(exists -> ServerResponse.ok().bodyValue(exists));
|
||||
}
|
||||
|
||||
@Operation(summary = "为用户分配角色", description = "为指定用户分配角色列表")
|
||||
@Operation(summary = "为用户分配角色", description = "为指定用户分配角色列表,需验证管理员密码,超级管理员不可分配")
|
||||
@OperationLog(operation = "分配角色", module = "用户管理")
|
||||
public Mono<ServerResponse> assignRoles(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(AssignRolesRequest.class)
|
||||
.flatMap(req -> userService.assignRolesToUser(id, req.getRoleIdsAsLong()))
|
||||
.then(ServerResponse.ok().build())
|
||||
.onErrorResume(error -> {
|
||||
logger.error("分配角色失败", error);
|
||||
return ServerResponse.status(500).bodyValue("分配角色失败: " + error.getMessage());
|
||||
|
||||
return verifyAdminPassword(request)
|
||||
.flatMap(valid -> {
|
||||
if (!valid) {
|
||||
return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||
}
|
||||
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()
|
||||
.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,34 @@
|
||||
import { get, post, put, del } from '@/api/request'
|
||||
import type { AxiosRequestConfig } from 'axios'
|
||||
|
||||
export function getAllBanners(params?: any) {
|
||||
return get('/api/banner/list', params)
|
||||
}
|
||||
|
||||
export function getActiveBanners() {
|
||||
return get('/api/banner/active')
|
||||
}
|
||||
|
||||
export function getBannerById(id: number) {
|
||||
return get(`/api/banner/${id}`)
|
||||
}
|
||||
|
||||
export function createBanner(data: any) {
|
||||
return post('/api/banner', data)
|
||||
}
|
||||
|
||||
export function updateBanner(id: number, data: any, config?: AxiosRequestConfig) {
|
||||
return put(`/api/banner/${id}`, data, config)
|
||||
}
|
||||
|
||||
export function deleteBanner(id: number, config?: AxiosRequestConfig) {
|
||||
return del(`/api/banner/${id}`, config)
|
||||
}
|
||||
|
||||
export function enableBanner(id: number) {
|
||||
return post(`/api/banner/${id}/enable`)
|
||||
}
|
||||
|
||||
export function disableBanner(id: number, config?: AxiosRequestConfig) {
|
||||
return post(`/api/banner/${id}/disable`, null, config)
|
||||
}
|
||||
@@ -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,22 @@
|
||||
import { get, put } from '@/api/request'
|
||||
|
||||
/**
|
||||
* 获取所有配置列表
|
||||
*/
|
||||
export function getAllConfigs(params?: any) {
|
||||
return get('/api/config', params)
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据配置键获取配置
|
||||
*/
|
||||
export function getConfigByKey(configKey: string) {
|
||||
return get(`/api/config/key/${configKey}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新配置
|
||||
*/
|
||||
export function updateConfig(id: number, data: any) {
|
||||
return put(`/api/config/${id}`, 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,59 @@
|
||||
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)
|
||||
}
|
||||
|
||||
export function getGroupCourseQRCode(id: number) {
|
||||
return get(`/api/groupCourse/${id}/qrcode`)
|
||||
}
|
||||
@@ -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,9 @@
|
||||
import { get } from '@/api/request'
|
||||
|
||||
export function getRevenueStatistics() {
|
||||
return get('/api/payment/revenue/statistics')
|
||||
}
|
||||
|
||||
export function getPaymentRecords(params?: any) {
|
||||
return get('/api/payment/revenue/records', 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,104 @@
|
||||
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: 'banner',
|
||||
name: 'Banner',
|
||||
component: () => import('@/views/banner/index.vue'),
|
||||
meta: { title: '轮播图', icon: 'Picture' },
|
||||
},
|
||||
{
|
||||
path: 'datacount',
|
||||
name: 'DataCount',
|
||||
component: () => import('@/views/datacount/index.vue'),
|
||||
meta: { title: '数据报表', icon: 'DataAnalysis' },
|
||||
},
|
||||
{
|
||||
path: 'payment/revenue',
|
||||
name: 'PaymentRevenue',
|
||||
component: () => import('@/views/payment/revenue/index.vue'),
|
||||
meta: { title: '营收详情', icon: 'Money' },
|
||||
},
|
||||
{
|
||||
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 }
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user