Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
836f0e1cbf | ||
|
|
44da3cab6e | ||
|
|
cf7e2560b5 | ||
|
|
fa94f52b53 | ||
|
|
566e949588 | ||
|
|
e61fa6de00 | ||
|
|
efd4d03037 | ||
|
|
80759f6793 | ||
|
|
f8279129be | ||
|
|
f1614c7d45 | ||
|
|
886e2748d5 | ||
|
|
1a5aa9b3ef | ||
|
|
0140bb0cc8 |
+43
@@ -194,4 +194,47 @@ public class CheckInHandler {
|
|||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询所有签到记录(支持排序)
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/admin/records
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getAllSignInRecords(ServerRequest request) {
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
String sortBy = request.queryParam("sortBy").orElse("signInTime");
|
||||||
|
String sortOrder = request.queryParam("sortOrder").orElse("desc");
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("管理员查询所有签到记录, startDate: {}, endDate: {}, sortBy: {}, sortOrder: {}", startDate, endDate, sortBy, sortOrder);
|
||||||
|
|
||||||
|
return checkService.getAllSignInRecords(startDate, endDate, sortBy, sortOrder)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(records -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", records)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询签到统计(不限会员)
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/admin/statistics
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getAllSignInStatistics(ServerRequest request) {
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("管理员查询签到统计, startDate: {}, endDate: {}", startDate, endDate);
|
||||||
|
|
||||||
|
return checkService.getAllSignInStats(startDate, endDate)
|
||||||
|
.flatMap(stats -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
@@ -57,6 +57,12 @@ public interface SignInRecordRepository extends R2dbcRepository<SignInRecord, Lo
|
|||||||
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
Flux<SignInRecord> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
Flux<SignInRecord> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据时间范围查询签到记录(支持动态排序)
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByTimeRangeSorted(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 统计会员在时间范围内的签到次数
|
* 统计会员在时间范围内的签到次数
|
||||||
*/
|
*/
|
||||||
|
|||||||
+16
@@ -78,4 +78,20 @@ public interface ICheckInService {
|
|||||||
* @return 签到统计VO
|
* @return 签到统计VO
|
||||||
*/
|
*/
|
||||||
Mono<SignInStatsVO> getDailySignInStats(LocalDate date);
|
Mono<SignInStatsVO> getDailySignInStats(LocalDate date);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询所有签到记录(支持排序)
|
||||||
|
*
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @param sortBy 排序字段
|
||||||
|
* @param sortOrder 排序方向
|
||||||
|
* @return 签到记录列表(含会员姓名、卡类型)
|
||||||
|
*/
|
||||||
|
Flux<SignInRecordVO> getAllSignInRecords(LocalDate startTime, LocalDate endTime, String sortBy, String sortOrder);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理员查询签到统计(不限会员)
|
||||||
|
*/
|
||||||
|
Mono<SignInStatsVO> getAllSignInStats(LocalDate startTime, LocalDate endTime);
|
||||||
}
|
}
|
||||||
|
|||||||
+81
-1
@@ -16,11 +16,13 @@ import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
|||||||
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||||
|
import cn.novalon.gym.manage.member.entity.Member;
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
import cn.novalon.gym.manage.member.repository.IMemberRepository;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -47,6 +49,7 @@ public class CheckServiceImpl implements ICheckInService {
|
|||||||
private final MemberCardRepository memberCardRepository;
|
private final MemberCardRepository memberCardRepository;
|
||||||
private final SignInRecordRepository signInRecordRepository;
|
private final SignInRecordRepository signInRecordRepository;
|
||||||
private final IGroupCourseBookingService groupCourseBookingService;
|
private final IGroupCourseBookingService groupCourseBookingService;
|
||||||
|
private final IMemberRepository memberRepository;
|
||||||
|
|
||||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||||
|
|
||||||
@@ -430,6 +433,83 @@ public class CheckServiceImpl implements ICheckInService {
|
|||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Flux<SignInRecordVO> getAllSignInRecords(LocalDate startTime, LocalDate endTime, String sortBy, String sortOrder) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
Flux<SignInRecord> recordFlux = signInRecordRepository.findByTimeRangeSorted(start, end);
|
||||||
|
|
||||||
|
return recordFlux
|
||||||
|
.flatMap(record -> {
|
||||||
|
// fetch member name
|
||||||
|
Mono<String> memberNameMono = memberRepository.findById(record.getMemberId())
|
||||||
|
.map(Member::getNickname)
|
||||||
|
.defaultIfEmpty("未知");
|
||||||
|
// fetch card type name
|
||||||
|
Mono<String> cardTypeMono = record.getMemberCardId() != null
|
||||||
|
? memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(record.getMemberCardId())
|
||||||
|
.map(MemberCard::getMemberCardName)
|
||||||
|
.defaultIfEmpty("未知")
|
||||||
|
: Mono.just("-");
|
||||||
|
return Mono.zip(memberNameMono, cardTypeMono)
|
||||||
|
.map(tuple -> {
|
||||||
|
SignInRecordVO vo = convertToVO(record);
|
||||||
|
vo.setMemberName(tuple.getT1());
|
||||||
|
vo.setMemberCardType(tuple.getT2());
|
||||||
|
return vo;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.collectList()
|
||||||
|
.flatMapMany(list -> {
|
||||||
|
// in-memory sort
|
||||||
|
boolean asc = "asc".equalsIgnoreCase(sortOrder);
|
||||||
|
java.util.Comparator<SignInRecordVO> comparator;
|
||||||
|
switch (sortBy != null ? sortBy : "signInTime") {
|
||||||
|
case "id":
|
||||||
|
comparator = java.util.Comparator.comparing(SignInRecordVO::getId, java.util.Comparator.nullsLast(Long::compareTo));
|
||||||
|
break;
|
||||||
|
case "memberName":
|
||||||
|
comparator = java.util.Comparator.comparing(SignInRecordVO::getMemberName, java.util.Comparator.nullsLast(String::compareTo));
|
||||||
|
break;
|
||||||
|
case "signInTime":
|
||||||
|
default:
|
||||||
|
comparator = java.util.Comparator.comparing(SignInRecordVO::getSignInTime, java.util.Comparator.nullsLast(java.time.LocalDateTime::compareTo));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!asc) {
|
||||||
|
comparator = comparator.reversed();
|
||||||
|
}
|
||||||
|
list.sort(comparator);
|
||||||
|
return Flux.fromIterable(list);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatsVO> getAllSignInStats(LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return Mono.zip(
|
||||||
|
(Object[] results) -> {
|
||||||
|
Long total = (Long) results[0];
|
||||||
|
Long success = (Long) results[1];
|
||||||
|
Long members = (Long) results[2];
|
||||||
|
SignInStatsVO stats = new SignInStatsVO();
|
||||||
|
stats.setTotalCount(total);
|
||||||
|
stats.setSuccessCount(success);
|
||||||
|
stats.setStartDate(startTime);
|
||||||
|
stats.setEndDate(endTime);
|
||||||
|
stats.setUniqueMemberCount(members);
|
||||||
|
stats.setSuccessRate(total > 0 ? (double) success / total * 100.0 : 0.0);
|
||||||
|
return stats;
|
||||||
|
},
|
||||||
|
signInRecordRepository.countByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countSuccessByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countDistinctMembersByTimeRange(start, end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private long getSecondsUntilEndOfDay() {
|
private long getSecondsUntilEndOfDay() {
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
||||||
|
|||||||
+10
@@ -59,6 +59,16 @@ public class SignInRecordVO {
|
|||||||
*/
|
*/
|
||||||
private String source;
|
private String source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员姓名(关联查询)
|
||||||
|
*/
|
||||||
|
private String memberName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员卡类型名称(关联查询)
|
||||||
|
*/
|
||||||
|
private String memberCardType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建时间
|
* 创建时间
|
||||||
*/
|
*/
|
||||||
|
|||||||
+6
-2
@@ -14,6 +14,7 @@ import cn.novalon.gym.manage.member.entity.MemberCard;
|
|||||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.IMemberRepository;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -57,6 +58,9 @@ class CheckInModuleTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private IGroupCourseBookingService groupCourseBookingService;
|
private IGroupCourseBookingService groupCourseBookingService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private IMemberRepository memberRepository;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private MemberCard mockMemberCard;
|
private MemberCard mockMemberCard;
|
||||||
|
|
||||||
@@ -72,7 +76,7 @@ class CheckInModuleTest {
|
|||||||
void setUp() {
|
void setUp() {
|
||||||
MockitoAnnotations.openMocks(this);
|
MockitoAnnotations.openMocks(this);
|
||||||
checkService = new CheckServiceImpl(qrCodeConfig, redisUtil, memberCardRecordRepository,
|
checkService = new CheckServiceImpl(qrCodeConfig, redisUtil, memberCardRecordRepository,
|
||||||
memberCardRepository, signInRecordRepository, groupCourseBookingService);
|
memberCardRepository, signInRecordRepository, groupCourseBookingService, memberRepository);
|
||||||
|
|
||||||
when(mockMemberCard.getId()).thenReturn(1L);
|
when(mockMemberCard.getId()).thenReturn(1L);
|
||||||
when(mockMemberCard.getMemberCardType()).thenReturn("TIME_CARD");
|
when(mockMemberCard.getMemberCardType()).thenReturn("TIME_CARD");
|
||||||
@@ -127,7 +131,7 @@ class CheckInModuleTest {
|
|||||||
|
|
||||||
when(redisUtil.get(eq(key))).thenReturn(Mono.just(qrData));
|
when(redisUtil.get(eq(key))).thenReturn(Mono.just(qrData));
|
||||||
when(memberCardRecordRepository.findById(1L)).thenReturn(Mono.just(mockMemberCardRecord));
|
when(memberCardRecordRepository.findById(1L)).thenReturn(Mono.just(mockMemberCardRecord));
|
||||||
when(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(1L)).thenReturn(Flux.just(mockMemberCard));
|
when(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(1L)).thenReturn(Mono.just(mockMemberCard));
|
||||||
when(signInRecordRepository.save(any(SignInRecord.class))).thenReturn(Mono.just(mockSignInRecord));
|
when(signInRecordRepository.save(any(SignInRecord.class))).thenReturn(Mono.just(mockSignInRecord));
|
||||||
when(redisUtil.set(any(String.class), any(Map.class))).thenReturn(Mono.just(true));
|
when(redisUtil.set(any(String.class), any(Map.class))).thenReturn(Mono.just(true));
|
||||||
when(groupCourseBookingService.getBookingsByMemberId(memberId)).thenReturn(Flux.empty());
|
when(groupCourseBookingService.getBookingsByMemberId(memberId)).thenReturn(Flux.empty());
|
||||||
|
|||||||
+2
-2
@@ -26,7 +26,7 @@ public class DataStatisticsDao {
|
|||||||
* 统计指定时间范围内新增会员数
|
* 统计指定时间范围内新增会员数
|
||||||
*/
|
*/
|
||||||
public Mono<Long> countNewMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
public Mono<Long> countNewMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE created_at >= :startTime AND created_at < :endTime AND is_deleted = false")
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE created_at >= :startTime AND created_at < :endTime AND deleted_at IS NULL")
|
||||||
.bind("startTime", startTime)
|
.bind("startTime", startTime)
|
||||||
.bind("endTime", endTime)
|
.bind("endTime", endTime)
|
||||||
.map(row -> row.get(0, Long.class))
|
.map(row -> row.get(0, Long.class))
|
||||||
@@ -37,7 +37,7 @@ public class DataStatisticsDao {
|
|||||||
* 统计总会员数
|
* 统计总会员数
|
||||||
*/
|
*/
|
||||||
public Mono<Long> countTotalMembers() {
|
public Mono<Long> countTotalMembers() {
|
||||||
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE is_deleted = false")
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE deleted_at IS NULL")
|
||||||
.map(row -> row.get(0, Long.class))
|
.map(row -> row.get(0, Long.class))
|
||||||
.one();
|
.one();
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -4,6 +4,8 @@ import cn.novalon.gym.manage.datacount.domain.*;
|
|||||||
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
@@ -25,6 +27,8 @@ import java.time.format.DateTimeFormatter;
|
|||||||
@Tag(name = "数据统计", description = "数据统计相关操作")
|
@Tag(name = "数据统计", description = "数据统计相关操作")
|
||||||
public class DataStatisticsHandler {
|
public class DataStatisticsHandler {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DataStatisticsHandler.class);
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IDataStatisticsService dataStatisticsService;
|
private IDataStatisticsService dataStatisticsService;
|
||||||
|
|
||||||
@@ -35,6 +39,7 @@ public class DataStatisticsHandler {
|
|||||||
return dataStatisticsService.getStatisticsSummaryWithCache(query)
|
return dataStatisticsService.getStatisticsSummaryWithCache(query)
|
||||||
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
||||||
.onErrorResume(e -> {
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取综合统计数据失败", e);
|
||||||
StatisticsSummary errorSummary = StatisticsSummary.builder()
|
StatisticsSummary errorSummary = StatisticsSummary.builder()
|
||||||
.statDate(LocalDateTime.now().toLocalDate().toString())
|
.statDate(LocalDateTime.now().toLocalDate().toString())
|
||||||
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
|
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
|
||||||
|
|||||||
+82
-9
@@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
@@ -22,7 +23,9 @@ import java.time.LocalDate;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
import java.time.temporal.TemporalAdjusters;
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -173,9 +176,25 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
|
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
|
||||||
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query);
|
String statDate = query.getStartTime() != null
|
||||||
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query);
|
? query.getStartTime().toLocalDate().toString()
|
||||||
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query);
|
: LocalDateTime.now().toLocalDate().toString();
|
||||||
|
|
||||||
|
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取会员统计数据失败", e);
|
||||||
|
return Mono.just(MemberStatistics.builder().statDate(statDate).build());
|
||||||
|
});
|
||||||
|
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取预约统计数据失败", e);
|
||||||
|
return Mono.just(BookingStatistics.builder().statDate(statDate).build());
|
||||||
|
});
|
||||||
|
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query)
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("获取签到统计数据失败", e);
|
||||||
|
return Mono.just(SignInStatistics.builder().statDate(statDate).build());
|
||||||
|
});
|
||||||
|
|
||||||
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono)
|
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono)
|
||||||
.map(tuple -> StatisticsSummary.builder()
|
.map(tuple -> StatisticsSummary.builder()
|
||||||
@@ -188,21 +207,75 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public reactor.core.publisher.Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
public Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
||||||
// 历史统计数据查询(从Redis缓存中获取)
|
// 历史统计数据查询(从Redis缓存中获取)
|
||||||
String cacheKey = buildCacheKey(query);
|
String cacheKey = buildCacheKey(query);
|
||||||
return redisUtil.get(cacheKey, String.class)
|
return redisUtil.get(cacheKey, String.class)
|
||||||
.flatMapMany(json -> {
|
.flatMapMany(json -> {
|
||||||
try {
|
try {
|
||||||
java.util.List<DataStatistics> stats = objectMapper.readValue(json,
|
List<DataStatistics> stats = objectMapper.readValue(json,
|
||||||
objectMapper.getTypeFactory().constructCollectionType(java.util.List.class, DataStatistics.class));
|
objectMapper.getTypeFactory().constructCollectionType(List.class, DataStatistics.class));
|
||||||
return reactor.core.publisher.Flux.fromIterable(stats);
|
return Flux.fromIterable(stats);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to parse historical statistics from cache", e);
|
log.error("Failed to parse historical statistics from cache", e);
|
||||||
return reactor.core.publisher.Flux.empty();
|
return Flux.empty();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.switchIfEmpty(reactor.core.publisher.Flux.empty());
|
.switchIfEmpty(buildLiveStatistics(query));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缓存未命中时,从数据库实时构建统计数据
|
||||||
|
*/
|
||||||
|
private Flux<DataStatistics> buildLiveStatistics(StatisticsQuery query) {
|
||||||
|
LocalDateTime startTime = getStartTime(query);
|
||||||
|
LocalDateTime endTime = getEndTime(query);
|
||||||
|
String periodType = query.getPeriodType() != null ? query.getPeriodType() : "DAY";
|
||||||
|
LocalDateTime statDate = endTime;
|
||||||
|
|
||||||
|
Mono<Long> memberCountMono = dataStatisticsDao.countNewMembers(startTime, endTime);
|
||||||
|
Mono<Long> totalMembersMono = dataStatisticsDao.countTotalMembers();
|
||||||
|
Mono<Long> bookingCountMono = dataStatisticsDao.countBookings(startTime, endTime);
|
||||||
|
Mono<Long> signInCountMono = dataStatisticsDao.countSignIns(startTime, endTime);
|
||||||
|
|
||||||
|
return Mono.zip(memberCountMono, totalMembersMono, bookingCountMono, signInCountMono)
|
||||||
|
.flatMapMany(tuple -> {
|
||||||
|
long newMembers = tuple.getT1() != null ? tuple.getT1() : 0L;
|
||||||
|
long totalMembers = tuple.getT2() != null ? tuple.getT2() : 0L;
|
||||||
|
long bookings = tuple.getT3() != null ? tuple.getT3() : 0L;
|
||||||
|
long signIns = tuple.getT4() != null ? tuple.getT4() : 0L;
|
||||||
|
|
||||||
|
List<DataStatistics> list = new ArrayList<>();
|
||||||
|
|
||||||
|
DataStatistics memberStat = DataStatistics.builder()
|
||||||
|
.statType(DataStatistics.StatType.MEMBER)
|
||||||
|
.periodType(periodType)
|
||||||
|
.statDate(statDate)
|
||||||
|
.count(totalMembers)
|
||||||
|
.extraData("新增" + newMembers + "人")
|
||||||
|
.build();
|
||||||
|
list.add(memberStat);
|
||||||
|
|
||||||
|
DataStatistics bookingStat = DataStatistics.builder()
|
||||||
|
.statType(DataStatistics.StatType.BOOKING)
|
||||||
|
.periodType(periodType)
|
||||||
|
.statDate(statDate)
|
||||||
|
.count(bookings)
|
||||||
|
.extraData("新增" + bookings + "条预约")
|
||||||
|
.build();
|
||||||
|
list.add(bookingStat);
|
||||||
|
|
||||||
|
DataStatistics signInStat = DataStatistics.builder()
|
||||||
|
.statType(DataStatistics.StatType.SIGN_IN)
|
||||||
|
.periodType(periodType)
|
||||||
|
.statDate(statDate)
|
||||||
|
.count(signIns)
|
||||||
|
.extraData("新增" + signIns + "次签到")
|
||||||
|
.build();
|
||||||
|
list.add(signInStat);
|
||||||
|
|
||||||
|
return Flux.fromIterable(list);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+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);
|
||||||
|
}
|
||||||
+6
@@ -61,6 +61,12 @@ public interface GroupCourseBookingDao extends R2dbcRepository<GroupCourseBookin
|
|||||||
*/
|
*/
|
||||||
Mono<Long> countByCourseIdAndStatusAndDeletedAtIsNull(Long courseId, String status);
|
Mono<Long> countByCourseIdAndStatusAndDeletedAtIsNull(Long courseId, String status);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员取消的预约次数
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("SELECT COUNT(*) FROM group_course_booking WHERE member_id = :memberId AND status = '1' AND deleted_at IS NULL")
|
||||||
|
Mono<Long> countCancelledByMemberId(Long memberId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询会员是否有时间冲突的预约(状态为已预约且未取消)
|
* 查询会员是否有时间冲突的预约(状态为已预约且未取消)
|
||||||
* 时间冲突条件:新课程的开始时间 < 已预约课程的结束时间 且 新课程的结束时间 > 已预约课程的开始时间
|
* 时间冲突条件:新课程的开始时间 < 已预约课程的结束时间 且 新课程的结束时间 > 已预约课程的开始时间
|
||||||
|
|||||||
+24
@@ -40,10 +40,18 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
|||||||
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
|
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET deleted_at = NULL, status = '1', updated_at = :updatedAt WHERE id = :id AND deleted_at IS NOT NULL")
|
||||||
|
Mono<Integer> restoreCourse(Long id, LocalDateTime updatedAt);
|
||||||
|
|
||||||
@Modifying
|
@Modifying
|
||||||
@Query("UPDATE group_course SET status = '2', updated_at = :updatedAt WHERE status = '0' AND end_time <= NOW() AND deleted_at IS NULL")
|
@Query("UPDATE group_course SET status = '2', updated_at = :updatedAt WHERE status = '0' AND end_time <= NOW() AND deleted_at IS NULL")
|
||||||
Mono<Integer> completeExpiredCourses(LocalDateTime updatedAt);
|
Mono<Integer> completeExpiredCourses(LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
@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);
|
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));
|
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||||
|
|
||||||
// 5. 价格排序 / 6. 剩余名额最多排序
|
// 5. 价格排序 / 6. 剩余名额最多排序
|
||||||
@@ -141,6 +154,9 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
|||||||
if (query.getEndDate() != null) {
|
if (query.getEndDate() != null) {
|
||||||
spec = spec.bind("endDate", query.getEndDate());
|
spec = spec.bind("endDate", query.getEndDate());
|
||||||
}
|
}
|
||||||
|
if (query.getIsRecurring() != null) {
|
||||||
|
spec = spec.bind("isRecurring", query.getIsRecurring());
|
||||||
|
}
|
||||||
spec = spec.bind("limit", size);
|
spec = spec.bind("limit", size);
|
||||||
spec = spec.bind("offset", offset);
|
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.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||||
entity.setUpdatedAt(row.get("updated_at", LocalDateTime.class));
|
entity.setUpdatedAt(row.get("updated_at", LocalDateTime.class));
|
||||||
entity.setDeletedAt(row.get("deleted_at", LocalDateTime.class));
|
entity.setDeletedAt(row.get("deleted_at", LocalDateTime.class));
|
||||||
|
entity.setIsRecurring(row.get("is_recurring", Boolean.class));
|
||||||
return entity;
|
return entity;
|
||||||
}).all();
|
}).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));
|
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||||
|
|
||||||
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||||
@@ -223,6 +244,9 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
|||||||
if (query.getEndDate() != null) {
|
if (query.getEndDate() != null) {
|
||||||
spec = spec.bind("endDate", query.getEndDate());
|
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();
|
return spec.map((row, meta) -> row.get(0, Long.class)).one();
|
||||||
}
|
}
|
||||||
|
|||||||
+4
@@ -29,4 +29,8 @@ public interface GroupCourseTypeDao extends R2dbcRepository<GroupCourseTypeEntit
|
|||||||
@Modifying
|
@Modifying
|
||||||
@Query("UPDATE group_course_type SET deleted_at = :deletedAt WHERE id = :id")
|
@Query("UPDATE group_course_type SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course_type SET type_name = :typeName, base_difficulty = :baseDifficulty, description = :description, category = :category, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateFields(Long id, String typeName, Integer baseDifficulty, String description, String category, LocalDateTime updatedAt);
|
||||||
}
|
}
|
||||||
+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")
|
@Schema(description = "二维码路径", example = "D:\\Games\\exmp\\image\\abc123_20260618120000.png")
|
||||||
private String qrCodePath;
|
private String qrCodePath;
|
||||||
|
|
||||||
|
//是否常态化团课
|
||||||
|
@Schema(description = "是否常态化团课", example = "true")
|
||||||
|
private Boolean isRecurring;
|
||||||
|
|
||||||
public String getCourseName() {
|
public String getCourseName() {
|
||||||
return courseName;
|
return courseName;
|
||||||
}
|
}
|
||||||
@@ -163,4 +167,12 @@ public class GroupCourse extends BaseDomain{
|
|||||||
public void setQrCodePath(String qrCodePath) {
|
public void setQrCodePath(String qrCodePath) {
|
||||||
this.qrCodePath = qrCodePath;
|
this.qrCodePath = qrCodePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Boolean getIsRecurring() {
|
||||||
|
return isRecurring;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIsRecurring(Boolean isRecurring) {
|
||||||
|
this.isRecurring = isRecurring;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
@@ -53,6 +53,10 @@ public class GroupCourseBooking extends BaseDomain {
|
|||||||
@Schema(description = "上课地点", example = "健身房A区")
|
@Schema(description = "上课地点", example = "健身房A区")
|
||||||
private String location;
|
private String location;
|
||||||
|
|
||||||
|
//封面图URL(非DB字段,由 Service 从 GroupCourse 填充)
|
||||||
|
@Schema(description = "封面图URL", example = "https://example.com/cover.jpg")
|
||||||
|
private String coverImage;
|
||||||
|
|
||||||
public Long getCourseId() {
|
public Long getCourseId() {
|
||||||
return courseId;
|
return courseId;
|
||||||
}
|
}
|
||||||
@@ -132,4 +136,12 @@ public class GroupCourseBooking extends BaseDomain {
|
|||||||
public void setLocation(String location) {
|
public void setLocation(String location) {
|
||||||
this.location = location;
|
this.location = location;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getCoverImage() {
|
||||||
|
return coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoverImage(String coverImage) {
|
||||||
|
this.coverImage = coverImage;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+11
@@ -40,6 +40,9 @@ public class GroupCourseQueryDto {
|
|||||||
@Schema(description = "每页大小", example = "10")
|
@Schema(description = "每页大小", example = "10")
|
||||||
private Integer size = 10;
|
private Integer size = 10;
|
||||||
|
|
||||||
|
@Schema(description = "是否常态化团课筛选:null-不过滤, true-仅常态化, false-仅非常态化", example = "true")
|
||||||
|
private Boolean isRecurring;
|
||||||
|
|
||||||
// ===== Getters and Setters =====
|
// ===== Getters and Setters =====
|
||||||
|
|
||||||
public String getCourseName() {
|
public String getCourseName() {
|
||||||
@@ -113,4 +116,12 @@ public class GroupCourseQueryDto {
|
|||||||
public void setSize(Integer size) {
|
public void setSize(Integer size) {
|
||||||
this.size = 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")
|
@Column("qr_code_path")
|
||||||
private String qrCodePath;
|
private String qrCodePath;
|
||||||
|
|
||||||
|
//是否常态化团课
|
||||||
|
@Column("is_recurring")
|
||||||
|
private Boolean isRecurring;
|
||||||
|
|
||||||
public String getCourseName() {
|
public String getCourseName() {
|
||||||
return courseName;
|
return courseName;
|
||||||
}
|
}
|
||||||
@@ -165,4 +169,12 @@ public class GroupCourseEntity extends BaseEntity {
|
|||||||
public void setQrCodePath(String qrCodePath) {
|
public void setQrCodePath(String qrCodePath) {
|
||||||
this.qrCodePath = 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+60
-63
@@ -9,11 +9,13 @@ import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
|||||||
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
import cn.novalon.gym.manage.member.service.IMemberCardRecordService;
|
import cn.novalon.gym.manage.member.service.IMemberCardRecordService;
|
||||||
|
import cn.novalon.gym.manage.member.service.IMemberStoredCardService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -34,6 +36,7 @@ public class BookingSagaHandler {
|
|||||||
private final IGroupCourseBookingRepository bookingRepository;
|
private final IGroupCourseBookingRepository bookingRepository;
|
||||||
private final IGroupCourseRepository courseRepository;
|
private final IGroupCourseRepository courseRepository;
|
||||||
private final IMemberCardRecordService memberCardRecordService;
|
private final IMemberCardRecordService memberCardRecordService;
|
||||||
|
private final IMemberStoredCardService memberStoredCardService;
|
||||||
private final MemberCardRepository memberCardRepository;
|
private final MemberCardRepository memberCardRepository;
|
||||||
private final GroupCourseRedisService redisService;
|
private final GroupCourseRedisService redisService;
|
||||||
|
|
||||||
@@ -44,10 +47,10 @@ public class BookingSagaHandler {
|
|||||||
*
|
*
|
||||||
* 步骤:
|
* 步骤:
|
||||||
* 1. 保存预约记录
|
* 1. 保存预约记录
|
||||||
* 2. 扣减会员卡权益
|
* 2. 扣减储值卡余额(储值卡类型)
|
||||||
* 3. 更新课程当前人数
|
* 3. 更新课程当前人数
|
||||||
*/
|
*/
|
||||||
public Mono<GroupCourseBooking> executeBooking(GroupCourseBooking booking, Long recordId) {
|
public Mono<GroupCourseBooking> executeBooking(GroupCourseBooking booking, Long recordId, BigDecimal storedValueAmount) {
|
||||||
List<SagaStep> steps = new ArrayList<>();
|
List<SagaStep> steps = new ArrayList<>();
|
||||||
List<SagaStep> rollbackSteps = new ArrayList<>();
|
List<SagaStep> rollbackSteps = new ArrayList<>();
|
||||||
|
|
||||||
@@ -60,11 +63,11 @@ public class BookingSagaHandler {
|
|||||||
steps.add(step1);
|
steps.add(step1);
|
||||||
rollbackSteps.add(0, step1);
|
rollbackSteps.add(0, step1);
|
||||||
|
|
||||||
// 步骤2:扣减会员卡权益(根据卡类型决定扣除次数还是金额)
|
// 步骤2:扣减权益(根据卡类型)
|
||||||
SagaStep step2 = new SagaStep(
|
SagaStep step2 = new SagaStep(
|
||||||
"扣减会员卡权益",
|
"扣减权益",
|
||||||
deductCardUsageByCardType(booking.getMemberId(), recordId),
|
deductCardUsageByCardType(booking.getMemberId(), recordId, storedValueAmount),
|
||||||
Mono.defer(() -> restoreCardUsageByCardType(booking.getMemberId(), recordId))
|
Mono.defer(() -> restoreCardUsageByCardType(booking.getMemberId(), recordId, storedValueAmount))
|
||||||
);
|
);
|
||||||
steps.add(step2);
|
steps.add(step2);
|
||||||
rollbackSteps.add(0, step2);
|
rollbackSteps.add(0, step2);
|
||||||
@@ -94,7 +97,7 @@ public class BookingSagaHandler {
|
|||||||
/**
|
/**
|
||||||
* 根据会员卡类型扣减权益
|
* 根据会员卡类型扣减权益
|
||||||
*/
|
*/
|
||||||
private Mono<Void> deductCardUsageByCardType(Long memberId, Long recordId) {
|
private Mono<Void> deductCardUsageByCardType(Long memberId, Long recordId, BigDecimal storedValueAmount) {
|
||||||
return memberCardRecordService.findById(recordId)
|
return memberCardRecordService.findById(recordId)
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在")))
|
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在")))
|
||||||
.flatMap(record -> {
|
.flatMap(record -> {
|
||||||
@@ -109,14 +112,13 @@ public class BookingSagaHandler {
|
|||||||
|
|
||||||
switch (cardType) {
|
switch (cardType) {
|
||||||
case COUNT_CARD:
|
case COUNT_CARD:
|
||||||
// 次数卡不再支持团课预约
|
return Mono.error(new RuntimeException("团课预约仅支持储值卡和时长卡支付"));
|
||||||
return Mono.error(new RuntimeException("团课预约仅支持储值卡支付"));
|
|
||||||
case STORED_VALUE_CARD:
|
case STORED_VALUE_CARD:
|
||||||
// 储值卡扣除金额
|
return deductStoredCardBalance(memberId, storedValueAmount);
|
||||||
return deductCardUsage(recordId, 0, DEFAULT_GROUP_COURSE_PRICE);
|
|
||||||
case TIME_CARD:
|
case TIME_CARD:
|
||||||
// 时长卡不扣除,但需验证有效期
|
// 时长卡验证有效期后,仍须从储值卡扣款
|
||||||
return validateTimeCard(record);
|
return validateTimeCard(record)
|
||||||
|
.then(deductStoredCardBalance(memberId, storedValueAmount));
|
||||||
default:
|
default:
|
||||||
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
||||||
}
|
}
|
||||||
@@ -153,11 +155,10 @@ public class BookingSagaHandler {
|
|||||||
/**
|
/**
|
||||||
* 根据会员卡类型恢复权益
|
* 根据会员卡类型恢复权益
|
||||||
*/
|
*/
|
||||||
private Mono<Void> restoreCardUsageByCardType(Long memberId, Long recordId) {
|
private Mono<Void> restoreCardUsageByCardType(Long memberId, Long recordId, BigDecimal storedValueAmount) {
|
||||||
return memberCardRecordService.findById(recordId)
|
return memberCardRecordService.findById(recordId)
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在,无法恢复权益")))
|
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在,无法恢复权益")))
|
||||||
.flatMap(record -> {
|
.flatMap(record -> {
|
||||||
// 验证会员卡归属(memberId为null时跳过验证)
|
|
||||||
if (memberId != null && !record.getMemberId().equals(memberId)) {
|
if (memberId != null && !record.getMemberId().equals(memberId)) {
|
||||||
return Mono.error(new RuntimeException("会员卡不归属当前用户"));
|
return Mono.error(new RuntimeException("会员卡不归属当前用户"));
|
||||||
}
|
}
|
||||||
@@ -168,12 +169,29 @@ public class BookingSagaHandler {
|
|||||||
|
|
||||||
switch (cardType) {
|
switch (cardType) {
|
||||||
case COUNT_CARD:
|
case COUNT_CARD:
|
||||||
// 次数卡不再支持团课预约,无需恢复
|
|
||||||
return Mono.empty();
|
return Mono.empty();
|
||||||
case STORED_VALUE_CARD:
|
case STORED_VALUE_CARD:
|
||||||
return restoreCardUsage(recordId, 0, DEFAULT_GROUP_COURSE_PRICE);
|
// 返还储值卡余额(回滚时全额返还)
|
||||||
case TIME_CARD:
|
BigDecimal amount = storedValueAmount != null ? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.recharge(memberId, amount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
log.info("储值卡回滚返还成功: memberId={}, amount={}", memberId, amount);
|
||||||
return Mono.empty();
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
case TIME_CARD:
|
||||||
|
// 时长卡回滚时也返还储值卡
|
||||||
|
BigDecimal timeAmount = storedValueAmount != null ? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.recharge(memberId, timeAmount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
log.info("储值卡回滚返还成功(时长卡): memberId={}, amount={}", memberId, timeAmount);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
default:
|
default:
|
||||||
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
||||||
}
|
}
|
||||||
@@ -184,7 +202,7 @@ public class BookingSagaHandler {
|
|||||||
/**
|
/**
|
||||||
* 执行取消预约事务
|
* 执行取消预约事务
|
||||||
*/
|
*/
|
||||||
public Mono<GroupCourseBooking> executeCancelBooking(Long bookingId, Long courseId, Long recordId, Long memberId) {
|
public Mono<GroupCourseBooking> executeCancelBooking(Long bookingId, Long courseId, Long recordId, Long memberId, BigDecimal storedValueAmount, long cancelCount) {
|
||||||
List<SagaStep> steps = new ArrayList<>();
|
List<SagaStep> steps = new ArrayList<>();
|
||||||
List<SagaStep> rollbackSteps = new ArrayList<>();
|
List<SagaStep> rollbackSteps = new ArrayList<>();
|
||||||
|
|
||||||
@@ -197,11 +215,12 @@ public class BookingSagaHandler {
|
|||||||
steps.add(step1);
|
steps.add(step1);
|
||||||
rollbackSteps.add(0, step1);
|
rollbackSteps.add(0, step1);
|
||||||
|
|
||||||
// 步骤2:恢复会员卡权益
|
// 步骤2:返还储值卡余额(含手续费逻辑)
|
||||||
SagaStep step2 = new SagaStep(
|
SagaStep step2 = new SagaStep(
|
||||||
"恢复会员卡权益",
|
"返还储值卡余额",
|
||||||
restoreCardUsageByCardType(memberId, recordId),
|
refundStoredCardWithFee(memberId, storedValueAmount, cancelCount),
|
||||||
Mono.defer(() -> deductCardUsageByCardType(memberId, recordId))
|
// 回滚时重新扣减
|
||||||
|
Mono.defer(() -> deductCardUsageByCardType(memberId, recordId, storedValueAmount))
|
||||||
);
|
);
|
||||||
steps.add(step2);
|
steps.add(step2);
|
||||||
rollbackSteps.add(0, step2);
|
rollbackSteps.add(0, step2);
|
||||||
@@ -253,54 +272,32 @@ public class BookingSagaHandler {
|
|||||||
return bookingRepository.deleteById(bookingId);
|
return bookingRepository.deleteById(bookingId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<Void> deductCardUsage(Long recordId, Integer deductTimes, Double deductAmount) {
|
/**
|
||||||
if (deductTimes == 0 && deductAmount == 0.0) {
|
* 从储值卡扣减余额
|
||||||
return Mono.empty();
|
*/
|
||||||
}
|
private Mono<Void> deductStoredCardBalance(Long memberId, BigDecimal storedValueAmount) {
|
||||||
|
BigDecimal amount = storedValueAmount != null && storedValueAmount.compareTo(BigDecimal.ZERO) > 0
|
||||||
return memberCardRecordService.findById(recordId)
|
? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在")))
|
return memberStoredCardService.consume(memberId, amount)
|
||||||
.flatMap(record -> {
|
|
||||||
cn.novalon.gym.manage.member.enums.MemberCardRecordStatus status = record.getStatus();
|
|
||||||
if (status != cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.ACTIVE) {
|
|
||||||
return Mono.error(new RuntimeException("会员卡状态无效,当前状态: " + (status != null ? status.getDesc() : "未知")));
|
|
||||||
}
|
|
||||||
java.time.LocalDateTime expireTime = record.getExpireTime();
|
|
||||||
if (expireTime != null && expireTime.isBefore(java.time.LocalDateTime.now())) {
|
|
||||||
return Mono.error(new RuntimeException("会员卡已过期"));
|
|
||||||
}
|
|
||||||
if (record.getRemainingTimes() != null && deductTimes > 0 && record.getRemainingTimes() < deductTimes) {
|
|
||||||
return Mono.error(new RuntimeException("会员卡剩余次数不足,当前剩余: " + record.getRemainingTimes() + "次"));
|
|
||||||
}
|
|
||||||
if (record.getRemainingAmount() != null && deductAmount > 0 && record.getRemainingAmount() < deductAmount) {
|
|
||||||
return Mono.error(new RuntimeException("会员卡余额不足,当前剩余: " + record.getRemainingAmount()));
|
|
||||||
}
|
|
||||||
return memberCardRecordService.deductUsage(recordId, deductTimes, deductAmount)
|
|
||||||
.flatMap(rows -> {
|
.flatMap(rows -> {
|
||||||
if (rows == 0) {
|
if (rows == 0) {
|
||||||
return Mono.error(new RuntimeException("扣减会员卡权益失败,请重试"));
|
return Mono.error(new RuntimeException("储值卡扣减失败,余额不足"));
|
||||||
}
|
}
|
||||||
|
log.info("储值卡扣减成功: memberId={}, amount={}", memberId, amount);
|
||||||
return Mono.empty();
|
return Mono.empty();
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<Void> restoreCardUsage(Long recordId, Integer addTimes, Double addAmount) {
|
/**
|
||||||
if (addTimes == 0 && addAmount == 0.0) {
|
* 返还储值卡余额(含手续费逻辑,仅用于取消预约)
|
||||||
|
*/
|
||||||
|
private Mono<Void> refundStoredCardWithFee(Long memberId, BigDecimal storedValueAmount, long cancelCount) {
|
||||||
|
BigDecimal amount = storedValueAmount != null && storedValueAmount.compareTo(BigDecimal.ZERO) > 0
|
||||||
|
? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.refundBalanceWithFee(memberId, amount, cancelCount)
|
||||||
|
.flatMap(refundedAmount -> {
|
||||||
|
log.info("储值卡退款成功(含手续费): memberId={}, cancelCount={}, 退款金额={}", memberId, cancelCount, refundedAmount);
|
||||||
return Mono.empty();
|
return Mono.empty();
|
||||||
}
|
|
||||||
|
|
||||||
return memberCardRecordService.findById(recordId)
|
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在,无法恢复权益")))
|
|
||||||
.flatMap(record -> {
|
|
||||||
// 使用当前记录的过期时间,避免清空过期时间
|
|
||||||
return memberCardRecordService.renewCard(recordId, addTimes, addAmount, record.getExpireTime())
|
|
||||||
.flatMap(rows -> {
|
|
||||||
if (rows == 0) {
|
|
||||||
return Mono.error(new RuntimeException("恢复会员卡权益失败,请重试"));
|
|
||||||
}
|
|
||||||
return Mono.empty();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.util.OSSUtil;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.codec.multipart.FilePart;
|
||||||
|
import org.springframework.http.codec.multipart.Part;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用文件上传处理器
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@Tag(name = "文件上传", description = "通用文件上传到阿里云OSS")
|
||||||
|
public class CommonUploadHandler {
|
||||||
|
|
||||||
|
@Operation(summary = "上传图片文件", description = "上传图片到阿里云OSS,返回ossKey和预签名URL")
|
||||||
|
public Mono<ServerResponse> uploadImage(ServerRequest request) {
|
||||||
|
return request.multipartData()
|
||||||
|
.flatMap(multiValueMap -> {
|
||||||
|
List<Part> fileParts = multiValueMap.get("file");
|
||||||
|
if (fileParts == null || fileParts.isEmpty()) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "未选择文件"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Part part = fileParts.get(0);
|
||||||
|
if (!(part instanceof FilePart filePart)) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "文件格式不正确"));
|
||||||
|
}
|
||||||
|
|
||||||
|
String originalFilename = filePart.filename();
|
||||||
|
String ext = "";
|
||||||
|
int dotIndex = originalFilename.lastIndexOf('.');
|
||||||
|
if (dotIndex > 0) {
|
||||||
|
ext = originalFilename.substring(dotIndex);
|
||||||
|
}
|
||||||
|
String newFileName = UUID.randomUUID().toString().replace("-", "") + ext;
|
||||||
|
|
||||||
|
Path tempFile = null;
|
||||||
|
try {
|
||||||
|
tempFile = Files.createTempFile("upload-", newFileName);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Mono.error(new RuntimeException("创建临时文件失败", e));
|
||||||
|
}
|
||||||
|
Path finalTempFile = tempFile;
|
||||||
|
|
||||||
|
return filePart.transferTo(finalTempFile)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
try {
|
||||||
|
String ossKey;
|
||||||
|
try (InputStream inputStream = Files.newInputStream(finalTempFile)) {
|
||||||
|
ossKey = OSSUtil.uploadCoverToOSS(inputStream, newFileName);
|
||||||
|
}
|
||||||
|
String presignedUrl = OSSUtil.generatePresignedUrl(ossKey);
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of(
|
||||||
|
"code", 200,
|
||||||
|
"message", "上传成功",
|
||||||
|
"data", Map.of(
|
||||||
|
"ossKey", ossKey,
|
||||||
|
"presignedUrl", presignedUrl,
|
||||||
|
"fileName", originalFilename
|
||||||
|
)
|
||||||
|
));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ServerResponse.status(500)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 500, "message", "上传失败: " + e.getMessage()));
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(finalTempFile);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取OSS预签名URL", description = "根据ossKey生成临时访问URL,有效期5分钟")
|
||||||
|
public Mono<ServerResponse> presignUrl(ServerRequest request) {
|
||||||
|
String ossKey = request.queryParam("key").orElse(null);
|
||||||
|
if (ossKey == null || ossKey.isBlank()) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", "参数 key 不能为空"));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
String presignedUrl = OSSUtil.generatePresignedUrl(ossKey);
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of(
|
||||||
|
"code", 200,
|
||||||
|
"data", Map.of("presignedUrl", presignedUrl)
|
||||||
|
));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ServerResponse.status(500)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 500, "message", "生成预签名URL失败: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-5
@@ -146,18 +146,25 @@ public class CourseLabelHandler {
|
|||||||
|
|
||||||
return request.bodyToMono(Map.class)
|
return request.bodyToMono(Map.class)
|
||||||
.flatMap(body -> {
|
.flatMap(body -> {
|
||||||
@SuppressWarnings("unchecked")
|
Object labelIdsObj = body.get("labelIds");
|
||||||
List<Integer> labelIdsInt = (List<Integer>) body.get("labelIds");
|
|
||||||
|
|
||||||
if (labelIdsInt == null || labelIdsInt.isEmpty()) {
|
if (!(labelIdsObj instanceof List)) {
|
||||||
Map<String, Object> error = new HashMap<>();
|
Map<String, Object> error = new HashMap<>();
|
||||||
error.put("success", false);
|
error.put("success", false);
|
||||||
error.put("message", "labelIds不能为空");
|
error.put("message", "labelIds不能为空");
|
||||||
return ServerResponse.badRequest().bodyValue(error);
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Long> labelIds = labelIdsInt.stream()
|
List<?> rawList = (List<?>) labelIdsObj;
|
||||||
.map(Integer::longValue)
|
if (rawList.isEmpty()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "labelIds不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Long> labelIds = rawList.stream()
|
||||||
|
.map(id -> Long.valueOf(String.valueOf(id)))
|
||||||
.collect(java.util.stream.Collectors.toList());
|
.collect(java.util.stream.Collectors.toList());
|
||||||
|
|
||||||
return courseLabelService.addLabelsToType(typeId, labelIds)
|
return courseLabelService.addLabelsToType(typeId, labelIds)
|
||||||
|
|||||||
+71
-5
@@ -2,6 +2,7 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||||
|
import cn.novalon.gym.manage.member.service.IMemberStoredCardService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
@@ -23,9 +24,12 @@ import java.util.Map;
|
|||||||
public class GroupCourseBookingHandler {
|
public class GroupCourseBookingHandler {
|
||||||
|
|
||||||
private final IGroupCourseBookingService bookingService;
|
private final IGroupCourseBookingService bookingService;
|
||||||
|
private final IMemberStoredCardService memberStoredCardService;
|
||||||
|
|
||||||
public GroupCourseBookingHandler(IGroupCourseBookingService bookingService) {
|
public GroupCourseBookingHandler(IGroupCourseBookingService bookingService,
|
||||||
|
IMemberStoredCardService memberStoredCardService) {
|
||||||
this.bookingService = bookingService;
|
this.bookingService = bookingService;
|
||||||
|
this.memberStoredCardService = memberStoredCardService;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,11 +49,21 @@ public class GroupCourseBookingHandler {
|
|||||||
if (body.get("memberCardRecordId") == null) {
|
if (body.get("memberCardRecordId") == null) {
|
||||||
return buildErrorResponse("请提供会员卡记录ID");
|
return buildErrorResponse("请提供会员卡记录ID");
|
||||||
}
|
}
|
||||||
|
if (body.get("payPassword") == null || body.get("payPassword").toString().isEmpty()) {
|
||||||
|
return buildErrorResponse("请输入支付密码");
|
||||||
|
}
|
||||||
|
|
||||||
Long courseId = ((Number) body.get("courseId")).longValue();
|
Long courseId = toLong(body.get("courseId"), "courseId");
|
||||||
Long memberId = ((Number) body.get("memberId")).longValue();
|
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||||
Long memberCardRecordId = ((Number) body.get("memberCardRecordId")).longValue();
|
Long memberCardRecordId = toLong(body.get("memberCardRecordId"), "memberCardRecordId");
|
||||||
|
String payPassword = body.get("payPassword").toString();
|
||||||
|
|
||||||
|
// 验证支付密码
|
||||||
|
return memberStoredCardService.verifyPayPassword(memberId, payPassword)
|
||||||
|
.flatMap(passwordValid -> {
|
||||||
|
if (!passwordValid) {
|
||||||
|
return buildErrorResponse("支付密码错误");
|
||||||
|
}
|
||||||
return bookingService.bookCourse(courseId, memberId, memberCardRecordId)
|
return bookingService.bookCourse(courseId, memberId, memberCardRecordId)
|
||||||
.flatMap(booking -> {
|
.flatMap(booking -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@@ -65,6 +79,7 @@ public class GroupCourseBookingHandler {
|
|||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -76,8 +91,18 @@ public class GroupCourseBookingHandler {
|
|||||||
|
|
||||||
return request.bodyToMono(Map.class)
|
return request.bodyToMono(Map.class)
|
||||||
.flatMap(body -> {
|
.flatMap(body -> {
|
||||||
Long memberId = ((Number) body.get("memberId")).longValue();
|
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||||
|
if (body.get("payPassword") == null || body.get("payPassword").toString().isEmpty()) {
|
||||||
|
return buildErrorResponse("请输入支付密码");
|
||||||
|
}
|
||||||
|
String payPassword = body.get("payPassword").toString();
|
||||||
|
|
||||||
|
// 验证支付密码
|
||||||
|
return memberStoredCardService.verifyPayPassword(memberId, payPassword)
|
||||||
|
.flatMap(passwordValid -> {
|
||||||
|
if (!passwordValid) {
|
||||||
|
return buildErrorResponse("支付密码错误");
|
||||||
|
}
|
||||||
return bookingService.cancelBooking(bookingId, memberId)
|
return bookingService.cancelBooking(bookingId, memberId)
|
||||||
.flatMap(booking -> {
|
.flatMap(booking -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@@ -93,6 +118,7 @@ public class GroupCourseBookingHandler {
|
|||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -129,6 +155,19 @@ public class GroupCourseBookingHandler {
|
|||||||
.body(bookingService.getBookingsByCourseId(courseId), GroupCourseBooking.class);
|
.body(bookingService.getBookingsByCourseId(courseId), GroupCourseBooking.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安全转换为 Long,支持 Number 和 String 类型
|
||||||
|
*/
|
||||||
|
private Long toLong(Object value, String fieldName) {
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).longValue();
|
||||||
|
}
|
||||||
|
if (value instanceof String) {
|
||||||
|
return Long.valueOf((String) value);
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("参数 " + fieldName + " 类型不正确");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建错误响应
|
* 构建错误响应
|
||||||
*/
|
*/
|
||||||
@@ -138,4 +177,31 @@ public class GroupCourseBookingHandler {
|
|||||||
response.put("message", message);
|
response.put("message", message);
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
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()));
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+133
-3
@@ -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.domain.GroupCourseDetail;
|
||||||
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import 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.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Validator;
|
import jakarta.validation.Validator;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
import reactor.core.publisher.Mono;
|
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.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -26,15 +36,21 @@ public class GroupCourseHandler {
|
|||||||
private final Validator validator;
|
private final Validator validator;
|
||||||
private final RedisUtil redisUtil;
|
private final RedisUtil redisUtil;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public GroupCourseHandler(IGroupCourseService groupCourseService,
|
public GroupCourseHandler(IGroupCourseService groupCourseService,
|
||||||
Validator validator,
|
Validator validator,
|
||||||
RedisUtil redisUtil,
|
RedisUtil redisUtil,
|
||||||
ObjectMapper objectMapper){
|
ObjectMapper objectMapper,
|
||||||
|
ISysUserService sysUserService,
|
||||||
|
AuthUtil authUtil){
|
||||||
this.groupCourseService = groupCourseService;
|
this.groupCourseService = groupCourseService;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
this.redisUtil = redisUtil;
|
this.redisUtil = redisUtil;
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表")
|
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表")
|
||||||
@@ -114,10 +130,27 @@ public class GroupCourseHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新团课", description = "更新指定团课信息")
|
@Operation(summary = "更新团课", description = "更新指定团课信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateGroupCourse(ServerRequest request) {
|
public Mono<ServerResponse> updateGroupCourse(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return request.bodyToMono(GroupCourse.class)
|
||||||
.flatMap(groupCourse -> {
|
.flatMap(groupCourse -> {
|
||||||
return groupCourseService.update(id, groupCourse)
|
return groupCourseService.update(id, groupCourse)
|
||||||
@@ -135,6 +168,7 @@ public class GroupCourseHandler {
|
|||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "取消团课", description = "取消指定团课(需提前24小时)")
|
@Operation(summary = "取消团课", description = "取消指定团课(需提前24小时)")
|
||||||
@@ -197,10 +231,27 @@ public class GroupCourseHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除团课", description = "删除指定团课(软删除)")
|
@Operation(summary = "删除团课", description = "删除指定团课(软删除),需验证管理员密码")
|
||||||
public Mono<ServerResponse> deleteGroupCourse(ServerRequest request) {
|
public Mono<ServerResponse> deleteGroupCourse(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return groupCourseService.delete(id)
|
||||||
.then(Mono.defer(() -> {
|
.then(Mono.defer(() -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@@ -214,6 +265,45 @@ public class GroupCourseHandler {
|
|||||||
response.put("message", error.getMessage());
|
response.put("message", error.getMessage());
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "多条件查询团课", description = "支持团课名称模糊查询、类型筛选、日期范围、时间段、价格排序、剩余名额排序等多条件组合查询")
|
@Operation(summary = "多条件查询团课", description = "支持团课名称模糊查询、类型筛选、日期范围、时间段、价格排序、剩余名额排序等多条件组合查询")
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-7
@@ -2,8 +2,11 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseRecommend;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseRecommend;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
@@ -17,9 +20,15 @@ import java.util.Map;
|
|||||||
public class GroupCourseRecommendHandler {
|
public class GroupCourseRecommendHandler {
|
||||||
|
|
||||||
private final IGroupCourseRecommendService recommendService;
|
private final IGroupCourseRecommendService recommendService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public GroupCourseRecommendHandler(IGroupCourseRecommendService recommendService) {
|
public GroupCourseRecommendHandler(IGroupCourseRecommendService recommendService,
|
||||||
|
ISysUserService sysUserService,
|
||||||
|
AuthUtil authUtil) {
|
||||||
this.recommendService = recommendService;
|
this.recommendService = recommendService;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有团课推荐", description = "获取系统中所有团课推荐列表,支持按优先级排序")
|
@Operation(summary = "获取所有团课推荐", description = "获取系统中所有团课推荐列表,支持按优先级排序")
|
||||||
@@ -80,13 +89,29 @@ public class GroupCourseRecommendHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新团课推荐", description = "更新指定团课推荐信息")
|
@Operation(summary = "更新团课推荐", description = "更新指定团课推荐信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateRecommendation(ServerRequest request) {
|
public Mono<ServerResponse> updateRecommendation(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return request.bodyToMono(GroupCourseRecommend.class)
|
||||||
.flatMap(recommend -> {
|
.flatMap(recommend -> recommendService.update(id, recommend)
|
||||||
return recommendService.update(id, recommend)
|
|
||||||
.flatMap(r -> {
|
.flatMap(r -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
response.put("success", true);
|
response.put("success", true);
|
||||||
@@ -99,14 +124,31 @@ public class GroupCourseRecommendHandler {
|
|||||||
response.put("success", false);
|
response.put("success", false);
|
||||||
response.put("message", error.getMessage());
|
response.put("message", error.getMessage());
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
}));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除团课推荐", description = "删除指定团课推荐(软删除)")
|
@Operation(summary = "删除团课推荐", description = "删除指定团课推荐(软删除),需验证管理员密码")
|
||||||
public Mono<ServerResponse> deleteRecommendation(ServerRequest request) {
|
public Mono<ServerResponse> deleteRecommendation(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return recommendService.delete(id)
|
||||||
.then(Mono.defer(() -> {
|
.then(Mono.defer(() -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@@ -120,6 +162,7 @@ public class GroupCourseRecommendHandler {
|
|||||||
response.put("message", error.getMessage());
|
response.put("message", error.getMessage());
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "启用团课推荐", description = "启用指定团课推荐")
|
@Operation(summary = "启用团课推荐", description = "启用指定团课推荐")
|
||||||
@@ -142,10 +185,27 @@ public class GroupCourseRecommendHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "禁用团课推荐", description = "禁用指定团课推荐")
|
@Operation(summary = "禁用团课推荐", description = "禁用指定团课推荐,需验证管理员密码")
|
||||||
public Mono<ServerResponse> disableRecommendation(ServerRequest request) {
|
public Mono<ServerResponse> disableRecommendation(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return recommendService.disable(id)
|
||||||
.flatMap(r -> {
|
.flatMap(r -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@@ -160,5 +220,6 @@ public class GroupCourseRecommendHandler {
|
|||||||
response.put("message", error.getMessage());
|
response.put("message", error.getMessage());
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+48
-3
@@ -2,8 +2,11 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
@@ -17,9 +20,15 @@ import java.util.Map;
|
|||||||
public class GroupCourseTypeHandler {
|
public class GroupCourseTypeHandler {
|
||||||
|
|
||||||
private final IGroupCourseTypeService groupCourseTypeService;
|
private final IGroupCourseTypeService groupCourseTypeService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public GroupCourseTypeHandler(IGroupCourseTypeService groupCourseTypeService) {
|
public GroupCourseTypeHandler(IGroupCourseTypeService groupCourseTypeService,
|
||||||
|
ISysUserService sysUserService,
|
||||||
|
AuthUtil authUtil) {
|
||||||
this.groupCourseTypeService = groupCourseTypeService;
|
this.groupCourseTypeService = groupCourseTypeService;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有团课类型", description = "获取系统中所有团课类型列表")
|
@Operation(summary = "获取所有团课类型", description = "获取系统中所有团课类型列表")
|
||||||
@@ -92,10 +101,27 @@ public class GroupCourseTypeHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新团课类型", description = "更新指定团课类型信息")
|
@Operation(summary = "更新团课类型", description = "更新指定团课类型信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateGroupCourseType(ServerRequest request) {
|
public Mono<ServerResponse> updateGroupCourseType(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return request.bodyToMono(GroupCourseType.class)
|
||||||
.flatMap(groupCourseType -> {
|
.flatMap(groupCourseType -> {
|
||||||
groupCourseType.setId(id);
|
groupCourseType.setId(id);
|
||||||
@@ -114,12 +140,30 @@ public class GroupCourseTypeHandler {
|
|||||||
return ServerResponse.badRequest().bodyValue(response);
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除团课类型", description = "删除指定团课类型(软删除)")
|
@Operation(summary = "删除团课类型", description = "删除指定团课类型(软删除),需验证管理员密码,且该类型不能被任何团课引用")
|
||||||
public Mono<ServerResponse> deleteGroupCourseType(ServerRequest request) {
|
public Mono<ServerResponse> deleteGroupCourseType(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
|
||||||
|
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)
|
return groupCourseTypeService.delete(id)
|
||||||
.then(Mono.defer(() -> {
|
.then(Mono.defer(() -> {
|
||||||
Map<String, Object> response = new HashMap<>();
|
Map<String, Object> response = new HashMap<>();
|
||||||
@@ -133,5 +177,6 @@ public class GroupCourseTypeHandler {
|
|||||||
response.put("message", error.getMessage());
|
response.put("message", error.getMessage());
|
||||||
return ServerResponse.badRequest().bodyValue(response);
|
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);
|
||||||
|
}
|
||||||
+7
@@ -89,4 +89,11 @@ public interface IGroupCourseBookingRepository {
|
|||||||
* @return 更新记录数
|
* @return 更新记录数
|
||||||
*/
|
*/
|
||||||
Mono<Integer> updateToAbsent(Long bookingId);
|
Mono<Integer> updateToAbsent(Long bookingId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员取消的预约次数
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @return 取消次数
|
||||||
|
*/
|
||||||
|
Mono<Long> countCancelledByMemberId(Long memberId);
|
||||||
}
|
}
|
||||||
+2
@@ -27,6 +27,8 @@ public interface IGroupCourseRepository {
|
|||||||
|
|
||||||
Mono<Void> deleteById(Long id);
|
Mono<Void> deleteById(Long id);
|
||||||
|
|
||||||
|
Mono<GroupCourse> restoreById(Long id);
|
||||||
|
|
||||||
Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta);
|
Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta);
|
||||||
|
|
||||||
Flux<GroupCourse> findByCourseType(Long courseType);
|
Flux<GroupCourse> findByCourseType(Long courseType);
|
||||||
|
|||||||
+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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
@@ -112,4 +112,9 @@ public class GroupCourseBookingRepository implements IGroupCourseBookingReposito
|
|||||||
java.time.LocalDateTime now = java.time.LocalDateTime.now();
|
java.time.LocalDateTime now = java.time.LocalDateTime.now();
|
||||||
return groupCourseBookingDao.updateToAbsent(bookingId, now);
|
return groupCourseBookingDao.updateToAbsent(bookingId, now);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Long> countCancelledByMemberId(Long memberId) {
|
||||||
|
return groupCourseBookingDao.countCancelledByMemberId(memberId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+13
@@ -138,6 +138,7 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
|||||||
entity.setUpdatedAt(LocalDateTime.now());
|
entity.setUpdatedAt(LocalDateTime.now());
|
||||||
entity.setStatus(0L);
|
entity.setStatus(0L);
|
||||||
entity.setCurrentMembers(0);
|
entity.setCurrentMembers(0);
|
||||||
|
entity.setIsRecurring(groupCourse.getIsRecurring() != null ? groupCourse.getIsRecurring() : false);
|
||||||
|
|
||||||
return groupCourseDao.save(entity)
|
return groupCourseDao.save(entity)
|
||||||
.map(groupCourseConverter::toDomain);
|
.map(groupCourseConverter::toDomain);
|
||||||
@@ -147,6 +148,7 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
|||||||
public Mono<GroupCourse> update(GroupCourse groupCourse) {
|
public Mono<GroupCourse> update(GroupCourse groupCourse) {
|
||||||
GroupCourseEntity entity = groupCourseConverter.toEntity(groupCourse);
|
GroupCourseEntity entity = groupCourseConverter.toEntity(groupCourse);
|
||||||
entity.setUpdatedAt(LocalDateTime.now());
|
entity.setUpdatedAt(LocalDateTime.now());
|
||||||
|
entity.setIsRecurring(groupCourse.getIsRecurring() != null ? groupCourse.getIsRecurring() : false);
|
||||||
|
|
||||||
return r2dbcEntityTemplate.update(entity)
|
return r2dbcEntityTemplate.update(entity)
|
||||||
.then(findByIdAndDeletedAtIsNull(groupCourse.getId()));
|
.then(findByIdAndDeletedAtIsNull(groupCourse.getId()));
|
||||||
@@ -169,6 +171,17 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
|||||||
.then();
|
.then();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<GroupCourse> restoreById(Long id) {
|
||||||
|
return groupCourseDao.restoreCourse(id, LocalDateTime.now())
|
||||||
|
.flatMap(updated -> {
|
||||||
|
if (updated > 0) {
|
||||||
|
return findByIdAndDeletedAtIsNull(id);
|
||||||
|
}
|
||||||
|
return Mono.error(new RuntimeException("团课恢复失败,可能该课程未被删除"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta) {
|
public Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta) {
|
||||||
return groupCourseDao.updateCurrentMembers(id, delta, LocalDateTime.now())
|
return groupCourseDao.updateCurrentMembers(id, delta, LocalDateTime.now())
|
||||||
|
|||||||
+14
-15
@@ -105,21 +105,20 @@ public class GroupCourseTypeRepository implements IGroupCourseTypeRepository {
|
|||||||
return groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId())
|
return groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId())
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("团课类型不存在")))
|
.switchIfEmpty(Mono.error(new RuntimeException("团课类型不存在")))
|
||||||
.flatMap(existing -> {
|
.flatMap(existing -> {
|
||||||
existing.markNotNew();
|
String typeName = groupCourseType.getTypeName() != null
|
||||||
if (groupCourseType.getTypeName() != null) {
|
? groupCourseType.getTypeName() : existing.getTypeName();
|
||||||
existing.setTypeName(groupCourseType.getTypeName());
|
Integer baseDifficulty = groupCourseType.getBaseDifficulty() != null
|
||||||
}
|
? groupCourseType.getBaseDifficulty() : existing.getBaseDifficulty();
|
||||||
if (groupCourseType.getBaseDifficulty() != null) {
|
String description = groupCourseType.getDescription() != null
|
||||||
existing.setBaseDifficulty(groupCourseType.getBaseDifficulty());
|
? groupCourseType.getDescription() : existing.getDescription();
|
||||||
}
|
String category = groupCourseType.getCategory() != null
|
||||||
if (groupCourseType.getDescription() != null) {
|
? groupCourseType.getCategory() : existing.getCategory();
|
||||||
existing.setDescription(groupCourseType.getDescription());
|
LocalDateTime now = LocalDateTime.now();
|
||||||
}
|
|
||||||
if (groupCourseType.getCategory() != null) {
|
return groupCourseTypeDao.updateFields(
|
||||||
existing.setCategory(groupCourseType.getCategory());
|
groupCourseType.getId(), typeName, baseDifficulty,
|
||||||
}
|
description, category, now)
|
||||||
existing.setUpdatedAt(LocalDateTime.now());
|
.then(groupCourseTypeDao.findByIdIsAndDeletedAtIsNull(groupCourseType.getId()));
|
||||||
return groupCourseTypeDao.save(existing);
|
|
||||||
})
|
})
|
||||||
.map(converter::toGroupCourseType);
|
.map(converter::toGroupCourseType);
|
||||||
}
|
}
|
||||||
|
|||||||
+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 处理的记录数
|
* @return 处理的记录数
|
||||||
*/
|
*/
|
||||||
Mono<Integer> processAbsentMembers();
|
Mono<Integer> processAbsentMembers();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫码签到
|
||||||
|
* 用户扫描团课二维码签到,将预约状态更新为已出席(2)
|
||||||
|
*
|
||||||
|
* @param courseId 团课ID
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @return 更新后的预约记录
|
||||||
|
*/
|
||||||
|
Mono<GroupCourseBooking> qrSignIn(Long courseId, Long memberId);
|
||||||
}
|
}
|
||||||
+2
@@ -27,5 +27,7 @@ public interface IGroupCourseService {
|
|||||||
|
|
||||||
Mono<Void> delete(Long id);
|
Mono<Void> delete(Long id);
|
||||||
|
|
||||||
|
Mono<GroupCourse> restore(Long id);
|
||||||
|
|
||||||
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
||||||
}
|
}
|
||||||
|
|||||||
+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()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+102
-4
@@ -7,12 +7,15 @@ import cn.novalon.gym.manage.groupcourse.handler.BookingSagaHandler;
|
|||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.util.OSSUtil;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.r2dbc.core.DatabaseClient;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -45,6 +48,7 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
|||||||
private final GroupCourseRedisService redisService;
|
private final GroupCourseRedisService redisService;
|
||||||
private final BookingReminderEventPublisher bookingReminderEventPublisher;
|
private final BookingReminderEventPublisher bookingReminderEventPublisher;
|
||||||
private final BookingSagaHandler bookingSagaHandler;
|
private final BookingSagaHandler bookingSagaHandler;
|
||||||
|
private final DatabaseClient databaseClient;
|
||||||
|
|
||||||
// 预约提前时间限制(分钟)
|
// 预约提前时间限制(分钟)
|
||||||
private static final long BOOKING_MIN_ADVANCE_MINUTES = 30;
|
private static final long BOOKING_MIN_ADVANCE_MINUTES = 30;
|
||||||
@@ -55,12 +59,14 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
|||||||
IGroupCourseRepository courseRepository,
|
IGroupCourseRepository courseRepository,
|
||||||
GroupCourseRedisService redisService,
|
GroupCourseRedisService redisService,
|
||||||
BookingReminderEventPublisher bookingReminderEventPublisher,
|
BookingReminderEventPublisher bookingReminderEventPublisher,
|
||||||
BookingSagaHandler bookingSagaHandler) {
|
BookingSagaHandler bookingSagaHandler,
|
||||||
|
DatabaseClient databaseClient) {
|
||||||
this.bookingRepository = bookingRepository;
|
this.bookingRepository = bookingRepository;
|
||||||
this.courseRepository = courseRepository;
|
this.courseRepository = courseRepository;
|
||||||
this.redisService = redisService;
|
this.redisService = redisService;
|
||||||
this.bookingReminderEventPublisher = bookingReminderEventPublisher;
|
this.bookingReminderEventPublisher = bookingReminderEventPublisher;
|
||||||
this.bookingSagaHandler = bookingSagaHandler;
|
this.bookingSagaHandler = bookingSagaHandler;
|
||||||
|
this.databaseClient = databaseClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -157,7 +163,8 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
|||||||
booking.setLocation(course.getLocation());
|
booking.setLocation(course.getLocation());
|
||||||
|
|
||||||
// 10. 使用Saga事务执行预约(包含权益扣减)
|
// 10. 使用Saga事务执行预约(包含权益扣减)
|
||||||
return bookingSagaHandler.executeBooking(booking, memberCardRecordId)
|
BigDecimal courseAmount = course.getStoredValueAmount() != null ? course.getStoredValueAmount() : BigDecimal.ZERO;
|
||||||
|
return bookingSagaHandler.executeBooking(booking, memberCardRecordId, courseAmount)
|
||||||
.flatMap(savedBooking -> {
|
.flatMap(savedBooking -> {
|
||||||
// 11. 释放锁
|
// 11. 释放锁
|
||||||
return redisService.releaseLock(courseId, requestId)
|
return redisService.releaseLock(courseId, requestId)
|
||||||
@@ -290,8 +297,15 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
|||||||
"需在课程开始前" + CANCEL_MIN_ADVANCE_HOURS + "小时取消");
|
"需在课程开始前" + CANCEL_MIN_ADVANCE_HOURS + "小时取消");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 使用Saga事务执行取消预约(包含权益恢复)
|
// 5. 查询课程金额和已取消次数,使用Saga事务执行取消预约
|
||||||
return bookingSagaHandler.executeCancelBooking(bookingId, booking.getCourseId(), booking.getMemberCardRecordId(), memberId)
|
return courseRepository.findByIdAndDeletedAtIsNull(booking.getCourseId())
|
||||||
|
.flatMap(course -> {
|
||||||
|
BigDecimal courseAmount = course.getStoredValueAmount() != null ? course.getStoredValueAmount() : BigDecimal.valueOf(50);
|
||||||
|
return bookingRepository.countCancelledByMemberId(memberId)
|
||||||
|
.flatMap(cancelCount -> {
|
||||||
|
return bookingSagaHandler.executeCancelBooking(bookingId, booking.getCourseId(), booking.getMemberCardRecordId(), memberId, courseAmount, cancelCount);
|
||||||
|
});
|
||||||
|
})
|
||||||
.flatMap(updatedBooking -> {
|
.flatMap(updatedBooking -> {
|
||||||
// 6. 释放锁
|
// 6. 释放锁
|
||||||
return redisService.releaseLock(bookingId, requestId)
|
return redisService.releaseLock(bookingId, requestId)
|
||||||
@@ -322,6 +336,18 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
|||||||
public Flux<GroupCourseBooking> getBookingsByMemberId(Long memberId) {
|
public Flux<GroupCourseBooking> getBookingsByMemberId(Long memberId) {
|
||||||
logger.debug("查询会员预约记录:memberId={}", memberId);
|
logger.debug("查询会员预约记录:memberId={}", memberId);
|
||||||
return bookingRepository.findByMemberId(memberId)
|
return bookingRepository.findByMemberId(memberId)
|
||||||
|
.flatMap(booking -> {
|
||||||
|
// 从关联的 GroupCourse 获取封面图并转为预签名URL
|
||||||
|
if (booking.getCourseId() != null) {
|
||||||
|
return courseRepository.findByIdAndDeletedAtIsNull(booking.getCourseId())
|
||||||
|
.map(course -> {
|
||||||
|
booking.setCoverImage(OSSUtil.toCoverPresignedUrl(course.getCoverImage()));
|
||||||
|
return booking;
|
||||||
|
})
|
||||||
|
.defaultIfEmpty(booking);
|
||||||
|
}
|
||||||
|
return Mono.just(booking);
|
||||||
|
})
|
||||||
.doOnComplete(() -> logger.debug("查询完成:memberId={}", memberId));
|
.doOnComplete(() -> logger.debug("查询完成:memberId={}", memberId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,6 +364,78 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
|||||||
.doOnComplete(() -> logger.debug("查询完成:courseId={}", courseId));
|
.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
|
@Override
|
||||||
public Mono<Integer> processAbsentMembers() {
|
public Mono<Integer> processAbsentMembers() {
|
||||||
logger.info("开始处理已开始课程但未到场会员的预约记录");
|
logger.info("开始处理已开始课程但未到场会员的预约记录");
|
||||||
|
|||||||
+3
@@ -5,6 +5,7 @@ import cn.novalon.gym.manage.groupcourse.domain.GroupCourseRecommend;
|
|||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRecommendRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRecommendRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.util.OSSUtil;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -134,6 +135,8 @@ public class GroupCourseRecommendService implements IGroupCourseRecommendService
|
|||||||
|
|
||||||
return groupCourseRepository.findByIdAndDeletedAtIsNull(recommend.getCourseId())
|
return groupCourseRepository.findByIdAndDeletedAtIsNull(recommend.getCourseId())
|
||||||
.map(course -> {
|
.map(course -> {
|
||||||
|
// 将 OSS Key 转换为预签名URL,前端可直接加载
|
||||||
|
course.setCoverImage(OSSUtil.toCoverPresignedUrl(course.getCoverImage()));
|
||||||
recommend.setGroupCourse(course);
|
recommend.setGroupCourse(course);
|
||||||
return recommend;
|
return recommend;
|
||||||
})
|
})
|
||||||
|
|||||||
+53
-12
@@ -19,6 +19,7 @@ import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
|||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
||||||
import cn.novalon.gym.manage.groupcourse.util.QRCodeUtil;
|
import cn.novalon.gym.manage.groupcourse.util.QRCodeUtil;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.util.OSSUtil;
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
@@ -32,6 +33,7 @@ import org.springframework.r2dbc.core.DatabaseClient;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
import reactor.core.scheduler.Schedulers;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -153,7 +155,7 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
detail.setCurrentMembers(course.getCurrentMembers());
|
detail.setCurrentMembers(course.getCurrentMembers());
|
||||||
detail.setStatus(course.getStatus());
|
detail.setStatus(course.getStatus());
|
||||||
detail.setLocation(course.getLocation());
|
detail.setLocation(course.getLocation());
|
||||||
detail.setCoverImage(course.getCoverImage());
|
detail.setCoverImage(OSSUtil.toCoverPresignedUrl(course.getCoverImage()));
|
||||||
detail.setDescription(course.getDescription());
|
detail.setDescription(course.getDescription());
|
||||||
detail.setStoredValueAmount(course.getStoredValueAmount());
|
detail.setStoredValueAmount(course.getStoredValueAmount());
|
||||||
detail.setQrCodePath(course.getQrCodePath());
|
detail.setQrCodePath(course.getQrCodePath());
|
||||||
@@ -178,7 +180,7 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
try {
|
try {
|
||||||
GroupCourse groupCourse = objectMapper.readValue(cachedJson, GroupCourse.class);
|
GroupCourse groupCourse = objectMapper.readValue(cachedJson, GroupCourse.class);
|
||||||
logger.info("缓存命中 - findById: id={}", id);
|
logger.info("缓存命中 - findById: id={}", id);
|
||||||
return Mono.just(groupCourse);
|
return Mono.just(fillCoverPresignedUrl(groupCourse));
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
logger.warn("缓存解析失败,删除缓存 - id: {}, error: {}", id, e.getMessage());
|
logger.warn("缓存解析失败,删除缓存 - id: {}, error: {}", id, e.getMessage());
|
||||||
return redisUtil.delete(cacheKey).then(Mono.empty());
|
return redisUtil.delete(cacheKey).then(Mono.empty());
|
||||||
@@ -188,6 +190,7 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
})
|
})
|
||||||
.switchIfEmpty(
|
.switchIfEmpty(
|
||||||
groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
||||||
|
.map(this::fillCoverPresignedUrl)
|
||||||
.flatMap(groupCourse -> {
|
.flatMap(groupCourse -> {
|
||||||
try {
|
try {
|
||||||
String jsonData = objectMapper.writeValueAsString(groupCourse);
|
String jsonData = objectMapper.writeValueAsString(groupCourse);
|
||||||
@@ -205,16 +208,19 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Flux<GroupCourse> findAll() {
|
public Flux<GroupCourse> findAll() {
|
||||||
return groupCourseRepository.findAll();
|
return groupCourseRepository.findAll()
|
||||||
|
.map(this::fillCoverPresignedUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Flux<GroupCourse> findAll(boolean includeDeleted) {
|
public Flux<GroupCourse> findAll(boolean includeDeleted) {
|
||||||
|
Flux<GroupCourse> flux;
|
||||||
if(includeDeleted){
|
if(includeDeleted){
|
||||||
return groupCourseRepository.findAll();
|
flux = groupCourseRepository.findAll();
|
||||||
}else{
|
}else{
|
||||||
return groupCourseRepository.findByDeletedAtIsNull();
|
flux = groupCourseRepository.findByDeletedAtIsNull();
|
||||||
}
|
}
|
||||||
|
return flux.map(this::fillCoverPresignedUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -234,6 +240,7 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
PageResponse<GroupCourse> pageResponse = objectMapper.readValue(cachedJson,
|
PageResponse<GroupCourse> pageResponse = objectMapper.readValue(cachedJson,
|
||||||
objectMapper.getTypeFactory().constructParametricType(PageResponse.class, GroupCourse.class));
|
objectMapper.getTypeFactory().constructParametricType(PageResponse.class, GroupCourse.class));
|
||||||
logger.info("缓存命中 - findByPage: key={}", cacheKey);
|
logger.info("缓存命中 - findByPage: key={}", cacheKey);
|
||||||
|
fillCoverPresignedUrl(pageResponse);
|
||||||
return Mono.just(pageResponse);
|
return Mono.just(pageResponse);
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
logger.warn("缓存解析失败,删除缓存 - key: {}, error: {}", cacheKey, e.getMessage());
|
logger.warn("缓存解析失败,删除缓存 - key: {}, error: {}", cacheKey, e.getMessage());
|
||||||
@@ -254,6 +261,7 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
|
|
||||||
return resultMono.flatMap(pageResponse -> {
|
return resultMono.flatMap(pageResponse -> {
|
||||||
try {
|
try {
|
||||||
|
fillCoverPresignedUrl(pageResponse);
|
||||||
String jsonData = objectMapper.writeValueAsString(pageResponse);
|
String jsonData = objectMapper.writeValueAsString(pageResponse);
|
||||||
return redisUtil.setWithExpire(cacheKey, jsonData, CACHE_EXPIRE_SECONDS)
|
return redisUtil.setWithExpire(cacheKey, jsonData, CACHE_EXPIRE_SECONDS)
|
||||||
.thenReturn(pageResponse)
|
.thenReturn(pageResponse)
|
||||||
@@ -347,6 +355,9 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
if (groupCourse.getQrCodePath() != null) {
|
if (groupCourse.getQrCodePath() != null) {
|
||||||
existing.setQrCodePath(groupCourse.getQrCodePath());
|
existing.setQrCodePath(groupCourse.getQrCodePath());
|
||||||
}
|
}
|
||||||
|
if (groupCourse.getIsRecurring() != null) {
|
||||||
|
existing.setIsRecurring(groupCourse.getIsRecurring());
|
||||||
|
}
|
||||||
return groupCourseRepository.update(existing);
|
return groupCourseRepository.update(existing);
|
||||||
})
|
})
|
||||||
.doOnSuccess(course -> logger.info("团课更新成功 - id={}", id))
|
.doOnSuccess(course -> logger.info("团课更新成功 - id={}", id))
|
||||||
@@ -536,14 +547,14 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Void> delete(Long id) {
|
public Mono<Void> delete(Long id) {
|
||||||
// 先查询课程状态,只有已取消的课程才能删除
|
// 已取消或已结束的课程才能删除
|
||||||
return groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
return groupCourseRepository.findByIdAndDeletedAtIsNull(id)
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||||
.flatMap(course -> {
|
.flatMap(course -> {
|
||||||
// 检查课程状态是否为已取消(状态码1)
|
Long status = course.getStatus();
|
||||||
if (course.getStatus() == null || !course.getStatus().equals(CourseStatus.CANCELLED.getValue())) {
|
if (status == null || (!status.equals(CourseStatus.CANCELLED.getValue()) && !status.equals(CourseStatus.ENDED.getValue()))) {
|
||||||
return Mono.error(new RuntimeException("只有已取消的课程才能删除,当前状态: " +
|
return Mono.error(new RuntimeException("只有已取消或已结束的课程才能删除,当前状态: " +
|
||||||
(course.getStatus() != null ? course.getStatus() : "未知")));
|
(status != null ? status : "未知")));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除课程
|
// 删除课程
|
||||||
@@ -554,6 +565,14 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<GroupCourse> restore(Long id) {
|
||||||
|
return groupCourseRepository.restoreById(id)
|
||||||
|
.doOnSuccess(course -> logger.info("团课恢复成功 - id={}", id))
|
||||||
|
.flatMap(course -> clearCache().thenReturn(course))
|
||||||
|
.doOnError(error -> logger.error("团课恢复失败 - id={}, error: {}", id, error.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query) {
|
public Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query) {
|
||||||
logger.info("多条件查询团课 - courseName={}, courseType={}, startDate={}, endDate={}, timePeriod={}, priceSort={}, remainingMost={}",
|
logger.info("多条件查询团课 - courseName={}, courseType={}, startDate={}, endDate={}, timePeriod={}, priceSort={}, remainingMost={}",
|
||||||
@@ -561,8 +580,11 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
query.getTimePeriod(), query.getPriceSort(), query.getRemainingMost());
|
query.getTimePeriod(), query.getPriceSort(), query.getRemainingMost());
|
||||||
|
|
||||||
return groupCourseRepository.searchGroupCourses(query)
|
return groupCourseRepository.searchGroupCourses(query)
|
||||||
.doOnSuccess(result -> logger.info("多条件查询结果 - total={}, page={}, size={}",
|
.doOnSuccess(result -> {
|
||||||
result.getTotalElements(), result.getCurrentPage(), result.getPageSize()))
|
fillCoverPresignedUrl(result);
|
||||||
|
logger.info("多条件查询结果 - total={}, page={}, size={}",
|
||||||
|
result.getTotalElements(), result.getCurrentPage(), result.getPageSize());
|
||||||
|
})
|
||||||
.doOnError(error -> logger.error("多条件查询失败 - error: {}", error.getMessage()));
|
.doOnError(error -> logger.error("多条件查询失败 - error: {}", error.getMessage()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -571,4 +593,23 @@ public class GroupCourseService implements IGroupCourseService {
|
|||||||
.then(redisUtil.deleteByPattern(CACHE_KEY_ID_PREFIX + "*"))
|
.then(redisUtil.deleteByPattern(CACHE_KEY_ID_PREFIX + "*"))
|
||||||
.then(redisUtil.deleteByPattern(CACHE_KEY_DETAIL_PREFIX + "*")).then();
|
.then(redisUtil.deleteByPattern(CACHE_KEY_DETAIL_PREFIX + "*")).then();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将单个 GroupCourse 的 coverImage 从 OSS Key 转换为预签名URL
|
||||||
|
*/
|
||||||
|
private GroupCourse fillCoverPresignedUrl(GroupCourse course) {
|
||||||
|
if (course != null) {
|
||||||
|
course.setCoverImage(OSSUtil.toCoverPresignedUrl(course.getCoverImage()));
|
||||||
|
}
|
||||||
|
return course;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将分页结果中所有 GroupCourse 的 coverImage 从 OSS Key 转换为预签名URL
|
||||||
|
*/
|
||||||
|
private void fillCoverPresignedUrl(PageResponse<GroupCourse> pageResponse) {
|
||||||
|
if (pageResponse != null && pageResponse.getContent() != null) {
|
||||||
|
pageResponse.getContent().forEach(this::fillCoverPresignedUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-5
@@ -1,6 +1,7 @@
|
|||||||
package cn.novalon.gym.manage.groupcourse.service.impl;
|
package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
||||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -9,18 +10,18 @@ import org.springframework.stereotype.Service;
|
|||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class GroupCourseTypeService implements IGroupCourseTypeService {
|
public class GroupCourseTypeService implements IGroupCourseTypeService {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(GroupCourseTypeService.class);
|
private static final Logger logger = LoggerFactory.getLogger(GroupCourseTypeService.class);
|
||||||
|
|
||||||
private final IGroupCourseTypeRepository groupCourseTypeRepository;
|
private final IGroupCourseTypeRepository groupCourseTypeRepository;
|
||||||
|
private final IGroupCourseRepository groupCourseRepository;
|
||||||
|
|
||||||
public GroupCourseTypeService(IGroupCourseTypeRepository groupCourseTypeRepository) {
|
public GroupCourseTypeService(IGroupCourseTypeRepository groupCourseTypeRepository,
|
||||||
|
IGroupCourseRepository groupCourseRepository) {
|
||||||
this.groupCourseTypeRepository = groupCourseTypeRepository;
|
this.groupCourseTypeRepository = groupCourseTypeRepository;
|
||||||
|
this.groupCourseRepository = groupCourseRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -71,7 +72,14 @@ public class GroupCourseTypeService implements IGroupCourseTypeService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Void> delete(Long id) {
|
public Mono<Void> delete(Long id) {
|
||||||
return groupCourseTypeRepository.deleteById(id)
|
return groupCourseRepository.findByCourseType(id)
|
||||||
|
.hasElements()
|
||||||
|
.flatMap(hasCourses -> {
|
||||||
|
if (hasCourses) {
|
||||||
|
return Mono.<Void>error(new RuntimeException("该类型下存在关联团课,无法删除"));
|
||||||
|
}
|
||||||
|
return groupCourseTypeRepository.deleteById(id);
|
||||||
|
})
|
||||||
.doOnSuccess(v -> logger.info("团课类型删除成功 - id={}", id))
|
.doOnSuccess(v -> logger.info("团课类型删除成功 - id={}", id))
|
||||||
.doOnError(error -> logger.error("团课类型删除失败 - id={}, error: {}", id, error.getMessage()));
|
.doOnError(error -> logger.error("团课类型删除失败 - id={}, error: {}", id, error.getMessage()));
|
||||||
}
|
}
|
||||||
|
|||||||
+113
-29
@@ -1,14 +1,19 @@
|
|||||||
package cn.novalon.gym.manage.groupcourse.util;
|
package cn.novalon.gym.manage.groupcourse.util;
|
||||||
|
|
||||||
|
import com.aliyun.oss.HttpMethod;
|
||||||
import com.aliyun.oss.OSS;
|
import com.aliyun.oss.OSS;
|
||||||
import com.aliyun.oss.OSSClientBuilder;
|
import com.aliyun.oss.OSSClientBuilder;
|
||||||
|
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
|
||||||
import com.aliyun.oss.model.PutObjectRequest;
|
import com.aliyun.oss.model.PutObjectRequest;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.URL;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 阿里云OSS工具类
|
* 阿里云OSS工具类
|
||||||
@@ -18,9 +23,9 @@ public class OSSUtil {
|
|||||||
private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
|
private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
|
||||||
|
|
||||||
// OSS配置信息
|
// OSS配置信息
|
||||||
private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
|
private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
|
||||||
private static final String ACCESS_KEY_ID = "LTAI5t9TFh9Vayeahz45kZjg";
|
private static final String ACCESS_KEY_ID = "LTAI5t9wHCiH68Xjxg64Xx4Y";
|
||||||
private static final String ACCESS_KEY_SECRET = "zD6NlCeH5UhjBs4vnQVqn8Ksi3CaZz";
|
private static final String ACCESS_KEY_SECRET = "isAfz1IFGAnV13LOIrVg19aPhY8aRq";
|
||||||
private static final String BUCKET_NAME = "ycc-filesaver";
|
private static final String BUCKET_NAME = "ycc-filesaver";
|
||||||
|
|
||||||
// OSS访问地址前缀
|
// OSS访问地址前缀
|
||||||
@@ -28,36 +33,33 @@ public class OSSUtil {
|
|||||||
|
|
||||||
// 文件存储目录
|
// 文件存储目录
|
||||||
private static final String QRCODE_DIR = "qrcode/";
|
private static final String QRCODE_DIR = "qrcode/";
|
||||||
|
private static final String COVER_DIR = "cover/";
|
||||||
|
|
||||||
|
// 预签名URL有效期(秒)
|
||||||
|
private static final long PRESIGN_EXPIRE_SECONDS = 300;
|
||||||
|
// 封面图预签名URL有效期(秒)- 1小时,确保前端列表页足够展示
|
||||||
|
private static final long COVER_PRESIGN_EXPIRE_SECONDS = 3600;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 上传文件到阿里云OSS
|
* 上传文件到阿里云OSS(文件默认继承Bucket权限,不设置ACL)
|
||||||
*
|
*
|
||||||
* @param localFilePath 本地文件路径
|
* @param localFilePath 本地文件路径
|
||||||
* @param fileName 文件名(不含路径)
|
* @param fileName 文件名(不含路径)
|
||||||
* @return OSS访问地址
|
* @return OSS object key(不含域名前缀)
|
||||||
*/
|
*/
|
||||||
public static String uploadToOSS(String localFilePath, String fileName) {
|
public static String uploadToOSS(String localFilePath, String fileName) {
|
||||||
OSS ossClient = null;
|
OSS ossClient = null;
|
||||||
try {
|
try {
|
||||||
// 创建OSS客户端
|
|
||||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||||
|
|
||||||
// 构建OSS文件路径:qrcode/2026/06/18/xxx.png
|
|
||||||
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
||||||
String ossFilePath = QRCODE_DIR + datePath + "/" + fileName;
|
String ossFilePath = QRCODE_DIR + datePath + "/" + fileName;
|
||||||
|
|
||||||
// 创建上传请求
|
|
||||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||||
|
|
||||||
// 上传文件
|
|
||||||
ossClient.putObject(putObjectRequest);
|
ossClient.putObject(putObjectRequest);
|
||||||
|
|
||||||
// 构建访问地址
|
logger.info("文件上传到OSS成功: localPath={}, ossKey={}", localFilePath, ossFilePath);
|
||||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
return ossFilePath;
|
||||||
|
|
||||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
|
||||||
|
|
||||||
return accessUrl;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||||
@@ -69,34 +71,25 @@ public class OSSUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 上传文件到阿里云OSS(自定义存储路径)
|
* 上传文件到阿里云OSS(自定义存储路径,文件默认继承Bucket权限)
|
||||||
*
|
*
|
||||||
* @param localFilePath 本地文件路径
|
* @param localFilePath 本地文件路径
|
||||||
* @param ossDirectory OSS存储目录
|
* @param ossDirectory OSS存储目录
|
||||||
* @param fileName 文件名(不含路径)
|
* @param fileName 文件名(不含路径)
|
||||||
* @return OSS访问地址
|
* @return OSS object key(不含域名前缀)
|
||||||
*/
|
*/
|
||||||
public static String uploadToOSS(String localFilePath, String ossDirectory, String fileName) {
|
public static String uploadToOSS(String localFilePath, String ossDirectory, String fileName) {
|
||||||
OSS ossClient = null;
|
OSS ossClient = null;
|
||||||
try {
|
try {
|
||||||
// 创建OSS客户端
|
|
||||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||||
|
|
||||||
// 构建OSS文件路径
|
|
||||||
String ossFilePath = ossDirectory + fileName;
|
String ossFilePath = ossDirectory + fileName;
|
||||||
|
|
||||||
// 创建上传请求
|
|
||||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||||
|
|
||||||
// 上传文件
|
|
||||||
ossClient.putObject(putObjectRequest);
|
ossClient.putObject(putObjectRequest);
|
||||||
|
|
||||||
// 构建访问地址
|
logger.info("文件上传到OSS成功: localPath={}, ossKey={}", localFilePath, ossFilePath);
|
||||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
return ossFilePath;
|
||||||
|
|
||||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
|
||||||
|
|
||||||
return accessUrl;
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||||
@@ -106,4 +99,95 @@ 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将OSS Key(相对路径)转换为封面图预签名URL(1小时有效期)
|
||||||
|
* 如果已经是HTTP(S)完整URL则直接返回
|
||||||
|
*
|
||||||
|
* @param ossKey OSS对象Key或完整URL
|
||||||
|
* @return 可访问的预签名URL,ossKey为空时返回null
|
||||||
|
*/
|
||||||
|
public static String toCoverPresignedUrl(String ossKey) {
|
||||||
|
if (ossKey == null || ossKey.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (ossKey.startsWith("http://") || ossKey.startsWith("https://")) {
|
||||||
|
return ossKey;
|
||||||
|
}
|
||||||
|
return generatePresignedUrl(ossKey, COVER_PRESIGN_EXPIRE_SECONDS);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-3
@@ -61,9 +61,7 @@ class QRCodeUtilTest {
|
|||||||
String ossUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent);
|
String ossUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent);
|
||||||
|
|
||||||
assertNotNull(ossUrl, "OSS访问地址不应为空");
|
assertNotNull(ossUrl, "OSS访问地址不应为空");
|
||||||
assertTrue(ossUrl.startsWith("https://"), "OSS访问地址应为HTTPS");
|
assertTrue(ossUrl.startsWith("qrcode/"), "OSS访问地址应以qrcode/开头");
|
||||||
assertTrue(ossUrl.contains("ycc-filesaver.oss-cn-beijing.aliyuncs.com"), "OSS访问地址应包含正确的域名");
|
|
||||||
assertTrue(ossUrl.contains("/qrcode/"), "OSS访问地址应包含qrcode目录");
|
|
||||||
assertTrue(ossUrl.endsWith(".png"), "OSS访问地址应为PNG格式");
|
assertTrue(ossUrl.endsWith(".png"), "OSS访问地址应为PNG格式");
|
||||||
|
|
||||||
System.out.println("上传到OSS的二维码地址: " + ossUrl);
|
System.out.println("上传到OSS的二维码地址: " + ossUrl);
|
||||||
|
|||||||
+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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
-10
@@ -2,16 +2,21 @@ package cn.novalon.gym.manage.member.handler;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
import cn.novalon.gym.manage.member.service.IMemberCardService;
|
import cn.novalon.gym.manage.member.service.IMemberCardService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 会员卡管理处理器
|
* 会员卡管理处理器
|
||||||
*
|
*
|
||||||
@@ -24,9 +29,13 @@ import reactor.core.publisher.Mono;
|
|||||||
public class MemberCardHandler {
|
public class MemberCardHandler {
|
||||||
|
|
||||||
private final IMemberCardService memberCardService;
|
private final IMemberCardService memberCardService;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public MemberCardHandler(IMemberCardService memberCardService) {
|
public MemberCardHandler(IMemberCardService memberCardService, ISysUserService sysUserService, AuthUtil authUtil) {
|
||||||
this.memberCardService = memberCardService;
|
this.memberCardService = memberCardService;
|
||||||
|
this.sysUserService = sysUserService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "根据ID查询会员卡类型", description = "查询指定ID的会员卡类型详情")
|
@Operation(summary = "根据ID查询会员卡类型", description = "查询指定ID的会员卡类型详情")
|
||||||
@@ -60,21 +69,65 @@ public class MemberCardHandler {
|
|||||||
.flatMap(card -> ServerResponse.status(HttpStatus.CREATED).bodyValue(card));
|
.flatMap(card -> ServerResponse.status(HttpStatus.CREATED).bodyValue(card));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新会员卡类型", description = "更新会员卡类型信息")
|
@Operation(summary = "更新会员卡类型", description = "更新会员卡类型信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> updateMemberCard(ServerRequest request) {
|
public Mono<ServerResponse> updateMemberCard(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
return request.bodyToMono(MemberCard.class)
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
.flatMap(card -> {
|
|
||||||
card.setMemberCardId(id);
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
return memberCardService.save(card);
|
return ServerResponse.badRequest()
|
||||||
})
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.flatMap(updated -> ServerResponse.ok().bodyValue(updated))
|
.bodyValue(Map.of("code", 400, "message", "管理员密码不能为空"))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.flatMap(resp -> Mono.just(resp));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除会员卡类型", description = "逻辑删除会员卡类型")
|
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 = "逻辑删除会员卡类型,需验证管理员密码")
|
||||||
public Mono<ServerResponse> deleteMemberCard(ServerRequest request) {
|
public Mono<ServerResponse> deleteMemberCard(ServerRequest request) {
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
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 memberCardService.logicalDelete(id)
|
return memberCardService.logicalDelete(id)
|
||||||
.flatMap(rows -> {
|
.flatMap(rows -> {
|
||||||
if (rows > 0) {
|
if (rows > 0) {
|
||||||
@@ -82,6 +135,7 @@ public class MemberCardHandler {
|
|||||||
}
|
}
|
||||||
return ServerResponse.notFound().build();
|
return ServerResponse.notFound().build();
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "购买会员卡", description = "会员购买会员卡,生成会员卡记录")
|
@Operation(summary = "购买会员卡", description = "会员购买会员卡,生成会员卡记录")
|
||||||
|
|||||||
+27
-8
@@ -1,7 +1,7 @@
|
|||||||
package cn.novalon.gym.manage.member.handler;
|
package cn.novalon.gym.manage.member.handler;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.common.exception.NotFoundException;
|
import cn.novalon.gym.manage.common.exception.NotFoundException;
|
||||||
import cn.novalon.gym.manage.member.config.WechatProperties;
|
import cn.novalon.gym.manage.member.dto.AdminEditMemberDto;
|
||||||
import cn.novalon.gym.manage.member.dto.AdminUpdatePhoneDto;
|
import cn.novalon.gym.manage.member.dto.AdminUpdatePhoneDto;
|
||||||
import cn.novalon.gym.manage.member.dto.SearchMemberDto;
|
import cn.novalon.gym.manage.member.dto.SearchMemberDto;
|
||||||
import cn.novalon.gym.manage.member.dto.UpdateMemberInfoDto;
|
import cn.novalon.gym.manage.member.dto.UpdateMemberInfoDto;
|
||||||
@@ -10,8 +10,8 @@ import cn.novalon.gym.manage.member.service.WechatAuthService;
|
|||||||
import cn.novalon.gym.manage.member.service.WechatOfficialService;
|
import cn.novalon.gym.manage.member.service.WechatOfficialService;
|
||||||
import cn.novalon.gym.manage.member.util.AesUtil;
|
import cn.novalon.gym.manage.member.util.AesUtil;
|
||||||
import cn.novalon.gym.manage.member.util.WechatPhoneUtil;
|
import cn.novalon.gym.manage.member.util.WechatPhoneUtil;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -24,6 +24,8 @@ import org.springframework.web.reactive.function.server.ServerRequest;
|
|||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 会员信息处理器
|
* 会员信息处理器
|
||||||
*
|
*
|
||||||
@@ -41,6 +43,7 @@ public class MemberHandler {
|
|||||||
private final WechatAuthService wechatAuthService;
|
private final WechatAuthService wechatAuthService;
|
||||||
private final WechatOfficialService wechatOfficialService;
|
private final WechatOfficialService wechatOfficialService;
|
||||||
private final AuthUtil authUtil;
|
private final AuthUtil authUtil;
|
||||||
|
private final ISysUserService sysUserService;
|
||||||
|
|
||||||
@Operation(summary = "获取会员信息", description = "根据当前登录用户获取会员基本信息")
|
@Operation(summary = "获取会员信息", description = "根据当前登录用户获取会员基本信息")
|
||||||
public Mono<ServerResponse> getMemberInfo(ServerRequest request) {
|
public Mono<ServerResponse> getMemberInfo(ServerRequest request) {
|
||||||
@@ -165,7 +168,7 @@ public class MemberHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "管理员编辑会员信息", description = "后台管理员编辑会员信息")
|
@Operation(summary = "管理员编辑会员信息", description = "后台管理员编辑会员信息,需验证管理员密码")
|
||||||
public Mono<ServerResponse> adminUpdateMemberInfo(ServerRequest request) {
|
public Mono<ServerResponse> adminUpdateMemberInfo(ServerRequest request) {
|
||||||
|
|
||||||
Long adminId = authUtil.getMemberIdOrThrow(request);
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
@@ -174,14 +177,30 @@ public class MemberHandler {
|
|||||||
long memberId = NumberUtils.toLong(memberIdStr, 0L);
|
long memberId = NumberUtils.toLong(memberIdStr, 0L);
|
||||||
if(memberId <= 0L) throw new IllegalArgumentException("会员ID格式错误");
|
if(memberId <= 0L) throw new IllegalArgumentException("会员ID格式错误");
|
||||||
|
|
||||||
// TODO: 补充签到记录
|
|
||||||
log.info("前台编辑会员信息, adminId: {}, memberId: {}", adminId, memberId);
|
log.info("前台编辑会员信息, adminId: {}, memberId: {}", adminId, memberId);
|
||||||
|
|
||||||
return request.bodyToMono(UpdateMemberInfoDto.class)
|
return request.bodyToMono(AdminEditMemberDto.class)
|
||||||
.flatMap(updateDto -> memberService.adminUpdateMemberInfo(memberId, updateDto))
|
.flatMap(dto -> {
|
||||||
.flatMap(detail -> ServerResponse.ok()
|
if (dto.getAdminPassword() == null || dto.getAdminPassword().isBlank()) {
|
||||||
|
return ServerResponse.badRequest()
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.bodyValue(detail));
|
.bodyValue(Map.of("code", 400, "message", "管理员密码不能为空"))
|
||||||
|
.flatMap(resp -> Mono.<ServerResponse>just(resp));
|
||||||
|
}
|
||||||
|
return sysUserService.verifyPassword(adminId, dto.getAdminPassword())
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
return ServerResponse.status(HttpStatus.FORBIDDEN)
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 403, "message", "管理员密码错误"))
|
||||||
|
.flatMap(resp -> Mono.<ServerResponse>just(resp));
|
||||||
|
}
|
||||||
|
return memberService.adminUpdateMemberInfo(memberId, dto.toUpdateMemberInfoDto())
|
||||||
|
.flatMap(result -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(result));
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "搜索会员列表", description = "后台管理员按关键词搜索会员,支持性别筛选和分页")
|
@Operation(summary = "搜索会员列表", description = "后台管理员按关键词搜索会员,支持性别筛选和分页")
|
||||||
|
|||||||
+12
@@ -110,6 +110,18 @@ public interface MemberCardRecordRepository extends R2dbcRepository<MemberCardRe
|
|||||||
@Query("SELECT * FROM member_card_record WHERE status = 'ACTIVE' AND expire_time < NOW() AND deleted_at IS NULL LIMIT 500")
|
@Query("SELECT * FROM member_card_record WHERE status = 'ACTIVE' AND expire_time < NOW() AND deleted_at IS NULL LIMIT 500")
|
||||||
Flux<MemberCardRecord> findExpiredCards();
|
Flux<MemberCardRecord> findExpiredCards();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据支付订单ID查询会员卡记录(用于幂等性检查)
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM member_card_record WHERE source_order_id = :sourceOrderId AND deleted_at IS NULL")
|
||||||
|
Mono<MemberCardRecord> findBySourceOrderId(Long sourceOrderId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员在指定时间后购买的同类活跃卡(防前端重复调用)
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM member_card_record WHERE member_id = :memberId AND member_card_id = :memberCardId AND status = 'ACTIVE' AND deleted_at IS NULL AND purchase_time > :since ORDER BY purchase_time DESC LIMIT 1")
|
||||||
|
Mono<MemberCardRecord> findRecentActivePurchase(Long memberId, Long memberCardId, LocalDateTime since);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询所有有效记录
|
* 查询所有有效记录
|
||||||
*/
|
*/
|
||||||
|
|||||||
+8
@@ -34,6 +34,14 @@ public interface MemberStoredCardRepository extends R2dbcRepository<MemberStored
|
|||||||
"WHERE member_id = :memberId AND deleted_at IS NULL")
|
"WHERE member_id = :memberId AND deleted_at IS NULL")
|
||||||
Mono<Integer> rechargeBalance(Long memberId, BigDecimal addAmount);
|
Mono<Integer> rechargeBalance(Long memberId, BigDecimal addAmount);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 储值卡返还 - 增加余额(用于取消预约退款)
|
||||||
|
*/
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE member_stored_card SET balance = balance + :addAmount, updated_at = NOW() " +
|
||||||
|
"WHERE member_id = :memberId AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> refundBalance(Long memberId, BigDecimal addAmount);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 储值卡消费 - 扣减余额
|
* 储值卡消费 - 扣减余额
|
||||||
*/
|
*/
|
||||||
|
|||||||
+11
@@ -52,6 +52,17 @@ public interface IMemberStoredCardService {
|
|||||||
*/
|
*/
|
||||||
Mono<PayResult> payWithStoredCard(Long memberId, String password, BigDecimal amount);
|
Mono<PayResult> payWithStoredCard(Long memberId, String password, BigDecimal amount);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 储值卡返还(取消预约退款,仅增加余额不修改充值总额)
|
||||||
|
*/
|
||||||
|
Mono<PayResult> refundToStoredCard(Long memberId, String password, BigDecimal amount, long cancelCount);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 储值卡返还(内部调用,无需密码,含手续费逻辑)
|
||||||
|
* @return 实际返还金额
|
||||||
|
*/
|
||||||
|
Mono<BigDecimal> refundBalanceWithFee(Long memberId, BigDecimal amount, long cancelCount);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询会员的充值记录列表
|
* 查询会员的充值记录列表
|
||||||
*/
|
*/
|
||||||
|
|||||||
+5
-5
@@ -213,9 +213,9 @@ public class MemberCardRecordServiceImpl implements IMemberCardRecordService {
|
|||||||
.filter(record -> record.getMemberCardType() == null ||
|
.filter(record -> record.getMemberCardType() == null ||
|
||||||
!record.getMemberCardType().equals("STORED_VALUE_CARD"))
|
!record.getMemberCardType().equals("STORED_VALUE_CARD"))
|
||||||
.collectList()
|
.collectList()
|
||||||
.map(records -> {
|
.flatMap(records -> {
|
||||||
if (records.isEmpty()) {
|
if (records.isEmpty()) {
|
||||||
return null;
|
return Mono.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 优先找临期卡(剩余1-3天)
|
// 优先找临期卡(剩余1-3天)
|
||||||
@@ -230,7 +230,7 @@ public class MemberCardRecordServiceImpl implements IMemberCardRecordService {
|
|||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
if (expiringCard != null) {
|
if (expiringCard != null) {
|
||||||
return expiringCard;
|
return Mono.just(expiringCard);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 再找普通有效卡(剩余>3天)
|
// 再找普通有效卡(剩余>3天)
|
||||||
@@ -245,11 +245,11 @@ public class MemberCardRecordServiceImpl implements IMemberCardRecordService {
|
|||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
if (activeCard != null) {
|
if (activeCard != null) {
|
||||||
return activeCard;
|
return Mono.just(activeCard);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 最后返回第一张卡
|
// 最后返回第一张卡
|
||||||
return records.get(0);
|
return Mono.just(records.get(0));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+38
-2
@@ -44,6 +44,7 @@ public class MemberCardServiceImpl implements IMemberCardService {
|
|||||||
|
|
||||||
private static final String MEMBER_CARD_CACHE_PREFIX = "member:card:";
|
private static final String MEMBER_CARD_CACHE_PREFIX = "member:card:";
|
||||||
private static final long CACHE_EXPIRE_SECONDS = 300;
|
private static final long CACHE_EXPIRE_SECONDS = 300;
|
||||||
|
private static final long DUPLICATE_WINDOW_SECONDS = 10;
|
||||||
|
|
||||||
public MemberCardServiceImpl(MemberCardRepository memberCardRepository,
|
public MemberCardServiceImpl(MemberCardRepository memberCardRepository,
|
||||||
MemberCardRecordRepository recordRepository,
|
MemberCardRecordRepository recordRepository,
|
||||||
@@ -130,6 +131,30 @@ public class MemberCardServiceImpl implements IMemberCardService {
|
|||||||
if (memberCardId == null) {
|
if (memberCardId == null) {
|
||||||
return Mono.error(new RuntimeException("会员卡类型ID不能为空"));
|
return Mono.error(new RuntimeException("会员卡类型ID不能为空"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 快速路径:幂等性检查,同一笔支付订单已创建过记录则直接返回
|
||||||
|
if (sourceOrderId != null) {
|
||||||
|
return recordRepository.findBySourceOrderId(sourceOrderId)
|
||||||
|
.flatMap(existingRecord -> {
|
||||||
|
log.info("支付订单已生成会员卡记录,幂等返回: sourceOrderId={}, memberCardRecordId={}",
|
||||||
|
sourceOrderId, existingRecord.getMemberCardRecordId());
|
||||||
|
return Mono.just(existingRecord);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> doPurchaseCard(memberId, memberCardId, sourceOrderId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// sourceOrderId为null(前端直接调用):检查10秒内是否已有同类卡,防前端重复调用
|
||||||
|
LocalDateTime since = LocalDateTime.now().minusSeconds(DUPLICATE_WINDOW_SECONDS);
|
||||||
|
return recordRepository.findRecentActivePurchase(memberId, memberCardId, since)
|
||||||
|
.flatMap(existingRecord -> {
|
||||||
|
log.info("前端重复购买检测命中: memberId={}, memberCardId={}, memberCardRecordId={}, purchaseTime={}",
|
||||||
|
memberId, memberCardId, existingRecord.getMemberCardRecordId(), existingRecord.getPurchaseTime());
|
||||||
|
return Mono.just(existingRecord);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> doPurchaseCard(memberId, memberCardId, sourceOrderId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<MemberCardRecord> doPurchaseCard(Long memberId, Long memberCardId, Long sourceOrderId) {
|
||||||
// 前端传的是数据库主键id,不是业务字段member_card_id
|
// 前端传的是数据库主键id,不是业务字段member_card_id
|
||||||
return memberCardRepository.findByIdAndDeletedAtIsNull(memberCardId)
|
return memberCardRepository.findByIdAndDeletedAtIsNull(memberCardId)
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡类型不存在")))
|
.switchIfEmpty(Mono.error(new RuntimeException("会员卡类型不存在")))
|
||||||
@@ -143,8 +168,19 @@ public class MemberCardServiceImpl implements IMemberCardService {
|
|||||||
return distributedLockService.executeWithLock(
|
return distributedLockService.executeWithLock(
|
||||||
memberId.toString(),
|
memberId.toString(),
|
||||||
cardType.name(),
|
cardType.name(),
|
||||||
Mono.defer(() -> createCardRecord(memberId, memberCardId, sourceOrderId, card))
|
Mono.defer(() -> {
|
||||||
// 修改:将 card 对象传递给 createTransaction 以获取购买金额
|
// 持锁后再次检查幂等,防止并发请求同时通过外层检查
|
||||||
|
if (sourceOrderId != null) {
|
||||||
|
return recordRepository.findBySourceOrderId(sourceOrderId)
|
||||||
|
.flatMap(existingRecord -> {
|
||||||
|
log.info("持锁幂等检查命中: sourceOrderId={}, memberCardRecordId={}",
|
||||||
|
sourceOrderId, existingRecord.getMemberCardRecordId());
|
||||||
|
return Mono.just(existingRecord);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> createCardRecord(memberId, memberCardId, sourceOrderId, card)));
|
||||||
|
}
|
||||||
|
return createCardRecord(memberId, memberCardId, sourceOrderId, card);
|
||||||
|
})
|
||||||
.flatMap(record -> createTransactionForPurchase(record, card, TransactionType.PURCHASE, "购买会员卡")
|
.flatMap(record -> createTransactionForPurchase(record, card, TransactionType.PURCHASE, "购买会员卡")
|
||||||
.thenReturn(record))
|
.thenReturn(record))
|
||||||
.flatMap(record -> expirationReminderService.scheduleExpirationReminder(record)
|
.flatMap(record -> expirationReminderService.scheduleExpirationReminder(record)
|
||||||
|
|||||||
+15
-2
@@ -254,6 +254,16 @@ public class MemberServiceImpl implements MemberService {
|
|||||||
log.debug("从缓存获取会员详情, memberId: {}", memberId);
|
log.debug("从缓存获取会员详情, memberId: {}", memberId);
|
||||||
return Mono.just(cached);
|
return Mono.just(cached);
|
||||||
}
|
}
|
||||||
|
// 缓存反序列化异常,查数据库
|
||||||
|
return queryMemberDetailFromDb(memberId, cacheKey);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
|
// 缓存不存在,查数据库
|
||||||
|
return queryMemberDetailFromDb(memberId, cacheKey);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<MemberDetailVO> queryMemberDetailFromDb(Long memberId, String cacheKey) {
|
||||||
return memberRepository.findById(memberId)
|
return memberRepository.findById(memberId)
|
||||||
.zipWith(
|
.zipWith(
|
||||||
memberRepository.findCardRecordsWithCardInfoByMemberId(memberId)
|
memberRepository.findCardRecordsWithCardInfoByMemberId(memberId)
|
||||||
@@ -291,8 +301,11 @@ public class MemberServiceImpl implements MemberService {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
.flatMap(vo -> redisUtil.setWithExpire(cacheKey, vo, CACHE_EXPIRE_SECONDS)
|
.flatMap(vo -> redisUtil.setWithExpire(cacheKey, vo, CACHE_EXPIRE_SECONDS)
|
||||||
.then(Mono.just(vo)));
|
.then(Mono.just(vo)))
|
||||||
});
|
.switchIfEmpty(Mono.error(() -> {
|
||||||
|
log.error("会员不存在: memberId={}", memberId);
|
||||||
|
return new NotFoundException(ErrorCode.NOT_FOUND_USER, "会员不存在");
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+87
-1
@@ -5,6 +5,7 @@ import cn.novalon.gym.manage.member.entity.MemberStoredCardRecharge;
|
|||||||
import cn.novalon.gym.manage.member.repository.MemberStoredCardRechargeRepository;
|
import cn.novalon.gym.manage.member.repository.MemberStoredCardRechargeRepository;
|
||||||
import cn.novalon.gym.manage.member.repository.MemberStoredCardRepository;
|
import cn.novalon.gym.manage.member.repository.MemberStoredCardRepository;
|
||||||
import cn.novalon.gym.manage.member.service.IMemberStoredCardService;
|
import cn.novalon.gym.manage.member.service.IMemberStoredCardService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysConfigService;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -22,12 +23,15 @@ public class MemberStoredCardServiceImpl implements IMemberStoredCardService {
|
|||||||
|
|
||||||
private final MemberStoredCardRepository memberStoredCardRepository;
|
private final MemberStoredCardRepository memberStoredCardRepository;
|
||||||
private final MemberStoredCardRechargeRepository memberStoredCardRechargeRepository;
|
private final MemberStoredCardRechargeRepository memberStoredCardRechargeRepository;
|
||||||
|
private final ISysConfigService sysConfigService;
|
||||||
private final BCryptPasswordEncoder passwordEncoder;
|
private final BCryptPasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
public MemberStoredCardServiceImpl(MemberStoredCardRepository memberStoredCardRepository,
|
public MemberStoredCardServiceImpl(MemberStoredCardRepository memberStoredCardRepository,
|
||||||
MemberStoredCardRechargeRepository memberStoredCardRechargeRepository) {
|
MemberStoredCardRechargeRepository memberStoredCardRechargeRepository,
|
||||||
|
ISysConfigService sysConfigService) {
|
||||||
this.memberStoredCardRepository = memberStoredCardRepository;
|
this.memberStoredCardRepository = memberStoredCardRepository;
|
||||||
this.memberStoredCardRechargeRepository = memberStoredCardRechargeRepository;
|
this.memberStoredCardRechargeRepository = memberStoredCardRechargeRepository;
|
||||||
|
this.sysConfigService = sysConfigService;
|
||||||
this.passwordEncoder = new BCryptPasswordEncoder();
|
this.passwordEncoder = new BCryptPasswordEncoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,12 +141,94 @@ public class MemberStoredCardServiceImpl implements IMemberStoredCardService {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<PayResult> refundToStoredCard(Long memberId, String password, BigDecimal amount, long cancelCount) {
|
||||||
|
// 从系统配置读取免手续费次数阈值,默认3次
|
||||||
|
Mono<Long> freeLimitMono = sysConfigService.getConfigValue("group_course.cancel_free_limit")
|
||||||
|
.map(Long::parseLong)
|
||||||
|
.defaultIfEmpty(3L);
|
||||||
|
|
||||||
|
return freeLimitMono.flatMap(freeLimit ->
|
||||||
|
memberStoredCardRepository.findByMemberId(memberId)
|
||||||
|
.flatMap(card -> {
|
||||||
|
// 验证密码
|
||||||
|
if (card.getPayPassword() == null || card.getPayPassword().isEmpty()) {
|
||||||
|
log.warn("[储值卡退款] 未设置支付密码: memberId={}", memberId);
|
||||||
|
return Mono.just(PayResult.fail("请先设置支付密码"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!passwordEncoder.matches(password, card.getPayPassword())) {
|
||||||
|
log.warn("[储值卡退款] 密码错误: memberId={}", memberId);
|
||||||
|
return Mono.just(PayResult.fail("支付密码错误"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 前N次取消不扣手续费,超出后扣除10%
|
||||||
|
BigDecimal refundAmount = amount;
|
||||||
|
BigDecimal fee = BigDecimal.ZERO;
|
||||||
|
if (cancelCount >= freeLimit) {
|
||||||
|
fee = amount.multiply(new BigDecimal("0.1")).setScale(2, java.math.RoundingMode.HALF_UP);
|
||||||
|
refundAmount = amount.subtract(fee);
|
||||||
|
log.info("[储值卡退款] 第{}次取消,已超出免手续费阈值({}次),扣除10%手续费: 原额={}, 手续费={}, 退款={}",
|
||||||
|
cancelCount + 1, freeLimit, amount, fee, refundAmount);
|
||||||
|
} else {
|
||||||
|
log.info("[储值卡退款] 第{}次取消,在免手续费阈值({}次)内,全额退款: 原额={}",
|
||||||
|
cancelCount + 1, freeLimit, amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行退款
|
||||||
|
BigDecimal finalRefundAmount = refundAmount;
|
||||||
|
return memberStoredCardRepository.refundBalance(memberId, refundAmount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
return memberStoredCardRepository.findByMemberId(memberId)
|
||||||
|
.map(updatedCard -> PayResult.success(
|
||||||
|
updatedCard.getBalance() != null ? updatedCard.getBalance() : BigDecimal.ZERO));
|
||||||
|
} else {
|
||||||
|
log.warn("[储值卡退款] 退款失败: memberId={}, amount={}", memberId, finalRefundAmount);
|
||||||
|
return Mono.just(PayResult.fail("退款失败,请稍后重试"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
|
log.warn("[储值卡退款] 储值卡不存在: memberId={}", memberId);
|
||||||
|
return Mono.just(PayResult.fail("储值卡不存在"));
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Flux<MemberStoredCardRecharge> getRechargeRecords(Long memberId, int page, int size) {
|
public Flux<MemberStoredCardRecharge> getRechargeRecords(Long memberId, int page, int size) {
|
||||||
int offset = (page - 1) * size;
|
int offset = (page - 1) * size;
|
||||||
return memberStoredCardRechargeRepository.findByMemberId(memberId, size, offset);
|
return memberStoredCardRechargeRepository.findByMemberId(memberId, size, offset);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<BigDecimal> refundBalanceWithFee(Long memberId, BigDecimal amount, long cancelCount) {
|
||||||
|
return sysConfigService.getConfigValue("group_course.cancel_free_limit")
|
||||||
|
.map(Long::parseLong)
|
||||||
|
.defaultIfEmpty(3L)
|
||||||
|
.flatMap(freeLimit -> {
|
||||||
|
BigDecimal refundAmount;
|
||||||
|
if (cancelCount >= freeLimit) {
|
||||||
|
BigDecimal fee = amount.multiply(new BigDecimal("0.1")).setScale(2, java.math.RoundingMode.HALF_UP);
|
||||||
|
refundAmount = amount.subtract(fee);
|
||||||
|
log.info("[储值卡退款-内部] 第{}次取消,超出免手续费阈值({}次),扣除10%: 原额={}, 手续费={}, 退款={}",
|
||||||
|
cancelCount + 1, freeLimit, amount, fee, refundAmount);
|
||||||
|
} else {
|
||||||
|
refundAmount = amount;
|
||||||
|
log.info("[储值卡退款-内部] 第{}次取消,在免手续费阈值({}次)内,全额退款: {}",
|
||||||
|
cancelCount + 1, freeLimit, amount);
|
||||||
|
}
|
||||||
|
return memberStoredCardRepository.refundBalance(memberId, refundAmount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
return Mono.just(refundAmount);
|
||||||
|
}
|
||||||
|
return Mono.error(new RuntimeException("储值卡退款失败"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Long> countRechargeRecords(Long memberId) {
|
public Mono<Long> countRechargeRecords(Long memberId) {
|
||||||
return memberStoredCardRechargeRepository.countByMemberIdAndDeletedAtIsNull(memberId);
|
return memberStoredCardRechargeRepository.countByMemberIdAndDeletedAtIsNull(memberId);
|
||||||
|
|||||||
+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.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
@@ -38,4 +39,24 @@ public interface PaymentOrderRepository extends R2dbcRepository<PaymentOrder, Lo
|
|||||||
Flux<PaymentOrder> findAllByDeletedAtIsNull();
|
Flux<PaymentOrder> findAllByDeletedAtIsNull();
|
||||||
|
|
||||||
Flux<PaymentOrder> findByMemberIdAndDeletedAtIsNull(Long memberId);
|
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;
|
package cn.novalon.gym.manage.payment.service;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.payment.dto.CreatePaymentRequest;
|
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.PaymentResponse;
|
||||||
|
import cn.novalon.gym.manage.payment.dto.RevenueStatistics;
|
||||||
import reactor.core.publisher.Flux;
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
@@ -30,4 +32,10 @@ public interface PaymentService {
|
|||||||
Mono<PaymentResponse> getPendingOrder(Long memberId, String orderType);
|
Mono<PaymentResponse> getPendingOrder(Long memberId, String orderType);
|
||||||
|
|
||||||
Mono<Boolean> closeOrder(Long memberId, String orderId);
|
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);
|
||||||
}
|
}
|
||||||
+80
-8
@@ -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.common.util.RedisUtil;
|
||||||
import cn.novalon.gym.manage.payment.config.HuifuProperties;
|
import cn.novalon.gym.manage.payment.config.HuifuProperties;
|
||||||
import cn.novalon.gym.manage.payment.dto.CreatePaymentRequest;
|
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.PaymentResponse;
|
||||||
|
import cn.novalon.gym.manage.payment.dto.RevenueStatistics;
|
||||||
import cn.novalon.gym.manage.payment.entity.PaymentOrder;
|
import cn.novalon.gym.manage.payment.entity.PaymentOrder;
|
||||||
import cn.novalon.gym.manage.payment.repository.PaymentOrderRepository;
|
import cn.novalon.gym.manage.payment.repository.PaymentOrderRepository;
|
||||||
import cn.novalon.gym.manage.payment.service.PaymentNotifyService;
|
import cn.novalon.gym.manage.payment.service.PaymentNotifyService;
|
||||||
@@ -222,28 +224,26 @@ public class PaymentServiceImpl implements PaymentService {
|
|||||||
if ("00000000".equals(respCode)) {
|
if ("00000000".equals(respCode)) {
|
||||||
if ("S".equals(transStat)) {
|
if ("S".equals(transStat)) {
|
||||||
if (!"SUCCESS".equals(order.getPayStatus())) {
|
if (!"SUCCESS".equals(order.getPayStatus())) {
|
||||||
log.info("[Huifu] 查询到支付成功,更新订单状态并触发业务处理, orderNo={}, orderType={}",
|
log.info("[Huifu] 查询到支付成功,更新订单状态并触发业务通知, orderNo={}", order.getOrderNo());
|
||||||
order.getOrderNo(), order.getOrderType());
|
|
||||||
order.setPayStatus("SUCCESS");
|
order.setPayStatus("SUCCESS");
|
||||||
order.setHfSeqId(String.valueOf(response.getOrDefault("hf_seq_id", order.getHfSeqId())));
|
order.setHfSeqId(String.valueOf(response.getOrDefault("hf_seq_id", order.getHfSeqId())));
|
||||||
order.setPayTime(LocalDateTime.now());
|
order.setPayTime(LocalDateTime.now());
|
||||||
return paymentOrderRepository.save(order)
|
return paymentOrderRepository.save(order)
|
||||||
.flatMap(savedOrder -> {
|
.flatMap(savedOrder -> {
|
||||||
log.info("[Huifu] 订单状态已更新,开始触发业务处理, orderNo={}", savedOrder.getOrderNo());
|
log.info("[Huifu] 订单状态已更新为SUCCESS, orderNo={}", savedOrder.getOrderNo());
|
||||||
return paymentNotifyService.notifyPaymentStatus(savedOrder.getOrderNo(), "SUCCESS", memberId)
|
return paymentNotifyService.notifyPaymentStatus(savedOrder.getOrderNo(), "SUCCESS", savedOrder.getMemberId())
|
||||||
.thenReturn(convertToResponse(savedOrder));
|
.thenReturn(convertToResponse(savedOrder));
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
log.info("[Huifu] 订单已处理过,跳过业务处理, orderNo={}", order.getOrderNo());
|
log.info("[Huifu] 订单已处理过,跳过, orderNo={}", order.getOrderNo());
|
||||||
}
|
}
|
||||||
} else if ("F".equals(transStat)) {
|
} else if ("F".equals(transStat)) {
|
||||||
if (!"FAIL".equals(order.getPayStatus())) {
|
if (!"FAIL".equals(order.getPayStatus())) {
|
||||||
log.info("[Huifu] 查询到支付失败,更新订单状态, orderNo={}", order.getOrderNo());
|
log.info("[Huifu] 查询到支付失败,仅更新订单状态, orderNo={}", order.getOrderNo());
|
||||||
order.setPayStatus("FAIL");
|
order.setPayStatus("FAIL");
|
||||||
order.setErrorMsg(String.valueOf(response.getOrDefault("resp_desc", "支付失败")));
|
order.setErrorMsg(String.valueOf(response.getOrDefault("resp_desc", "支付失败")));
|
||||||
return paymentOrderRepository.save(order)
|
return paymentOrderRepository.save(order)
|
||||||
.flatMap(savedOrder -> paymentNotifyService.notifyPaymentStatus(savedOrder.getOrderNo(), "FAIL", memberId)
|
.map(savedOrder -> convertToResponse(savedOrder));
|
||||||
.thenReturn(convertToResponse(savedOrder)));
|
|
||||||
}
|
}
|
||||||
} else if ("P".equals(transStat)) {
|
} else if ("P".equals(transStat)) {
|
||||||
order.setPayStatus("PENDING");
|
order.setPayStatus("PENDING");
|
||||||
@@ -936,4 +936,76 @@ public class PaymentServiceImpl implements PaymentService {
|
|||||||
})
|
})
|
||||||
.switchIfEmpty(Mono.just(false));
|
.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;
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1945
-896
File diff suppressed because it is too large
Load Diff
+36
-3
@@ -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.auth.handler.PhoneAuthHandler;
|
||||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseBookingHandler;
|
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseBookingHandler;
|
||||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseHandler;
|
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.GroupCourseRecommendHandler;
|
||||||
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseTypeHandler;
|
import cn.novalon.gym.manage.groupcourse.handler.GroupCourseTypeHandler;
|
||||||
import cn.novalon.gym.manage.groupcourse.handler.CourseLabelHandler;
|
import cn.novalon.gym.manage.groupcourse.handler.CourseLabelHandler;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.handler.CommonUploadHandler;
|
||||||
import cn.novalon.gym.manage.member.handler.MemberCardHandler;
|
import cn.novalon.gym.manage.member.handler.MemberCardHandler;
|
||||||
import cn.novalon.gym.manage.member.handler.MemberCardRecordHandler;
|
import cn.novalon.gym.manage.member.handler.MemberCardRecordHandler;
|
||||||
import cn.novalon.gym.manage.member.handler.MemberCardTransactionHandler;
|
import cn.novalon.gym.manage.member.handler.MemberCardTransactionHandler;
|
||||||
@@ -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.SysNoticeHandler;
|
||||||
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
|
import cn.novalon.gym.manage.notify.handler.SysUserMessageHandler;
|
||||||
import cn.novalon.gym.manage.payment.handler.PaymentHandler;
|
import cn.novalon.gym.manage.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.PasswordDiagnosticHandler;
|
||||||
import cn.novalon.gym.manage.sys.handler.auth.SysAuthHandler;
|
import cn.novalon.gym.manage.sys.handler.auth.SysAuthHandler;
|
||||||
import cn.novalon.gym.manage.sys.handler.config.SysConfigHandler;
|
import cn.novalon.gym.manage.sys.handler.config.SysConfigHandler;
|
||||||
@@ -79,10 +82,13 @@ public class SystemRouter {
|
|||||||
GroupCourseRecommendHandler groupCourseRecommendHandler,
|
GroupCourseRecommendHandler groupCourseRecommendHandler,
|
||||||
GroupCourseTypeHandler groupCourseTypeHandler,
|
GroupCourseTypeHandler groupCourseTypeHandler,
|
||||||
CourseLabelHandler courseLabelHandler,
|
CourseLabelHandler courseLabelHandler,
|
||||||
|
BannerHandler bannerHandler,
|
||||||
CheckInHandler checkInHandler,
|
CheckInHandler checkInHandler,
|
||||||
DataStatisticsHandler dataStatisticsHandler,
|
DataStatisticsHandler dataStatisticsHandler,
|
||||||
PhoneAuthHandler phoneAuthHandler,
|
PhoneAuthHandler phoneAuthHandler,
|
||||||
PaymentHandler paymentHandler) {
|
PaymentHandler paymentHandler,
|
||||||
|
PaymentRevenueHandler paymentRevenueHandler,
|
||||||
|
CommonUploadHandler commonUploadHandler) {
|
||||||
|
|
||||||
return route()
|
return route()
|
||||||
// ========== 诊断路由 ==========
|
// ========== 诊断路由 ==========
|
||||||
@@ -170,6 +176,7 @@ public class SystemRouter {
|
|||||||
.POST("/api/auth/login", authHandler::login)
|
.POST("/api/auth/login", authHandler::login)
|
||||||
.POST("/api/auth/register", authHandler::register)
|
.POST("/api/auth/register", authHandler::register)
|
||||||
.POST("/api/auth/logout", authHandler::logout)
|
.POST("/api/auth/logout", authHandler::logout)
|
||||||
|
.GET("/api/auth/me", authHandler::me)
|
||||||
|
|
||||||
// ========== 统计路由 ==========
|
// ========== 统计路由 ==========
|
||||||
.GET("/api/stats/overview", statsHandler::getOverview)
|
.GET("/api/stats/overview", statsHandler::getOverview)
|
||||||
@@ -217,6 +224,10 @@ public class SystemRouter {
|
|||||||
.GET("/api/files/preview/{fileName}", fileHandler::previewFileByName)
|
.GET("/api/files/preview/{fileName}", fileHandler::previewFileByName)
|
||||||
.DELETE("/api/files/{id}", fileHandler::deleteFile)
|
.DELETE("/api/files/{id}", fileHandler::deleteFile)
|
||||||
|
|
||||||
|
// ===== 通用文件上传(OSS)=====
|
||||||
|
.POST("/api/upload/image", commonUploadHandler::uploadImage)
|
||||||
|
.GET("/api/upload/presign", commonUploadHandler::presignUrl)
|
||||||
|
|
||||||
// ========== 权限路由 ==========
|
// ========== 权限路由 ==========
|
||||||
.GET("/api/permissions", permissionHandler::getAllPermissions)
|
.GET("/api/permissions", permissionHandler::getAllPermissions)
|
||||||
.GET("/api/permissions/{id}", permissionHandler::getPermissionById)
|
.GET("/api/permissions/{id}", permissionHandler::getPermissionById)
|
||||||
@@ -257,8 +268,11 @@ public class SystemRouter {
|
|||||||
|
|
||||||
// ===== 会员卡类型管理 =====
|
// ===== 会员卡类型管理 =====
|
||||||
.GET("/api/member-cards/active", memberCardHandler::getActiveCards)
|
.GET("/api/member-cards/active", memberCardHandler::getActiveCards)
|
||||||
|
.GET("/api/member-cards", memberCardHandler::listMemberCards)
|
||||||
.GET("/api/member-cards/{memberCardId}", memberCardHandler::getMemberCardById)
|
.GET("/api/member-cards/{memberCardId}", memberCardHandler::getMemberCardById)
|
||||||
.POST("/api/member-cards", memberCardHandler::createMemberCard)
|
.POST("/api/member-cards", memberCardHandler::createMemberCard)
|
||||||
|
.PUT("/api/member-cards/{id}", memberCardHandler::updateMemberCard)
|
||||||
|
.DELETE("/api/member-cards/{id}", memberCardHandler::deleteMemberCard)
|
||||||
|
|
||||||
// ===== 会员卡记录管理(核心业务)=====
|
// ===== 会员卡记录管理(核心业务)=====
|
||||||
.POST("/api/member-card-records/purchase", memberCardRecordHandler::purchaseCard)
|
.POST("/api/member-card-records/purchase", memberCardRecordHandler::purchaseCard)
|
||||||
@@ -338,13 +352,26 @@ public class SystemRouter {
|
|||||||
.POST("/api/groupCourse/recommend/{id}/enable", groupCourseRecommendHandler::enableRecommendation)
|
.POST("/api/groupCourse/recommend/{id}/enable", groupCourseRecommendHandler::enableRecommendation)
|
||||||
.POST("/api/groupCourse/recommend/{id}/disable", groupCourseRecommendHandler::disableRecommendation)
|
.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}", groupCourseHandler::getGroupCourseById)
|
||||||
.GET("/api/groupCourse/{id}/detail", groupCourseHandler::getGroupCourseDetailById)
|
.GET("/api/groupCourse/{id}/detail", groupCourseHandler::getGroupCourseDetailById)
|
||||||
.POST("/api/groupCourse", groupCourseHandler::createGroupCourse)
|
.POST("/api/groupCourse", groupCourseHandler::createGroupCourse)
|
||||||
.PUT("/api/groupCourse/{id}", groupCourseHandler::updateGroupCourse)
|
.PUT("/api/groupCourse/{id}", groupCourseHandler::updateGroupCourse)
|
||||||
.DELETE("/api/groupCourse/{id}", groupCourseHandler::deleteGroupCourse)
|
.DELETE("/api/groupCourse/{id}", groupCourseHandler::deleteGroupCourse)
|
||||||
.POST("/api/groupCourse/{id}/cancel", groupCourseHandler::cancelGroupCourse)
|
.POST("/api/groupCourse/{id}/cancel", groupCourseHandler::cancelGroupCourse)
|
||||||
|
.POST("/api/groupCourse/{id}/restore", groupCourseHandler::restoreGroupCourse)
|
||||||
.POST("/api/groupCourse/signin/{memberId}", groupCourseHandler::signIn)
|
.POST("/api/groupCourse/signin/{memberId}", groupCourseHandler::signIn)
|
||||||
.POST("/api/groupCourse/search", groupCourseHandler::searchGroupCourses)
|
.POST("/api/groupCourse/search", groupCourseHandler::searchGroupCourses)
|
||||||
|
|
||||||
@@ -354,6 +381,7 @@ public class SystemRouter {
|
|||||||
.GET("/api/checkIn/qrcode", checkInHandler::getQRCode)
|
.GET("/api/checkIn/qrcode", checkInHandler::getQRCode)
|
||||||
|
|
||||||
// ===== 签到记录管理 =====
|
// ===== 签到记录管理 =====
|
||||||
|
.GET("/api/checkIn/records/export", checkInHandler::exportSignInRecords)
|
||||||
.GET("/api/checkIn/records", checkInHandler::getSignInRecords)
|
.GET("/api/checkIn/records", checkInHandler::getSignInRecords)
|
||||||
.GET("/api/checkIn/records/{id}", checkInHandler::getSignInRecordById)
|
.GET("/api/checkIn/records/{id}", checkInHandler::getSignInRecordById)
|
||||||
|
|
||||||
@@ -361,8 +389,9 @@ public class SystemRouter {
|
|||||||
.GET("/api/checkIn/statistics", checkInHandler::getSignInStatistics)
|
.GET("/api/checkIn/statistics", checkInHandler::getSignInStatistics)
|
||||||
.GET("/api/checkIn/daily-stats", checkInHandler::getDailySignInStats)
|
.GET("/api/checkIn/daily-stats", checkInHandler::getDailySignInStats)
|
||||||
|
|
||||||
// ===== 签到数据导出 =====
|
// ===== 管理员签到记录(全员) =====
|
||||||
.GET("/api/checkIn/records/export", checkInHandler::exportSignInRecords)
|
.GET("/api/checkIn/admin/records", checkInHandler::getAllSignInRecords)
|
||||||
|
.GET("/api/checkIn/admin/statistics", checkInHandler::getAllSignInStatistics)
|
||||||
|
|
||||||
// ========================================
|
// ========================================
|
||||||
// ========== 数据统计模块路由 ============
|
// ========== 数据统计模块路由 ============
|
||||||
@@ -391,6 +420,10 @@ public class SystemRouter {
|
|||||||
.POST("/api/payment/{orderId}/refund", paymentHandler::refundPayment)
|
.POST("/api/payment/{orderId}/refund", paymentHandler::refundPayment)
|
||||||
.POST("/api/payment/{orderId}/close", paymentHandler::closeOrder)
|
.POST("/api/payment/{orderId}/close", paymentHandler::closeOrder)
|
||||||
|
|
||||||
|
// ===== 支付营业数据 =====
|
||||||
|
.GET("/api/payment/revenue/statistics", paymentRevenueHandler::getRevenueStatistics)
|
||||||
|
.GET("/api/payment/revenue/records", paymentRevenueHandler::getPaymentRecords)
|
||||||
|
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-7
@@ -22,7 +22,6 @@ public class PaymentNotifyServiceImpl implements PaymentNotifyService {
|
|||||||
private final MemberStoredCardRepository memberStoredCardRepository;
|
private final MemberStoredCardRepository memberStoredCardRepository;
|
||||||
private final MemberStoredCardRechargeRepository memberStoredCardRechargeRepository;
|
private final MemberStoredCardRechargeRepository memberStoredCardRechargeRepository;
|
||||||
private final IMemberCardService memberCardService;
|
private final IMemberCardService memberCardService;
|
||||||
private Long memberIdGlob;
|
|
||||||
|
|
||||||
public PaymentNotifyServiceImpl(PaymentOrderRepository paymentOrderRepository,
|
public PaymentNotifyServiceImpl(PaymentOrderRepository paymentOrderRepository,
|
||||||
MemberStoredCardRepository memberStoredCardRepository,
|
MemberStoredCardRepository memberStoredCardRepository,
|
||||||
@@ -35,8 +34,7 @@ public class PaymentNotifyServiceImpl implements PaymentNotifyService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<Void> notifyPaymentStatus(String orderNo, String status,Long memberId) {
|
public Mono<Void> notifyPaymentStatus(String orderNo, String status, Long memberId) {
|
||||||
memberIdGlob = memberId;
|
|
||||||
return paymentOrderRepository.findByOrderNo(orderNo)
|
return paymentOrderRepository.findByOrderNo(orderNo)
|
||||||
.flatMap(order -> {
|
.flatMap(order -> {
|
||||||
log.info("[PaymentNotify] 支付通知: orderNo={}, status={}, orderType={}", orderNo, status, order.getOrderType());
|
log.info("[PaymentNotify] 支付通知: orderNo={}, status={}, orderType={}", orderNo, status, order.getOrderType());
|
||||||
@@ -114,19 +112,33 @@ public class PaymentNotifyServiceImpl implements PaymentNotifyService {
|
|||||||
final Long finalMemberCardId = memberCardId;
|
final Long finalMemberCardId = memberCardId;
|
||||||
final int finalCount = count;
|
final int finalCount = count;
|
||||||
final Long sourceOrderId = order.getId();
|
final Long sourceOrderId = order.getId();
|
||||||
|
final Long orderMemberId = order.getMemberId();
|
||||||
|
|
||||||
log.info("[PaymentNotify] 处理会员卡购买: orderNo={}, memberId={}, memberCardId={}, count={}",
|
log.info("[PaymentNotify] 处理会员卡购买: orderNo={}, memberId={}, memberCardId={}, count={}",
|
||||||
order.getOrderNo(), memberIdGlob, finalMemberCardId, finalCount);
|
order.getOrderNo(), orderMemberId, finalMemberCardId, finalCount);
|
||||||
|
|
||||||
return memberCardService.purchaseCard(memberIdGlob, finalMemberCardId, sourceOrderId)
|
// 幂等性检查:同一笔支付订单只创建一次会员卡记录
|
||||||
|
return memberCardService.purchaseCard(orderMemberId, finalMemberCardId, sourceOrderId)
|
||||||
.doOnSuccess(record -> log.info("[PaymentNotify] 会员卡购买完成: orderNo={}, memberId={}, memberCardRecordId={}",
|
.doOnSuccess(record -> log.info("[PaymentNotify] 会员卡购买完成: orderNo={}, memberId={}, memberCardRecordId={}",
|
||||||
order.getOrderNo(), memberIdGlob, record.getMemberCardRecordId()))
|
order.getOrderNo(), orderMemberId, record.getMemberCardRecordId()))
|
||||||
.doOnError(e -> log.error("[PaymentNotify] 会员卡购买异常, orderNo={}", order.getOrderNo(), e))
|
.doOnError(e -> log.error("[PaymentNotify] 会员卡购买异常, orderNo={}", order.getOrderNo(), e))
|
||||||
.onErrorResume(e -> Mono.empty())
|
.onErrorResume(e -> Mono.empty())
|
||||||
.then();
|
.then();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Mono<Void> handleStoredCardRecharge(PaymentOrder order) {
|
private Mono<Void> handleStoredCardRecharge(PaymentOrder order) {
|
||||||
|
String orderNo = order.getOrderNo();
|
||||||
|
|
||||||
|
return memberStoredCardRechargeRepository.findByOrderNo(orderNo)
|
||||||
|
.flatMap(existing -> {
|
||||||
|
log.info("[PaymentNotify] 充值记录已存在,跳过重复处理, orderNo={}, status={}", orderNo, existing.getStatus());
|
||||||
|
return Mono.<Void>empty();
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> doHandleStoredCardRecharge(order)))
|
||||||
|
.then();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> doHandleStoredCardRecharge(PaymentOrder order) {
|
||||||
String remark = order.getRemark();
|
String remark = order.getRemark();
|
||||||
log.info("[PaymentNotify] 开始处理储值卡充值, orderNo={}, memberId={}, orderType={}, remark={}",
|
log.info("[PaymentNotify] 开始处理储值卡充值, orderNo={}, memberId={}, orderType={}, remark={}",
|
||||||
order.getOrderNo(), order.getMemberId(), order.getOrderType(), remark);
|
order.getOrderNo(), order.getMemberId(), order.getOrderType(), remark);
|
||||||
@@ -166,7 +178,7 @@ public class PaymentNotifyServiceImpl implements PaymentNotifyService {
|
|||||||
final BigDecimal finalRechargeAmount = rechargeAmount;
|
final BigDecimal finalRechargeAmount = rechargeAmount;
|
||||||
final BigDecimal finalBonus = bonus != null ? bonus : BigDecimal.ZERO;
|
final BigDecimal finalBonus = bonus != null ? bonus : BigDecimal.ZERO;
|
||||||
final BigDecimal totalAddAmount = finalRechargeAmount.add(finalBonus);
|
final BigDecimal totalAddAmount = finalRechargeAmount.add(finalBonus);
|
||||||
Long memberId = memberIdGlob;
|
Long memberId = order.getMemberId();
|
||||||
final String orderNo = order.getOrderNo();
|
final String orderNo = order.getOrderNo();
|
||||||
final BigDecimal payAmount = order.getTransAmt();
|
final BigDecimal payAmount = order.getTransAmt();
|
||||||
final LocalDateTime now = LocalDateTime.now();
|
final LocalDateTime now = LocalDateTime.now();
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ spring:
|
|||||||
cache:
|
cache:
|
||||||
type: none
|
type: none
|
||||||
r2dbc:
|
r2dbc:
|
||||||
url: r2dbc:postgresql://localhost:5432/manage_system
|
url: r2dbc:postgresql://localhost:55432/manage_system
|
||||||
username: postgres
|
username: novalon
|
||||||
password: 123456
|
password: novalon123
|
||||||
pool:
|
pool:
|
||||||
initial-size: 5
|
initial-size: 5
|
||||||
max-size: 20
|
max-size: 20
|
||||||
@@ -12,10 +12,10 @@ spring:
|
|||||||
max-life-time: 30m
|
max-life-time: 30m
|
||||||
acquire-timeout: 3s
|
acquire-timeout: 3s
|
||||||
flyway:
|
flyway:
|
||||||
url: jdbc:postgresql://localhost:5432/manage_system
|
url: jdbc:postgresql://localhost:55432/manage_system
|
||||||
user: postgres
|
user: novalon
|
||||||
password: 123456
|
password: novalon123
|
||||||
enabled: false
|
enabled: true
|
||||||
locations: classpath:db/migration
|
locations: classpath:db/migration
|
||||||
baseline-on-migrate: true
|
baseline-on-migrate: true
|
||||||
validate-on-migrate: false
|
validate-on-migrate: false
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ spring:
|
|||||||
exclude:
|
exclude:
|
||||||
- org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
|
- org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
|
||||||
r2dbc:
|
r2dbc:
|
||||||
url: r2dbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:manage_system}
|
url: r2dbc:postgresql://${DB_HOST:localhost}:${DB_PORT:55432}/${DB_NAME:manage_system}
|
||||||
username: ${DB_USERNAME:postgres}
|
username: ${DB_USERNAME:novalon}
|
||||||
password: ${DB_PASSWORD:123456}
|
password: ${DB_PASSWORD:novalon123}
|
||||||
pool:
|
pool:
|
||||||
initial-size: 10
|
initial-size: 10
|
||||||
max-size: 50
|
max-size: 50
|
||||||
@@ -25,12 +25,12 @@ spring:
|
|||||||
max-life-time: 1h
|
max-life-time: 1h
|
||||||
acquire-timeout: 5s
|
acquire-timeout: 5s
|
||||||
datasource:
|
datasource:
|
||||||
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:manage_system}
|
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:55432}/${DB_NAME:manage_system}
|
||||||
username: ${DB_USERNAME:postgres}
|
username: ${DB_USERNAME:novalon}
|
||||||
password: ${DB_PASSWORD:123456}
|
password: ${DB_PASSWORD:novalon123}
|
||||||
driver-class-name: org.postgresql.Driver
|
driver-class-name: org.postgresql.Driver
|
||||||
flyway:
|
flyway:
|
||||||
enabled: false
|
enabled: true
|
||||||
locations: classpath:db/migration
|
locations: classpath:db/migration
|
||||||
baseline-on-migrate: true
|
baseline-on-migrate: true
|
||||||
baseline-version: 0
|
baseline-version: 0
|
||||||
|
|||||||
@@ -60,6 +60,10 @@
|
|||||||
<groupId>org.springframework.data</groupId>
|
<groupId>org.springframework.data</groupId>
|
||||||
<artifactId>spring-data-redis</artifactId>
|
<artifactId>spring-data-redis</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
+15
-2
@@ -1,5 +1,8 @@
|
|||||||
package cn.novalon.gym.manage.common.config;
|
package cn.novalon.gym.manage.common.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
|
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
|
||||||
@@ -24,13 +27,23 @@ public class RedisConfig {
|
|||||||
public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(
|
public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(
|
||||||
ReactiveRedisConnectionFactory connectionFactory) {
|
ReactiveRedisConnectionFactory connectionFactory) {
|
||||||
|
|
||||||
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
objectMapper.registerModule(new JavaTimeModule());
|
||||||
|
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||||
|
objectMapper.activateDefaultTyping(
|
||||||
|
objectMapper.getPolymorphicTypeValidator(),
|
||||||
|
ObjectMapper.DefaultTyping.NON_FINAL
|
||||||
|
);
|
||||||
|
|
||||||
|
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);
|
||||||
|
|
||||||
// 配置序列化上下文
|
// 配置序列化上下文
|
||||||
RedisSerializationContext<String, Object> serializationContext =
|
RedisSerializationContext<String, Object> serializationContext =
|
||||||
RedisSerializationContext.<String, Object>newSerializationContext()
|
RedisSerializationContext.<String, Object>newSerializationContext()
|
||||||
.key(StringRedisSerializer.UTF_8)
|
.key(StringRedisSerializer.UTF_8)
|
||||||
.value(new GenericJackson2JsonRedisSerializer())
|
.value(serializer)
|
||||||
.hashKey(StringRedisSerializer.UTF_8)
|
.hashKey(StringRedisSerializer.UTF_8)
|
||||||
.hashValue(new GenericJackson2JsonRedisSerializer())
|
.hashValue(serializer)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
|
return new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
|
||||||
|
|||||||
+93
-93
@@ -1,7 +1,7 @@
|
|||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- V13: 整合所有测试数据(基于 2026-06-16 17:13)
|
-- V13: 整合所有测试数据(基于 2026-06-29 17:13)
|
||||||
-- 说明: 系统初始数据由 V2 处理,本文件仅包含业务测试数据
|
-- 说明: 系统初始数据由 V2 处理,本文件仅包含业务测试数据
|
||||||
-- 所有时间相关字段已更新为基于 2026-06-16
|
-- 所有时间相关字段已更新为基于 2026-06-29
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
@@ -84,38 +84,38 @@ INSERT INTO member_card (member_card_name, member_card_type, member_card_price,
|
|||||||
|
|
||||||
-- E1: 数据统计测试会员(V14,显式 ID 1001-1012)
|
-- E1: 数据统计测试会员(V14,显式 ID 1001-1012)
|
||||||
INSERT INTO member_user (id, member_no, nickname, phone, created_at, updated_at, is_deleted) VALUES
|
INSERT INTO member_user (id, member_no, nickname, phone, created_at, updated_at, is_deleted) VALUES
|
||||||
(1001, 'M20260616001', '张三', '13800138001', '2026-06-16 08:00:00', '2026-06-16 08:00:00', false),
|
(1001, 'M20260629001', '张三', '13800138001', '2026-06-29 08:00:00', '2026-06-29 08:00:00', false),
|
||||||
(1002, 'M20260616002', '李四', '13800138002', '2026-06-16 09:00:00', '2026-06-16 09:00:00', false),
|
(1002, 'M20260629002', '李四', '13800138002', '2026-06-29 09:00:00', '2026-06-29 09:00:00', false),
|
||||||
(1003, 'M20260615003', '王五', '13800138003', '2026-06-15 10:00:00', '2026-06-15 10:00:00', false),
|
(1003, 'M20260628003', '王五', '13800138003', '2026-06-28 10:00:00', '2026-06-28 10:00:00', false),
|
||||||
(1004, 'M20260614004', '赵六', '13800138004', '2026-06-14 11:00:00', '2026-06-14 11:00:00', false),
|
(1004, 'M20260627004', '赵六', '13800138004', '2026-06-27 11:00:00', '2026-06-27 11:00:00', false),
|
||||||
(1005, 'M20260616005', '钱七', '13800138005', '2026-06-16 08:00:00', '2026-06-16 08:00:00', false),
|
(1005, 'M20260629005', '钱七', '13800138005', '2026-06-29 08:00:00', '2026-06-29 08:00:00', false),
|
||||||
(1006, 'M20260616006', '孙八', '13800138006', '2026-06-16 09:00:00', '2026-06-16 09:00:00', false),
|
(1006, 'M20260629006', '孙八', '13800138006', '2026-06-29 09:00:00', '2026-06-29 09:00:00', false),
|
||||||
(1007, 'M20260616007', '周九', '13800138007', '2026-06-16 10:00:00', '2026-06-16 10:00:00', false),
|
(1007, 'M20260629007', '周九', '13800138007', '2026-06-29 10:00:00', '2026-06-29 10:00:00', false),
|
||||||
(1008, 'M20260613008', '吴十', '13800138008', '2026-06-13 14:00:00', '2026-06-13 14:00:00', false),
|
(1008, 'M20260626008', '吴十', '13800138008', '2026-06-26 14:00:00', '2026-06-26 14:00:00', false),
|
||||||
(1009, 'M20260612009', '郑十一', '13800138009', '2026-06-12 15:00:00', '2026-06-12 15:00:00', false),
|
(1009, 'M20260625009', '郑十一', '13800138009', '2026-06-25 15:00:00', '2026-06-25 15:00:00', false),
|
||||||
(1010, 'M20260611010', '王十二', '13800138010', '2026-06-11 16:00:00', '2026-06-11 16:00:00', false),
|
(1010, 'M20260624010', '王十二', '13800138010', '2026-06-24 16:00:00', '2026-06-24 16:00:00', false),
|
||||||
(1011, 'M20260610011', '陈十三', '13800138011', '2026-06-10 17:00:00', '2026-06-10 17:00:00', false),
|
(1011, 'M20260623011', '陈十三', '13800138011', '2026-06-23 17:00:00', '2026-06-23 17:00:00', false),
|
||||||
(1012, 'M20260609012', '刘十四', '13800138012', '2026-06-09 18:00:00', '2026-06-09 18:00:00', false);
|
(1012, 'M20260622012', '刘十四', '13800138012', '2026-06-22 18:00:00', '2026-06-22 18:00:00', false);
|
||||||
|
|
||||||
-- E2: 预约场景测试会员(V10: A-G)
|
-- E2: 预约场景测试会员(V10: A-G)
|
||||||
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
||||||
('MEM_TEST_A', '用户A_无卡新用户', '13800001001', 1, false, '2026-06-16 10:00:00', '2026-06-16 10:00:00'),
|
('MEM_TEST_A', '用户A_无卡新用户', '13800001001', 1, false, '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
('MEM_TEST_B', '用户B_过期时长卡', '13800001002', 1, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_B', '用户B_过期时长卡', '13800001002', 1, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_C', '会员C_有效时长卡', '13800001003', 2, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_C', '会员C_有效时长卡', '13800001003', 2, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_D', '会员D_次数用尽', '13800001004', 1, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_D', '会员D_次数用尽', '13800001004', 1, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_E', '会员E_次数充足', '13800001005', 2, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_E', '会员E_次数充足', '13800001005', 2, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_F', '会员F_储值卡余额不足', '13800001006', 1, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_F', '会员F_储值卡余额不足', '13800001006', 1, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_G', '会员G_储值卡余额充足', '13800001007', 2, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00');
|
('MEM_TEST_G', '会员G_储值卡余额充足', '13800001007', 2, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00');
|
||||||
|
|
||||||
-- E3: 取消预约测试会员(V11: 张三/李四/王五)
|
-- E3: 取消预约测试会员(V11: 张三/李四/王五)
|
||||||
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
||||||
('MEM_TEST_ZHANG', '张三_时长卡用户', '13800002001', 1, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_ZHANG', '张三_时长卡用户', '13800002001', 1, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_LI', '李四_次数卡用户', '13800002002', 1, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00'),
|
('MEM_TEST_LI', '李四_次数卡用户', '13800002002', 1, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00'),
|
||||||
('MEM_TEST_WANG', '王五_储值卡用户', '13800002003', 2, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00');
|
('MEM_TEST_WANG', '王五_储值卡用户', '13800002003', 2, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00');
|
||||||
|
|
||||||
-- E4: 时间冲突测试会员(V12)
|
-- E4: 时间冲突测试会员(V12)
|
||||||
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
||||||
('MEM_TIME_CONFLICT', '时间冲突测试会员', '13800009999', 1, false, '2026-06-15 10:00:00', '2026-06-15 10:00:00');
|
('MEM_TIME_CONFLICT', '时间冲突测试会员', '13800009999', 1, false, '2026-06-28 10:00:00', '2026-06-28 10:00:00');
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- Section F: 会员卡记录
|
-- Section F: 会员卡记录
|
||||||
@@ -123,67 +123,67 @@ INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created
|
|||||||
|
|
||||||
-- F1: V10 预约场景 - 6条会员卡记录
|
-- F1: V10 预约场景 - 6条会员卡记录
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_B'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'EXPIRED', 0, 0.00, '2026-06-15 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_B'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'EXPIRED', 0, 0.00, '2026-06-28 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_C'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'ACTIVE', 0, 0.00, '2026-07-16 23:59:59', '2026-06-16 10:00:00', 0, '{}', '2026-06-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_C'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'ACTIVE', 0, 0.00, '2026-07-29 23:59:59', '2026-06-29 10:00:00', 0, '{}', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_D'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 0, 0.00, '2026-12-31 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_D'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 0, 0.00, '2026-12-31 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_E'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 5, 0.00, '2026-12-31 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_E'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 5, 0.00, '2026-12-31 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_F'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 30.00, '2027-06-16 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_F'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 30.00, '2027-06-29 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_G'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 200.00, '2027-06-16 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_G'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 200.00, '2027-06-29 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- F2: V11 取消预约场景 - 3条
|
-- F2: V11 取消预约场景 - 3条
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_ZHANG'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'ACTIVE', 0, 0.00, '2026-07-16 23:59:59', '2026-06-16 10:00:00', 0, '{}', '2026-06-16 10:00:00', '2026-06-16 10:00:00'),
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_ZHANG'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'ACTIVE', 0, 0.00, '2026-07-29 23:59:59', '2026-06-29 10:00:00', 0, '{}', '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_LI'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 5, 0.00, '2026-12-31 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00'),
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_LI'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 5, 0.00, '2026-12-31 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_WANG'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 200.00, '2027-06-16 23:59:59', '2026-05-16 10:00:00', 0, '{}', '2026-05-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_WANG'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 200.00, '2027-06-29 23:59:59', '2026-05-29 10:00:00', 0, '{}', '2026-05-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- F3: V12 时间冲突场景 - 1条
|
-- F3: V12 时间冲突场景 - 1条
|
||||||
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM member_user WHERE member_no = 'MEM_TIME_CONFLICT'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 10, 0.00, '2026-12-31 23:59:59', '2026-06-16 10:00:00', 0, '{}', '2026-06-16 10:00:00', '2026-06-16 10:00:00');
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TIME_CONFLICT'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 10, 0.00, '2026-12-31 23:59:59', '2026-06-29 10:00:00', 0, '{}', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- Section G: 团课课程(来源 V7 / V10 / V11 / V12 / V14,基于 2026-06-24)
|
-- Section G: 团课课程(来源 V7 / V10 / V11 / V12 / V14,基于 2026-06-29)
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
|
|
||||||
-- G1: V7 - 7种场景团课
|
-- G1: V7 - 7种场景团课
|
||||||
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
||||||
('极速燃脂单车', 104, 2, '2026-06-25 16:45:00', '2026-06-25 20:20:00', 25, 0, 0, '单车房', '/images/spinning.jpg', '跟随音乐节奏变换阻力和速度,体验爬坡与冲刺的快感。', 50.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00'),
|
('极速燃脂单车', 104, 2, '2026-06-30 16:45:00', '2026-06-30 20:20:00', 25, 0, 0, '单车房', '/images/spinning.jpg', '跟随音乐节奏变换阻力和速度,体验爬坡与冲刺的快感。', 50.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
('清晨流瑜伽', 101, 1, '2026-06-28 09:00:00', '2026-06-28 10:30:00', 15, 5, 0, 'A座3楼瑜伽教室', '/images/yoga_flow.jpg', '适合有一定基础的学员,通过流畅的体式连接呼吸。', 50.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00'),
|
('清晨流瑜伽', 101, 1, '2026-07-03 09:00:00', '2026-07-03 10:30:00', 15, 5, 0, 'A座3楼瑜伽教室', '/images/yoga_flow.jpg', '适合有一定基础的学员,通过流畅的体式连接呼吸。', 50.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
('燃脂搏击', 102, 2, '2026-06-26 18:30:00', '2026-06-26 19:30:00', 20, 20, 0, '综合训练区', '/images/kickboxing.jpg', '高强度间歇训练,名额已满。', 50.00, 'coach_zhang', '2026-06-24 14:30:00', '2026-06-24 14:30:00'),
|
('燃脂搏击', 102, 2, '2026-07-01 18:30:00', '2026-07-01 19:30:00', 20, 20, 0, '综合训练区', '/images/kickboxing.jpg', '高强度间歇训练,名额已满。', 50.00, 'coach_zhang', '2026-06-29 14:30:00', '2026-06-29 14:30:00'),
|
||||||
('哈他瑜伽', 101, 1, '2026-06-24 17:45:00', '2026-06-24 18:50:00', 12, 3, 0, '瑜伽教室B', '/images/hatha_yoga.jpg', '基础哈他瑜伽,距开始不足30分钟,已停止预约。', 50.00, 'coach_li', '2026-06-24 08:00:00', '2026-06-24 08:00:00'),
|
('哈他瑜伽', 101, 1, '2026-06-29 17:45:00', '2026-06-29 18:50:00', 12, 3, 0, '瑜伽教室B', '/images/hatha_yoga.jpg', '基础哈他瑜伽,距开始不足30分钟,已停止预约。', 50.00, 'coach_li', '2026-06-29 08:00:00', '2026-06-29 08:00:00'),
|
||||||
('周末冥想修复', 101, 1, '2026-07-06 15:00:00', '2026-07-06 16:00:00', 12, 3, 1, '冥想室', '/images/meditation.jpg', '通过呼吸和正念冥想,该课程已被取消。', 50.00, 'coach_wang', '2026-06-24 08:00:00', '2026-06-24 08:00:00'),
|
('周末冥想修复', 101, 1, '2026-07-11 15:00:00', '2026-07-11 16:00:00', 12, 3, 1, '冥想室', '/images/meditation.jpg', '通过呼吸和正念冥想,该课程已被取消。', 50.00, 'coach_wang', '2026-06-29 08:00:00', '2026-06-29 08:00:00'),
|
||||||
('蜜桃臀塑造', 103, 3, '2026-06-18 19:00:00', '2026-06-18 20:00:00', 10, 8, 2, '私教专区', '/images/glute.jpg', '针对性训练臀部肌肉群,课程已结束。', 50.00, 'coach_li', '2026-06-18 09:15:00', '2026-06-18 09:15:00'),
|
('蜜桃臀塑造', 103, 3, '2026-06-23 19:00:00', '2026-06-23 20:00:00', 10, 8, 2, '私教专区', '/images/glute.jpg', '针对性训练臀部肌肉群,课程已结束。', 50.00, 'coach_li', '2026-06-23 09:15:00', '2026-06-23 09:15:00'),
|
||||||
('午间冥想放松', 101, 1, '2026-06-20 12:00:00', '2026-06-20 13:00:00', 15, 6, 2, '冥想室', '/images/meditation_noon.jpg', '午间冥想课程,已结束。', 50.00, 'admin', '2026-06-20 09:00:00', '2026-06-20 09:00:00');
|
('午间冥想放松', 101, 1, '2026-06-25 12:00:00', '2026-06-25 13:00:00', 15, 6, 2, '冥想室', '/images/meditation_noon.jpg', '午间冥想课程,已结束。', 50.00, 'admin', '2026-06-25 09:00:00', '2026-06-25 09:00:00');
|
||||||
|
|
||||||
-- G2: V10 预约场景(已取消次数卡支付,仅保留储值卡)
|
-- G2: V10 预约场景(已取消次数卡支付,仅保留储值卡)
|
||||||
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
||||||
('燃脂搏击_储值测试', 102, 2, '2026-06-26 19:30:00', '2026-06-26 20:30:00', 20, 0, 0, '综合训练区', '消耗储值50元', 50.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00'),
|
('燃脂搏击_储值测试', 102, 2, '2026-07-01 19:30:00', '2026-07-01 20:30:00', 20, 0, 0, '综合训练区', '消耗储值50元', 50.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
('高端普拉提_储值卡课程', 103, 1, '2026-06-27 19:00:00', '2026-06-27 20:00:00', 15, 0, 0, '普拉提教室', '消耗储值20元', 20.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00');
|
('高端普拉提_储值卡课程', 103, 1, '2026-07-02 19:00:00', '2026-07-02 20:00:00', 15, 0, 0, '普拉提教室', '消耗储值20元', 20.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- G3: V11 取消预约场景
|
-- G3: V11 取消预约场景
|
||||||
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
||||||
('晚间瑜伽_取消测试', 101, 1, '2026-06-27 19:00:00', '2026-06-27 20:00:00', 20, 0, 0, '瑜伽教室', '用于测试取消预约功能', 30.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00');
|
('晚间瑜伽_取消测试', 101, 1, '2026-07-02 19:00:00', '2026-07-02 20:00:00', 20, 0, 0, '瑜伽教室', '用于测试取消预约功能', 30.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- G4: V12 时间冲突场景
|
-- G4: V12 时间冲突场景
|
||||||
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, stored_value_amount, create_by, created_at, updated_at) VALUES
|
||||||
('时间冲突测试_A_13点-15点', 102, 2, '2026-06-26 13:00:00', '2026-06-26 15:00:00', 20, 0, 0, '综合训练区', '测试用团课A', 50.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00'),
|
('时间冲突测试_A_13点-15点', 102, 2, '2026-07-01 13:00:00', '2026-07-01 15:00:00', 20, 0, 0, '综合训练区', '测试用团课A', 50.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
('时间冲突测试_B_14点-16点', 103, 1, '2026-06-26 14:00:00', '2026-06-26 16:00:00', 15, 0, 0, '普拉提教室', '与团课A时间重叠', 50.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00'),
|
('时间冲突测试_B_14点-16点', 103, 1, '2026-07-01 14:00:00', '2026-07-01 16:00:00', 15, 0, 0, '普拉提教室', '与团课A时间重叠', 50.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
('时间冲突测试_C_10点-12点', 101, 1, '2026-06-26 10:00:00', '2026-06-26 12:00:00', 15, 0, 0, '瑜伽教室', '与A/B不冲突', 50.00, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00');
|
('时间冲突测试_C_10点-12点', 101, 1, '2026-07-01 10:00:00', '2026-07-01 12:00:00', 15, 0, 0, '瑜伽教室', '与A/B不冲突', 50.00, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- G5: V14 数据统计场景(今天 2026-06-24)
|
-- G5: V14 数据统计场景(今天 2026-06-29)
|
||||||
INSERT INTO group_course (id, course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, created_at, updated_at) VALUES
|
INSERT INTO group_course (id, course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, cover_image, description, stored_value_amount, created_at, updated_at) VALUES
|
||||||
(3001, '瑜伽入门', 1, 1, '2026-06-24 08:00:00', '2026-06-24 09:00:00', 20, 15, 0, '健身房A区', 'https://example.com/yoga.jpg', '适合初学者的瑜伽课程', 50.00, '2026-06-24 10:00:00', '2026-06-24 10:00:00'),
|
(3001, '瑜伽入门', 1, 1, '2026-06-29 08:00:00', '2026-06-29 09:00:00', 20, 15, 0, '健身房A区', 'https://example.com/yoga.jpg', '适合初学者的瑜伽课程', 50.00, '2026-06-29 10:00:00', '2026-06-29 10:00:00'),
|
||||||
(3002, '动感单车', 2, 2, '2026-06-24 09:30:00', '2026-06-24 10:30:00', 25, 20, 0, '健身房B区', 'https://example.com/spinning.jpg', '高强度有氧运动', 50.00, '2026-06-24 11:00:00', '2026-06-24 11:00:00'),
|
(3002, '动感单车', 2, 2, '2026-06-29 09:30:00', '2026-06-29 10:30:00', 25, 20, 0, '健身房B区', 'https://example.com/spinning.jpg', '高强度有氧运动', 50.00, '2026-06-29 11:00:00', '2026-06-29 11:00:00'),
|
||||||
(3003, '普拉提', 3, 1, '2026-06-24 14:00:00', '2026-06-24 15:00:00', 15, 10, 0, '健身房C区', 'https://example.com/pilates.jpg', '核心力量训练', 50.00, '2026-06-24 12:00:00', '2026-06-24 12:00:00');
|
(3003, '普拉提', 3, 1, '2026-06-29 14:00:00', '2026-06-29 15:00:00', 15, 10, 0, '健身房C区', 'https://example.com/pilates.jpg', '核心力量训练', 50.00, '2026-06-29 12:00:00', '2026-06-29 12:00:00');
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- Section H: 团课预约记录
|
-- Section H: 团课预约记录
|
||||||
@@ -191,26 +191,26 @@ INSERT INTO group_course (id, course_name, coach_id, course_type, start_time, en
|
|||||||
|
|
||||||
-- H1: V11 取消预约测试
|
-- H1: V11 取消预约测试
|
||||||
INSERT INTO group_course_booking (course_id, member_id, member_card_id, booking_time, status, course_name, course_start_time, course_end_time, location, created_at, updated_at) VALUES
|
INSERT INTO group_course_booking (course_id, member_id, member_card_id, booking_time, status, course_name, course_start_time, course_end_time, location, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '晚间瑜伽_取消测试'), (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_ZHANG'), (SELECT id FROM member_card_record WHERE member_id = (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_ZHANG')), '2026-06-24 11:00:00', '0', '晚间瑜伽_取消测试', '2026-06-27 19:00:00', '2026-06-27 20:00:00', '瑜伽教室', '2026-06-24 11:00:00', '2026-06-24 11:00:00'),
|
((SELECT id FROM group_course WHERE course_name = '晚间瑜伽_取消测试'), (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_ZHANG'), (SELECT id FROM member_card_record WHERE member_id = (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_ZHANG')), '2026-06-29 11:00:00', '0', '晚间瑜伽_取消测试', '2026-07-02 19:00:00', '2026-07-02 20:00:00', '瑜伽教室', '2026-06-29 11:00:00', '2026-06-29 11:00:00'),
|
||||||
((SELECT id FROM group_course WHERE course_name = '晚间瑜伽_取消测试'), (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_LI'), (SELECT id FROM member_card_record WHERE member_id = (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_LI')), '2026-06-24 11:30:00', '0', '晚间瑜伽_取消测试', '2026-06-27 19:00:00', '2026-06-27 20:00:00', '瑜伽教室', '2026-06-24 11:30:00', '2026-06-24 11:30:00'),
|
((SELECT id FROM group_course WHERE course_name = '晚间瑜伽_取消测试'), (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_LI'), (SELECT id FROM member_card_record WHERE member_id = (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_LI')), '2026-06-29 11:30:00', '0', '晚间瑜伽_取消测试', '2026-07-02 19:00:00', '2026-07-02 20:00:00', '瑜伽教室', '2026-06-29 11:30:00', '2026-06-29 11:30:00'),
|
||||||
((SELECT id FROM group_course WHERE course_name = '晚间瑜伽_取消测试'), (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_WANG'), (SELECT id FROM member_card_record WHERE member_id = (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_WANG')), '2026-06-24 12:00:00', '0', '晚间瑜伽_取消测试', '2026-06-27 19:00:00', '2026-06-27 20:00:00', '瑜伽教室', '2026-06-24 12:00:00', '2026-06-24 12:00:00');
|
((SELECT id FROM group_course WHERE course_name = '晚间瑜伽_取消测试'), (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_WANG'), (SELECT id FROM member_card_record WHERE member_id = (SELECT id FROM member_user WHERE member_no = 'MEM_TEST_WANG')), '2026-06-29 12:00:00', '0', '晚间瑜伽_取消测试', '2026-07-02 19:00:00', '2026-07-02 20:00:00', '瑜伽教室', '2026-06-29 12:00:00', '2026-06-29 12:00:00');
|
||||||
|
|
||||||
UPDATE group_course SET current_members = current_members + 3 WHERE course_name = '晚间瑜伽_取消测试';
|
UPDATE group_course SET current_members = current_members + 3 WHERE course_name = '晚间瑜伽_取消测试';
|
||||||
|
|
||||||
-- H2: V14 数据统计预约 - 今天(6月24日)
|
-- H2: V14 数据统计预约 - 今天(6月24日)
|
||||||
INSERT INTO group_course_booking (id, member_id, member_card_id, course_id, booking_time, status, created_at, updated_at) VALUES
|
INSERT INTO group_course_booking (id, member_id, member_card_id, course_id, booking_time, status, created_at, updated_at) VALUES
|
||||||
(4001, 1001, 1, 3001, '2026-06-24 08:00:00', '2', '2026-06-23 20:00:00', '2026-06-24 08:30:00'),
|
(4001, 1001, 1, 3001, '2026-06-29 08:00:00', '2', '2026-06-23 20:00:00', '2026-06-29 08:30:00'),
|
||||||
(4002, 1002, 2, 3001, '2026-06-24 08:00:00', '2', '2026-06-23 21:00:00', '2026-06-24 08:30:00'),
|
(4002, 1002, 2, 3001, '2026-06-29 08:00:00', '2', '2026-06-23 21:00:00', '2026-06-29 08:30:00'),
|
||||||
(4003, 1003, 3, 3001, '2026-06-24 08:00:00', '3', '2026-06-23 22:00:00', '2026-06-24 09:00:00'),
|
(4003, 1003, 3, 3001, '2026-06-29 08:00:00', '3', '2026-06-23 22:00:00', '2026-06-29 09:00:00'),
|
||||||
(4004, 1004, 4, 3002, '2026-06-24 09:30:00', '2', '2026-06-23 19:00:00', '2026-06-24 09:30:00'),
|
(4004, 1004, 4, 3002, '2026-06-29 09:30:00', '2', '2026-06-23 19:00:00', '2026-06-29 09:30:00'),
|
||||||
(4005, 1005, 5, 3002, '2026-06-24 09:30:00', '1', '2026-06-23 20:30:00', '2026-06-24 09:00:00'),
|
(4005, 1005, 5, 3002, '2026-06-29 09:30:00', '1', '2026-06-23 20:30:00', '2026-06-29 09:00:00'),
|
||||||
(4006, 1006, 6, 3002, '2026-06-24 09:30:00', '2', '2026-06-23 21:30:00', '2026-06-24 09:30:00'),
|
(4006, 1006, 6, 3002, '2026-06-29 09:30:00', '2', '2026-06-23 21:30:00', '2026-06-29 09:30:00'),
|
||||||
(4007, 1007, 7, 3003, '2026-06-24 14:00:00', '2', '2026-06-23 22:30:00', '2026-06-24 14:00:00'),
|
(4007, 1007, 7, 3003, '2026-06-29 14:00:00', '2', '2026-06-23 22:30:00', '2026-06-29 14:00:00'),
|
||||||
(4008, 1008, 8, 3003, '2026-06-24 14:00:00', '3', '2026-06-24 08:00:00', '2026-06-24 14:00:00'),
|
(4008, 1008, 8, 3003, '2026-06-29 14:00:00', '3', '2026-06-29 08:00:00', '2026-06-29 14:00:00'),
|
||||||
(4009, 1009, 9, 3003, '2026-06-24 14:00:00', '2', '2026-06-24 09:00:00', '2026-06-24 14:00:00'),
|
(4009, 1009, 9, 3003, '2026-06-29 14:00:00', '2', '2026-06-29 09:00:00', '2026-06-29 14:00:00'),
|
||||||
(4010, 1010, 10, 3001, '2026-06-24 08:00:00', '2', '2026-06-24 07:00:00', '2026-06-24 08:00:00'),
|
(4010, 1010, 10, 3001, '2026-06-29 08:00:00', '2', '2026-06-29 07:00:00', '2026-06-29 08:00:00'),
|
||||||
(4011, 1011, 11, 3002, '2026-06-24 09:30:00', '1', '2026-06-24 08:30:00', '2026-06-24 09:00:00'),
|
(4011, 1011, 11, 3002, '2026-06-29 09:30:00', '1', '2026-06-29 08:30:00', '2026-06-29 09:00:00'),
|
||||||
(4012, 1012, 12, 3003, '2026-06-24 14:00:00', '2', '2026-06-24 10:00:00', '2026-06-24 14:00:00');
|
(4012, 1012, 12, 3003, '2026-06-29 14:00:00', '2', '2026-06-29 10:00:00', '2026-06-29 14:00:00');
|
||||||
|
|
||||||
-- H3: V14 数据统计预约 - 昨天(6月23日)
|
-- H3: V14 数据统计预约 - 昨天(6月23日)
|
||||||
INSERT INTO group_course_booking (id, member_id, member_card_id, course_id, booking_time, status, created_at, updated_at) VALUES
|
INSERT INTO group_course_booking (id, member_id, member_card_id, course_id, booking_time, status, created_at, updated_at) VALUES
|
||||||
@@ -229,22 +229,22 @@ INSERT INTO group_course_booking (id, member_id, member_card_id, course_id, book
|
|||||||
(4022, 1004, 4, 3003, '2026-06-22 14:00:00', '3', '2026-06-21 19:00:00', '2026-06-22 14:00:00');
|
(4022, 1004, 4, 3003, '2026-06-22 14:00:00', '3', '2026-06-21 19:00:00', '2026-06-22 14:00:00');
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- Section I: 签到记录(来源 V14,基于 2026-06-24)
|
-- Section I: 签到记录(来源 V14,基于 2026-06-29)
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
|
|
||||||
INSERT INTO sign_in_record (id, member_id, sign_in_time, sign_in_type, sign_in_status, source, is_delete) VALUES
|
INSERT INTO sign_in_record (id, member_id, sign_in_time, sign_in_type, sign_in_status, source, is_delete) VALUES
|
||||||
(2001, 1001, '2026-06-24 08:00:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2001, 1001, '2026-06-29 08:00:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2002, 1002, '2026-06-24 08:15:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false),
|
(2002, 1002, '2026-06-29 08:15:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false),
|
||||||
(2003, 1003, '2026-06-24 08:30:00', 'FACE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2003, 1003, '2026-06-29 08:30:00', 'FACE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2004, 1004, '2026-06-24 09:00:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2004, 1004, '2026-06-29 09:00:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2005, 1005, '2026-06-24 09:15:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false),
|
(2005, 1005, '2026-06-29 09:15:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false),
|
||||||
(2006, 1006, '2026-06-24 09:30:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2006, 1006, '2026-06-29 09:30:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2007, 1007, '2026-06-24 10:00:00', 'FACE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2007, 1007, '2026-06-29 10:00:00', 'FACE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2008, 1008, '2026-06-24 10:15:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2008, 1008, '2026-06-29 10:15:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2009, 1009, '2026-06-24 10:30:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false),
|
(2009, 1009, '2026-06-29 10:30:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false),
|
||||||
(2010, 1010, '2026-06-24 11:00:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2010, 1010, '2026-06-29 11:00:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
(2011, 1011, '2026-06-24 11:15:00', 'FACE', 'FAIL', 'MINI_PROGRAM', false),
|
(2011, 1011, '2026-06-29 11:15:00', 'FACE', 'FAIL', 'MINI_PROGRAM', false),
|
||||||
(2012, 1012, '2026-06-24 11:30:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false);
|
(2012, 1012, '2026-06-29 11:30:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false);
|
||||||
|
|
||||||
INSERT INTO sign_in_record (id, member_id, sign_in_time, sign_in_type, sign_in_status, source, is_delete) VALUES
|
INSERT INTO sign_in_record (id, member_id, sign_in_time, sign_in_type, sign_in_status, source, is_delete) VALUES
|
||||||
(2013, 1001, '2026-06-23 07:30:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
(2013, 1001, '2026-06-23 07:30:00', 'QR_CODE', 'SUCCESS', 'MINI_PROGRAM', false),
|
||||||
@@ -264,43 +264,43 @@ INSERT INTO sign_in_record (id, member_id, sign_in_time, sign_in_type, sign_in_s
|
|||||||
(2025, 1005, '2026-06-22 09:00:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false);
|
(2025, 1005, '2026-06-22 09:00:00', 'MANUAL', 'SUCCESS', 'PC_BACKEND', false);
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- Section J: 团课推荐测试数据(来源 V18,基于 2026-06-24)
|
-- Section J: 团课推荐测试数据(来源 V18,基于 2026-06-29)
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '极速燃脂单车'), '本周热门推荐', '极速燃脂单车课程,跟随音乐节奏变换阻力和速度,体验爬坡与冲刺的快感,一节课消耗800大卡!', '教练专业,课程内容丰富,深受学员喜爱,燃脂效果显著', 20, true, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00');
|
((SELECT id FROM group_course WHERE course_name = '极速燃脂单车'), '本周热门推荐', '极速燃脂单车课程,跟随音乐节奏变换阻力和速度,体验爬坡与冲刺的快感,一节课消耗800大卡!', '教练专业,课程内容丰富,深受学员喜爱,燃脂效果显著', 20, true, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '清晨流瑜伽'), '新手友好推荐', '清晨流瑜伽课程,适合有一定基础的学员,通过流畅的体式连接呼吸,唤醒身体能量。', '适合新手入门,教练耐心指导,课程节奏适中', 15, true, 'admin', '2026-06-24 11:00:00', '2026-06-24 11:00:00');
|
((SELECT id FROM group_course WHERE course_name = '清晨流瑜伽'), '新手友好推荐', '清晨流瑜伽课程,适合有一定基础的学员,通过流畅的体式连接呼吸,唤醒身体能量。', '适合新手入门,教练耐心指导,课程节奏适中', 15, true, 'admin', '2026-06-29 11:00:00', '2026-06-29 11:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '燃脂搏击'), '高强度燃脂', '燃脂搏击课程,高强度间歇训练,配合音乐快速燃脂,释放压力。', '高强度训练,适合进阶学员,快速燃脂塑形', 10, false, 'admin', '2026-06-24 12:00:00', '2026-06-24 12:00:00');
|
((SELECT id FROM group_course WHERE course_name = '燃脂搏击'), '高强度燃脂', '燃脂搏击课程,高强度间歇训练,配合音乐快速燃脂,释放压力。', '高强度训练,适合进阶学员,快速燃脂塑形', 10, false, 'admin', '2026-06-29 12:00:00', '2026-06-29 12:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '哈他瑜伽'), '基础瑜伽推荐', '基础哈他瑜伽课程,适合所有级别学员,通过基础体式练习提升身体柔韧性和平衡能力。', '零基础友好,适合所有健身水平,放松身心', 12, true, 'coach_li', '2026-06-24 13:00:00', '2026-06-24 13:00:00');
|
((SELECT id FROM group_course WHERE course_name = '哈他瑜伽'), '基础瑜伽推荐', '基础哈他瑜伽课程,适合所有级别学员,通过基础体式练习提升身体柔韧性和平衡能力。', '零基础友好,适合所有健身水平,放松身心', 12, true, 'coach_li', '2026-06-29 13:00:00', '2026-06-29 13:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '蜜桃臀塑造'), '塑形热门课程', '蜜桃臀塑造课程,针对性训练臀部肌肉群,打造完美曲线。', '专业私教指导,动作标准,效果显著,深受女性学员喜爱', 18, true, 'coach_li', '2026-06-24 09:15:00', '2026-06-24 09:15:00');
|
((SELECT id FROM group_course WHERE course_name = '蜜桃臀塑造'), '塑形热门课程', '蜜桃臀塑造课程,针对性训练臀部肌肉群,打造完美曲线。', '专业私教指导,动作标准,效果显著,深受女性学员喜爱', 18, true, 'coach_li', '2026-06-29 09:15:00', '2026-06-29 09:15:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '午间冥想放松'), '午间放松推荐', '午间冥想放松课程,通过呼吸和正念冥想,深度放松身心,缓解工作压力。', '适合上班族,午间放松充电,提升下午工作效率', 8, true, 'admin', '2026-06-24 09:00:00', '2026-06-24 09:00:00');
|
((SELECT id FROM group_course WHERE course_name = '午间冥想放松'), '午间放松推荐', '午间冥想放松课程,通过呼吸和正念冥想,深度放松身心,缓解工作压力。', '适合上班族,午间放松充电,提升下午工作效率', 8, true, 'admin', '2026-06-29 09:00:00', '2026-06-29 09:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '极速燃脂单车'), '减脂首选课程', '想要快速减脂?极速燃脂单车是你的最佳选择!专业教练带领,科学训练计划。', '减脂效果最佳,课程强度适中,适合想要快速瘦身的学员', 16, true, 'coach_zhang', '2026-06-24 14:00:00', '2026-06-24 14:00:00');
|
((SELECT id FROM group_course WHERE course_name = '极速燃脂单车'), '减脂首选课程', '想要快速减脂?极速燃脂单车是你的最佳选择!专业教练带领,科学训练计划。', '减脂效果最佳,课程强度适中,适合想要快速瘦身的学员', 16, true, 'coach_zhang', '2026-06-29 14:00:00', '2026-06-29 14:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '清晨流瑜伽'), '晨练优选', '清晨流瑜伽,唤醒身体能量,开启活力一天!适合晨练爱好者。', '晨练最佳选择,提升身体活力,改善精神状态', 14, true, 'coach_wang', '2026-06-24 15:00:00', '2026-06-24 15:00:00');
|
((SELECT id FROM group_course WHERE course_name = '清晨流瑜伽'), '晨练优选', '清晨流瑜伽,唤醒身体能量,开启活力一天!适合晨练爱好者。', '晨练最佳选择,提升身体活力,改善精神状态', 14, true, 'coach_wang', '2026-06-29 15:00:00', '2026-06-29 15:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '哈他瑜伽'), '身心平衡推荐', '哈他瑜伽课程,通过体式练习和呼吸控制,达到身心平衡,提升整体健康水平。', '改善身体柔韧性,增强核心力量,提升身体协调性', 11, true, 'coach_li', '2026-06-24 16:00:00', '2026-06-24 16:00:00');
|
((SELECT id FROM group_course WHERE course_name = '哈他瑜伽'), '身心平衡推荐', '哈他瑜伽课程,通过体式练习和呼吸控制,达到身心平衡,提升整体健康水平。', '改善身体柔韧性,增强核心力量,提升身体协调性', 11, true, 'coach_li', '2026-06-29 16:00:00', '2026-06-29 16:00:00');
|
||||||
|
|
||||||
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
INSERT INTO group_course_recommend (course_id, recommend_title, recommend_content, recommend_reason, priority, is_active, create_by, created_at, updated_at) VALUES
|
||||||
((SELECT id FROM group_course WHERE course_name = '午间冥想放松'), '职场减压课程', '午间冥想放松,专为职场人士设计,快速缓解工作压力,提升工作状态。', '职场减压首选,课程时间短,效果显著', 9, false, 'admin', '2026-06-24 10:00:00', '2026-06-24 10:00:00');
|
((SELECT id FROM group_course WHERE course_name = '午间冥想放松'), '职场减压课程', '午间冥想放松,专为职场人士设计,快速缓解工作压力,提升工作状态。', '职场减压首选,课程时间短,效果显著', 9, false, 'admin', '2026-06-29 10:00:00', '2026-06-29 10:00:00');
|
||||||
|
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- Section K: 统计说明
|
-- Section K: 统计说明
|
||||||
-- ============================================================
|
-- ============================================================
|
||||||
-- 今日(2026-06-24)统计预期:
|
-- 今日(2026-06-29)统计预期:
|
||||||
-- 新增会员: 3 (1005, 1006, 1007)
|
-- 新增会员: 3 (1005, 1006, 1007)
|
||||||
-- 签到会员: 12
|
-- 签到会员: 12
|
||||||
-- 预约总数: 12 (4001-4012),取消: 2,出席: 8,缺席: 2
|
-- 预约总数: 12 (4001-4012),取消: 2,出席: 8,缺席: 2
|
||||||
|
|||||||
+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 '删除时间(软删除)';
|
||||||
+2
-1
@@ -218,7 +218,8 @@ VALUES
|
|||||||
('主框架页-默认皮肤样式名称', 'sys.index.skinName', 'skin-blue', 'Y', 'system', 'system', NOW(), NOW()),
|
('主框架页-默认皮肤样式名称', 'sys.index.skinName', 'skin-blue', 'Y', 'system', 'system', NOW(), NOW()),
|
||||||
('用户自助-验证码开关', 'sys.account.captchaEnabled', 'true', 'Y', 'system', 'system', NOW(), NOW()),
|
('用户自助-验证码开关', 'sys.account.captchaEnabled', 'true', 'Y', 'system', 'system', NOW(), NOW()),
|
||||||
('用户自助-是否开启用户注册功能', 'sys.account.registerUser', 'false', 'Y', 'system', 'system', NOW(), NOW()),
|
('用户自助-是否开启用户注册功能', 'sys.account.registerUser', 'false', 'Y', 'system', 'system', NOW(), NOW()),
|
||||||
('账号自助-密码验证码', 'sys.account.pwdCaptchaEnabled', 'true', 'Y', 'system', 'system', NOW(), NOW())
|
('账号自助-密码验证码', 'sys.account.pwdCaptchaEnabled', 'true', 'Y', 'system', 'system', NOW(), NOW()),
|
||||||
|
('团课-取消预约免手续费次数', 'group_course.cancel_free_limit', '3', 'Y', 'system', 'system', NOW(), NOW())
|
||||||
ON CONFLICT (config_key) DO NOTHING;
|
ON CONFLICT (config_key) DO NOTHING;
|
||||||
|
|
||||||
-- ============================================
|
-- ============================================
|
||||||
|
|||||||
+171
-91
@@ -9,24 +9,17 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.core.Ordered;
|
import org.springframework.core.Ordered;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||||
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.reactive.function.server.HandlerStrategies;
|
|
||||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
|
||||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
|
||||||
import org.springframework.web.server.ServerWebExchange;
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
import org.springframework.web.server.WebFilter;
|
import org.springframework.web.server.WebFilter;
|
||||||
import org.springframework.web.server.WebFilterChain;
|
import org.springframework.web.server.WebFilterChain;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.util.LinkedHashMap;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||||
@@ -37,19 +30,76 @@ public class OperationLogWebFilter implements WebFilter {
|
|||||||
private final IOperationLogService operationLogService;
|
private final IOperationLogService operationLogService;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
private static final Map<String, OperationInfo> OPERATION_MAPPING = new ConcurrentHashMap<>();
|
/** 精确匹配的操作映射(method:path → module, operation) */
|
||||||
|
private static final Map<String, OperationInfo> PRECISE_MAPPING = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
/** 前缀匹配的操作映射(按声明顺序) */
|
||||||
|
private static final Map<String, OperationInfo> PREFIX_MAPPING = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
/** URL模块名称映射 */
|
||||||
|
private static final Map<String, String> MODULE_NAMES = new LinkedHashMap<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
OPERATION_MAPPING.put("POST:/api/roles", new OperationInfo("角色管理", "创建角色"));
|
// ===== 精确路径匹配 =====
|
||||||
OPERATION_MAPPING.put("PUT:/api/roles/", new OperationInfo("角色管理", "更新角色"));
|
PRECISE_MAPPING.put("POST:/api/roles", new OperationInfo("角色管理", "创建角色"));
|
||||||
OPERATION_MAPPING.put("DELETE:/api/roles/", new OperationInfo("角色管理", "删除角色"));
|
PRECISE_MAPPING.put("POST:/api/users", new OperationInfo("用户管理", "创建用户"));
|
||||||
OPERATION_MAPPING.put("POST:/api/users", new OperationInfo("用户管理", "创建用户"));
|
PRECISE_MAPPING.put("POST:/api/menus", new OperationInfo("菜单管理", "创建菜单"));
|
||||||
OPERATION_MAPPING.put("PUT:/api/users/", new OperationInfo("用户管理", "更新用户"));
|
PRECISE_MAPPING.put("POST:/api/auth/login", new OperationInfo("认证", "用户登录"));
|
||||||
OPERATION_MAPPING.put("DELETE:/api/users/", new OperationInfo("用户管理", "删除用户"));
|
PRECISE_MAPPING.put("GET:/api/groupCourse/types/categories", new OperationInfo("团课类型", "查询分类"));
|
||||||
OPERATION_MAPPING.put("POST:/api/users/", new OperationInfo("用户管理", "用户操作"));
|
PRECISE_MAPPING.put("POST:/api/groupCourse/types", new OperationInfo("团课类型", "创建类型"));
|
||||||
OPERATION_MAPPING.put("POST:/api/menus", new OperationInfo("菜单管理", "创建菜单"));
|
PRECISE_MAPPING.put("POST:/api/groupCourse", new OperationInfo("团课管理", "创建团课"));
|
||||||
OPERATION_MAPPING.put("PUT:/api/menus/", new OperationInfo("菜单管理", "更新菜单"));
|
PRECISE_MAPPING.put("POST:/api/member", new OperationInfo("会员管理", "创建会员"));
|
||||||
OPERATION_MAPPING.put("DELETE:/api/menus/", new OperationInfo("菜单管理", "删除菜单"));
|
PRECISE_MAPPING.put("POST:/api/member-cards", new OperationInfo("会员卡管理", "创建会员卡"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/groupCourse/recommend", new OperationInfo("推荐管理", "创建推荐"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/checkIn", new OperationInfo("签到管理", "签到"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/payment/create", new OperationInfo("支付管理", "创建支付"));
|
||||||
|
PRECISE_MAPPING.put("POST:/api/upload/image", new OperationInfo("文件管理", "上传图片"));
|
||||||
|
|
||||||
|
// ===== 前缀匹配 =====
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/roles/", new OperationInfo("角色管理", "更新角色"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/roles/", new OperationInfo("角色管理", "删除角色"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/users/", new OperationInfo("用户管理", "更新用户"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/users/", new OperationInfo("用户管理", "删除用户"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/menus/", new OperationInfo("菜单管理", "更新菜单"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/menus/", new OperationInfo("菜单管理", "删除菜单"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/groupCourse/types/", new OperationInfo("团课类型", "更新类型"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/types/", new OperationInfo("团课类型", "删除类型"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/groupCourse/", new OperationInfo("团课管理", "更新团课"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/", new OperationInfo("团课管理", "删除团课"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/groupCourse/", new OperationInfo("团课管理", "操作团课"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/member/", new OperationInfo("会员管理", "编辑会员"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/member/", new OperationInfo("会员管理", "删除会员"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/member-cards/", new OperationInfo("会员卡管理", "编辑会员卡"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/member-cards/", new OperationInfo("会员卡管理", "删除会员卡"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/groupCourse/recommend/", new OperationInfo("推荐管理", "更新推荐"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/recommend/", new OperationInfo("推荐管理", "删除推荐"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/groupCourse/recommend/", new OperationInfo("推荐管理", "操作推荐"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/member-card-transactions/", new OperationInfo("会员卡", "交易操作"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/payment/", new OperationInfo("支付管理", "更新支付"));
|
||||||
|
PREFIX_MAPPING.put("POST:/api/payment/", new OperationInfo("支付管理", "支付操作"));
|
||||||
|
PREFIX_MAPPING.put("PUT:/api/admin/member/", new OperationInfo("会员管理", "管理员编辑会员"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/admin/member/", new OperationInfo("会员管理", "管理员删除会员"));
|
||||||
|
PREFIX_MAPPING.put("DELETE:/api/groupCourse/labels/", new OperationInfo("标签管理", "删除标签"));
|
||||||
|
|
||||||
|
// ===== URL模块名映射(用于未匹配写操作自动生成) =====
|
||||||
|
MODULE_NAMES.put("roles", "角色管理");
|
||||||
|
MODULE_NAMES.put("users", "用户管理");
|
||||||
|
MODULE_NAMES.put("menus", "菜单管理");
|
||||||
|
MODULE_NAMES.put("auth", "认证");
|
||||||
|
MODULE_NAMES.put("groupCourse", "团课管理");
|
||||||
|
MODULE_NAMES.put("member", "会员管理");
|
||||||
|
MODULE_NAMES.put("member-cards", "会员卡管理");
|
||||||
|
MODULE_NAMES.put("member-card-records", "会员卡记录");
|
||||||
|
MODULE_NAMES.put("member-card-transactions", "会员卡交易");
|
||||||
|
MODULE_NAMES.put("checkIn", "签到管理");
|
||||||
|
MODULE_NAMES.put("payment", "支付管理");
|
||||||
|
MODULE_NAMES.put("dictionaries", "字典管理");
|
||||||
|
MODULE_NAMES.put("config", "系统配置");
|
||||||
|
MODULE_NAMES.put("upload", "文件管理");
|
||||||
|
MODULE_NAMES.put("logs", "日志管理");
|
||||||
|
MODULE_NAMES.put("datacount", "数据统计");
|
||||||
|
MODULE_NAMES.put("diagnostic", "诊断");
|
||||||
|
MODULE_NAMES.put("stats", "统计");
|
||||||
}
|
}
|
||||||
|
|
||||||
public OperationLogWebFilter(IOperationLogService operationLogService, ObjectMapper objectMapper) {
|
public OperationLogWebFilter(IOperationLogService operationLogService, ObjectMapper objectMapper) {
|
||||||
@@ -61,10 +111,8 @@ public class OperationLogWebFilter implements WebFilter {
|
|||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void init() {
|
public void init() {
|
||||||
logger.info("=== OperationLogWebFilter 初始化 ===");
|
logger.info("=== OperationLogWebFilter 初始化 ===");
|
||||||
logger.info("操作日志映射配置数量: {}", OPERATION_MAPPING.size());
|
logger.info("精确匹配配置数量: {}, 前缀匹配配置数量: {}, 模块映射数量: {}",
|
||||||
OPERATION_MAPPING.forEach((key, value) -> {
|
PRECISE_MAPPING.size(), PREFIX_MAPPING.size(), MODULE_NAMES.size());
|
||||||
logger.info(" {} -> {}:{}", key, value.module, value.operation);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -72,103 +120,135 @@ public class OperationLogWebFilter implements WebFilter {
|
|||||||
ServerHttpRequest request = exchange.getRequest();
|
ServerHttpRequest request = exchange.getRequest();
|
||||||
String method = request.getMethod().name();
|
String method = request.getMethod().name();
|
||||||
String path = request.getPath().value();
|
String path = request.getPath().value();
|
||||||
|
String key = method + ":" + path;
|
||||||
|
|
||||||
logger.info("WebFilter 拦截请求: {} {}", method, path);
|
// 先尝试精确匹配
|
||||||
|
OperationInfo operationInfo = PRECISE_MAPPING.get(key);
|
||||||
|
|
||||||
OperationInfo operationInfo = findOperationInfo(method, path);
|
if (operationInfo == null) {
|
||||||
|
// 尝试前缀匹配
|
||||||
|
operationInfo = findPrefixMatch(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (operationInfo == null) {
|
||||||
|
// 未匹配:如果是写操作(POST/PUT/DELETE),自动生成记录
|
||||||
|
if (isWriteOperation(method)) {
|
||||||
|
operationInfo = buildAutoOperationInfo(method, path);
|
||||||
|
logger.info("自动生成操作日志: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("匹配到操作日志配置: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
||||||
|
}
|
||||||
|
|
||||||
if (operationInfo == null) {
|
if (operationInfo == null) {
|
||||||
logger.info("未匹配到操作日志配置,跳过: {} {}", method, path);
|
|
||||||
return chain.filter(exchange);
|
return chain.filter(exchange);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info("匹配到操作日志配置: {} {} -> {}:{}", method, path, operationInfo.module, operationInfo.operation);
|
|
||||||
|
|
||||||
long startTime = System.currentTimeMillis();
|
long startTime = System.currentTimeMillis();
|
||||||
String ip = IpUtils.getClientIp(request);
|
String ip = IpUtils.getClientIp(request);
|
||||||
|
final OperationInfo finalInfo = operationInfo;
|
||||||
|
|
||||||
return Mono.deferContextual(contextView -> {
|
|
||||||
return chain.filter(exchange)
|
return chain.filter(exchange)
|
||||||
.then(Mono.defer(() -> {
|
.then(Mono.defer(() -> {
|
||||||
long duration = System.currentTimeMillis() - startTime;
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
logger.info("请求处理完成,准备保存操作日志: {} {}, 耗时: {}ms", method, path, duration);
|
return getCurrentUsername()
|
||||||
|
.flatMap(username -> saveOperationLog(username, method, path, ip, duration, "0", null, finalInfo));
|
||||||
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 -> {
|
.onErrorResume(error -> {
|
||||||
long duration = System.currentTimeMillis() - startTime;
|
long duration = System.currentTimeMillis() - startTime;
|
||||||
logger.error("请求处理失败: {} {}, 错误: {}", method, path, error.getMessage());
|
logger.error("请求处理失败: {} {}, 错误: {}", method, path, error.getMessage());
|
||||||
|
return getCurrentUsername()
|
||||||
return ReactiveSecurityContextHolder.getContext()
|
.flatMap(username -> saveOperationLog(username, method, path, ip, duration, "1",
|
||||||
.flatMap(securityContext -> {
|
error.getMessage().substring(0, Math.min(error.getMessage().length(), 500)), finalInfo))
|
||||||
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));
|
.then(Mono.error(error));
|
||||||
});
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private OperationInfo findOperationInfo(String method, String path) {
|
private boolean isWriteOperation(String method) {
|
||||||
String key = method + ":" + path;
|
return HttpMethod.POST.name().equals(method) ||
|
||||||
if (OPERATION_MAPPING.containsKey(key)) {
|
HttpMethod.PUT.name().equals(method) ||
|
||||||
return OPERATION_MAPPING.get(key);
|
HttpMethod.DELETE.name().equals(method) ||
|
||||||
|
HttpMethod.PATCH.name().equals(method);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Map.Entry<String, OperationInfo> entry : OPERATION_MAPPING.entrySet()) {
|
private OperationInfo findPrefixMatch(String key) {
|
||||||
String mappingKey = entry.getKey();
|
for (Map.Entry<String, OperationInfo> entry : PREFIX_MAPPING.entrySet()) {
|
||||||
if (key.startsWith(mappingKey)) {
|
if (key.startsWith(entry.getKey())) {
|
||||||
return entry.getValue();
|
return entry.getValue();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据URL路径自动生成操作信息
|
||||||
|
* 例如: DELETE:/api/groupCourse/types/5 → 团课管理 - 删除操作
|
||||||
|
*/
|
||||||
|
private OperationInfo buildAutoOperationInfo(String method, String path) {
|
||||||
|
String module = extractModuleFromPath(path);
|
||||||
|
String operation = methodToOperationName(method);
|
||||||
|
return new OperationInfo(module, operation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractModuleFromPath(String path) {
|
||||||
|
// 去掉 /api/ 前缀,取第一段作为模块名
|
||||||
|
if (path.startsWith("/api/")) {
|
||||||
|
String subPath = path.substring(5); // remove "/api/"
|
||||||
|
int slashIdx = subPath.indexOf('/');
|
||||||
|
String moduleKey = slashIdx > 0 ? subPath.substring(0, slashIdx) : subPath;
|
||||||
|
|
||||||
|
// 尝试复合模块名 (如 member-cards)
|
||||||
|
if (slashIdx > 0) {
|
||||||
|
String rest = subPath.substring(slashIdx + 1);
|
||||||
|
int nextSlash = rest.indexOf('/');
|
||||||
|
String secondPart = nextSlash > 0 ? rest.substring(0, nextSlash) : rest;
|
||||||
|
String compositeKey = moduleKey + "/" + secondPart;
|
||||||
|
if (MODULE_NAMES.containsKey(compositeKey)) {
|
||||||
|
return MODULE_NAMES.get(compositeKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return MODULE_NAMES.getOrDefault(moduleKey, moduleKey);
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String methodToOperationName(String method) {
|
||||||
|
switch (method.toUpperCase()) {
|
||||||
|
case "POST": return "创建/新增操作";
|
||||||
|
case "PUT": return "编辑/更新操作";
|
||||||
|
case "DELETE": return "删除操作";
|
||||||
|
case "PATCH": return "修改操作";
|
||||||
|
default: return "操作";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<String> getCurrentUsername() {
|
||||||
|
return ReactiveSecurityContextHolder.getContext()
|
||||||
|
.map(ctx -> ctx.getAuthentication().getPrincipal())
|
||||||
|
.map(principal -> principal instanceof String ? (String) principal : "system")
|
||||||
|
.defaultIfEmpty("system")
|
||||||
|
.onErrorReturn("system");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> saveOperationLog(String username, String method, String path, String ip,
|
||||||
|
long duration, String status, String errorMsg, OperationInfo info) {
|
||||||
|
OperationLog log = new OperationLog();
|
||||||
|
log.setUsername(username);
|
||||||
|
log.setOperation(info.module + " - " + info.operation);
|
||||||
|
log.setMethod(method + " " + path);
|
||||||
|
log.setIp(ip);
|
||||||
|
log.setDuration(duration);
|
||||||
|
log.setStatus(status);
|
||||||
|
log.setErrorMsg(errorMsg);
|
||||||
|
|
||||||
|
return operationLogService.save(log)
|
||||||
|
.doOnSuccess(saved -> logger.debug("操作日志保存成功: {} - {}", info.module, info.operation))
|
||||||
|
.doOnError(e -> logger.error("操作日志保存失败: {}", e.getMessage(), e))
|
||||||
|
.onErrorResume(e -> Mono.empty())
|
||||||
|
.then();
|
||||||
|
}
|
||||||
|
|
||||||
private static class OperationInfo {
|
private static class OperationInfo {
|
||||||
final String module;
|
final String module;
|
||||||
final String operation;
|
final String operation;
|
||||||
|
|||||||
+20
@@ -11,6 +11,11 @@ import org.springframework.security.config.annotation.web.reactive.EnableWebFlux
|
|||||||
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
|
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
|
||||||
import org.springframework.security.config.web.server.ServerHttpSecurity;
|
import org.springframework.security.config.web.server.ServerHttpSecurity;
|
||||||
import org.springframework.security.web.server.SecurityWebFilterChain;
|
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||||
|
import org.springframework.web.cors.CorsConfiguration;
|
||||||
|
import org.springframework.web.cors.reactive.CorsConfigurationSource;
|
||||||
|
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebFluxSecurity
|
@EnableWebFluxSecurity
|
||||||
@@ -29,6 +34,20 @@ public class SecurityConfig {
|
|||||||
this.environment = environment;
|
this.environment = environment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CorsConfigurationSource corsConfigurationSource() {
|
||||||
|
CorsConfiguration configuration = new CorsConfiguration();
|
||||||
|
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
|
||||||
|
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||||
|
configuration.setAllowedHeaders(Arrays.asList("*"));
|
||||||
|
configuration.setAllowCredentials(true);
|
||||||
|
configuration.setMaxAge(3600L);
|
||||||
|
|
||||||
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||||
|
source.registerCorsConfiguration("/**", configuration);
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
|
||||||
String[] activeProfiles = environment.getActiveProfiles();
|
String[] activeProfiles = environment.getActiveProfiles();
|
||||||
@@ -41,6 +60,7 @@ public class SecurityConfig {
|
|||||||
activeProfiles.length > 0 ? String.join(",", activeProfiles) : "default", isDevOrTest);
|
activeProfiles.length > 0 ? String.join(",", activeProfiles) : "default", isDevOrTest);
|
||||||
|
|
||||||
http
|
http
|
||||||
|
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||||
.csrf(ServerHttpSecurity.CsrfSpec::disable)
|
.csrf(ServerHttpSecurity.CsrfSpec::disable)
|
||||||
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
|
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
|
||||||
.formLogin(ServerHttpSecurity.FormLoginSpec::disable)
|
.formLogin(ServerHttpSecurity.FormLoginSpec::disable)
|
||||||
|
|||||||
+2
@@ -53,6 +53,8 @@ public interface ISysUserService {
|
|||||||
|
|
||||||
Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword);
|
Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword);
|
||||||
|
|
||||||
|
Mono<Boolean> verifyPassword(Long userId, String password);
|
||||||
|
|
||||||
Mono<Void> updateRoleIdToNullByRoleId(Long roleId);
|
Mono<Void> updateRoleIdToNullByRoleId(Long roleId);
|
||||||
|
|
||||||
Mono<Void> assignRolesToUser(Long userId, java.util.List<Long> roleIds);
|
Mono<Void> assignRolesToUser(Long userId, java.util.List<Long> roleIds);
|
||||||
|
|||||||
+3
@@ -120,6 +120,9 @@ public class SysPermissionService implements ISysPermissionService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Flux<SysPermission> findByRoleIds(List<Long> roleIds) {
|
public Flux<SysPermission> findByRoleIds(List<Long> roleIds) {
|
||||||
|
if (roleIds == null || roleIds.isEmpty()) {
|
||||||
|
return Flux.empty();
|
||||||
|
}
|
||||||
return permissionRepository.findByRoleIds(roleIds);
|
return permissionRepository.findByRoleIds(roleIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-1
@@ -83,7 +83,6 @@ public class SysRoleService implements ISysRoleService {
|
|||||||
@Override
|
@Override
|
||||||
public Mono<SysRole> createRole(CreateRoleCommand command) {
|
public Mono<SysRole> createRole(CreateRoleCommand command) {
|
||||||
SysRole role = new SysRole();
|
SysRole role = new SysRole();
|
||||||
role.generateId();
|
|
||||||
role.setRoleName(command.roleName());
|
role.setRoleName(command.roleName());
|
||||||
role.setRoleKey(command.roleKey());
|
role.setRoleKey(command.roleKey());
|
||||||
role.setRoleSort(command.roleSort());
|
role.setRoleSort(command.roleSort());
|
||||||
|
|||||||
+7
-2
@@ -97,7 +97,6 @@ public class SysUserService implements ISysUserService {
|
|||||||
logger.info("SysUserService.createUser - 用户名: {}, 密码前缀: {}",
|
logger.info("SysUserService.createUser - 用户名: {}, 密码前缀: {}",
|
||||||
user.getUsername(),
|
user.getUsername(),
|
||||||
user.getPassword() != null ? user.getPassword().substring(0, 7) : "null");
|
user.getPassword() != null ? user.getPassword().substring(0, 7) : "null");
|
||||||
user.generateId();
|
|
||||||
if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")
|
if (user.getPassword() != null && !user.getPassword().startsWith("$2a$")
|
||||||
&& !user.getPassword().startsWith("$2b$")) {
|
&& !user.getPassword().startsWith("$2b$")) {
|
||||||
logger.info("密码不以$2a$或$2b$开头,重新编码");
|
logger.info("密码不以$2a$或$2b$开头,重新编码");
|
||||||
@@ -117,7 +116,6 @@ public class SysUserService implements ISysUserService {
|
|||||||
@Override
|
@Override
|
||||||
public Mono<SysUser> createUser(CreateUserCommand command) {
|
public Mono<SysUser> createUser(CreateUserCommand command) {
|
||||||
SysUser user = new SysUser();
|
SysUser user = new SysUser();
|
||||||
user.generateId();
|
|
||||||
user.setUsername(command.username().getValue());
|
user.setUsername(command.username().getValue());
|
||||||
user.setPassword(passwordEncoder.encode(command.password().getValue()));
|
user.setPassword(passwordEncoder.encode(command.password().getValue()));
|
||||||
user.setEmail(command.email().getValue());
|
user.setEmail(command.email().getValue());
|
||||||
@@ -204,6 +202,13 @@ public class SysUserService implements ISysUserService {
|
|||||||
return userRepository.updateRoleIdToNullByRoleId(roleId);
|
return userRepository.updateRoleIdToNullByRoleId(roleId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Boolean> verifyPassword(Long userId, String password) {
|
||||||
|
return userRepository.findById(userId)
|
||||||
|
.map(user -> passwordEncoder.matches(password, user.getPassword()))
|
||||||
|
.defaultIfEmpty(false);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword) {
|
public Mono<SysUser> changePassword(Long userId, String oldPassword, String newPassword) {
|
||||||
return userRepository.findById(userId)
|
return userRepository.findById(userId)
|
||||||
|
|||||||
+27
-1
@@ -2,6 +2,8 @@ package cn.novalon.gym.manage.sys.dto.response;
|
|||||||
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证响应DTO
|
* 认证响应DTO
|
||||||
*
|
*
|
||||||
@@ -20,13 +22,21 @@ public class AuthResponse {
|
|||||||
@Schema(description = "用户名", example = "admin")
|
@Schema(description = "用户名", example = "admin")
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
|
@Schema(description = "角色标识列表", example = "[\"admin\"]")
|
||||||
|
private List<String> roles;
|
||||||
|
|
||||||
|
@Schema(description = "权限码列表", example = "[\"system:user:view\", \"system:user:create\"]")
|
||||||
|
private List<String> permissions;
|
||||||
|
|
||||||
public AuthResponse() {
|
public AuthResponse() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public AuthResponse(String token, Long userId, String username) {
|
public AuthResponse(String token, Long userId, String username, List<String> roles, List<String> permissions) {
|
||||||
this.token = token;
|
this.token = token;
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
this.username = username;
|
this.username = username;
|
||||||
|
this.roles = roles;
|
||||||
|
this.permissions = permissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getToken() {
|
public String getToken() {
|
||||||
@@ -52,4 +62,20 @@ public class AuthResponse {
|
|||||||
public void setUsername(String username) {
|
public void setUsername(String username) {
|
||||||
this.username = username;
|
this.username = username;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<String> getRoles() {
|
||||||
|
return roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRoles(List<String> roles) {
|
||||||
|
this.roles = roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getPermissions() {
|
||||||
|
return permissions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPermissions(List<String> permissions) {
|
||||||
|
this.permissions = permissions;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+76
-7
@@ -8,6 +8,7 @@ import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
|||||||
import cn.novalon.gym.manage.sys.core.domain.SysLoginLog;
|
import cn.novalon.gym.manage.sys.core.domain.SysLoginLog;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysLoginLogService;
|
import cn.novalon.gym.manage.sys.core.service.ISysLoginLogService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
||||||
import cn.novalon.gym.manage.sys.util.UserAgentParser;
|
import cn.novalon.gym.manage.sys.util.UserAgentParser;
|
||||||
import cn.novalon.gym.manage.sys.util.IpLocationParser;
|
import cn.novalon.gym.manage.sys.util.IpLocationParser;
|
||||||
import cn.novalon.gym.manage.common.util.StatusConstants;
|
import cn.novalon.gym.manage.common.util.StatusConstants;
|
||||||
@@ -28,6 +29,7 @@ import org.springframework.web.reactive.function.server.ServerResponse;
|
|||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -50,6 +52,7 @@ public class SysAuthHandler {
|
|||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final JwtTokenProvider jwtTokenProvider;
|
private final JwtTokenProvider jwtTokenProvider;
|
||||||
private final ISysLoginLogService loginLogService;
|
private final ISysLoginLogService loginLogService;
|
||||||
|
private final ISysPermissionService permissionService;
|
||||||
private final UserAgentParser userAgentParser;
|
private final UserAgentParser userAgentParser;
|
||||||
private final IpLocationParser ipLocationParser;
|
private final IpLocationParser ipLocationParser;
|
||||||
|
|
||||||
@@ -60,11 +63,13 @@ public class SysAuthHandler {
|
|||||||
public SysAuthHandler(ISysUserService userService,
|
public SysAuthHandler(ISysUserService userService,
|
||||||
@Qualifier("passwordEncoder") PasswordEncoder passwordEncoder,
|
@Qualifier("passwordEncoder") PasswordEncoder passwordEncoder,
|
||||||
JwtTokenProvider jwtTokenProvider, ISysLoginLogService loginLogService,
|
JwtTokenProvider jwtTokenProvider, ISysLoginLogService loginLogService,
|
||||||
|
ISysPermissionService permissionService,
|
||||||
UserAgentParser userAgentParser, IpLocationParser ipLocationParser) {
|
UserAgentParser userAgentParser, IpLocationParser ipLocationParser) {
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
this.jwtTokenProvider = jwtTokenProvider;
|
this.jwtTokenProvider = jwtTokenProvider;
|
||||||
this.loginLogService = loginLogService;
|
this.loginLogService = loginLogService;
|
||||||
|
this.permissionService = permissionService;
|
||||||
this.userAgentParser = userAgentParser;
|
this.userAgentParser = userAgentParser;
|
||||||
this.ipLocationParser = ipLocationParser;
|
this.ipLocationParser = ipLocationParser;
|
||||||
|
|
||||||
@@ -126,30 +131,50 @@ public class SysAuthHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return userService.getUserRoles(user.getId())
|
return userService.getUserRoles(user.getId())
|
||||||
.map(role -> role.getRoleKey())
|
|
||||||
.collectList()
|
.collectList()
|
||||||
.flatMap(roleKeys -> {
|
.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
|
String token = jwtTokenProvider
|
||||||
.generateToken(
|
.generateToken(
|
||||||
user.getUsername(),
|
user.getUsername(),
|
||||||
user.getId(),
|
user.getId(),
|
||||||
roleKeys);
|
roleKeys);
|
||||||
logger.info("用户登录成功: username={}, userId={}, roles={}",
|
logger.info("用户登录成功: username={}, userId={}, roles={}, permissions={}",
|
||||||
user.getUsername(),
|
user.getUsername(),
|
||||||
user.getId(),
|
user.getId(),
|
||||||
roleKeys);
|
roleKeys,
|
||||||
recordLoginLog(loginRequest
|
permCodes.size());
|
||||||
.getUsername(),
|
recordLoginLog(loginRequest.getUsername(),
|
||||||
clientIp,
|
clientIp,
|
||||||
"0", "登录成功",
|
"0", "登录成功",
|
||||||
userAgent);
|
userAgent);
|
||||||
AuthResponse response = new AuthResponse(
|
AuthResponse response = new AuthResponse(
|
||||||
token,
|
token,
|
||||||
user.getId(),
|
user.getId(),
|
||||||
user.getUsername());
|
user.getUsername(),
|
||||||
|
roleKeys,
|
||||||
|
permCodes);
|
||||||
return ServerResponse.ok()
|
return ServerResponse.ok()
|
||||||
.bodyValue(response);
|
.bodyValue(response);
|
||||||
});
|
});
|
||||||
|
});
|
||||||
})
|
})
|
||||||
.switchIfEmpty(Mono.defer(() -> {
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
logger.warn("用户登录失败: username={}, reason=用户不存在",
|
logger.warn("用户登录失败: username={}, reason=用户不存在",
|
||||||
@@ -190,6 +215,50 @@ public class SysAuthHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取当前用户信息", description = "根据Token获取当前登录用户的详细信息和权限")
|
||||||
|
public Mono<ServerResponse> me(ServerRequest request) {
|
||||||
|
String authHeader = request.headers().firstHeader("Authorization");
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
return ServerResponse.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
if (!jwtTokenProvider.validateToken(token)) {
|
||||||
|
return ServerResponse.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
Long userId = jwtTokenProvider.getUserIdFromToken(token);
|
||||||
|
return userService.findById(userId)
|
||||||
|
.flatMap(user -> userService.getUserRoles(user.getId())
|
||||||
|
.collectList()
|
||||||
|
.flatMap(roles -> {
|
||||||
|
List<String> roleKeys = roles.stream()
|
||||||
|
.map(r -> r.getRoleKey())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
List<Long> roleIds = roles.stream()
|
||||||
|
.map(r -> r.getId())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
Mono<List<String>> permCodesMono;
|
||||||
|
if (roleIds.isEmpty()) {
|
||||||
|
permCodesMono = Mono.just(java.util.Collections.<String>emptyList());
|
||||||
|
} else {
|
||||||
|
permCodesMono = permissionService.findByRoleIds(roleIds)
|
||||||
|
.map(p -> p.getPermissionCode())
|
||||||
|
.collectList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return permCodesMono
|
||||||
|
.flatMap(permCodes -> {
|
||||||
|
AuthResponse response = new AuthResponse(
|
||||||
|
token,
|
||||||
|
user.getId(),
|
||||||
|
user.getUsername(),
|
||||||
|
roleKeys,
|
||||||
|
permCodes);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
private void recordLoginLog(String username, String ip, String status, String message, String userAgent) {
|
private void recordLoginLog(String username, String ip, String status, String message, String userAgent) {
|
||||||
try {
|
try {
|
||||||
SysLoginLog loginLog = new SysLoginLog();
|
SysLoginLog loginLog = new SysLoginLog();
|
||||||
|
|||||||
+31
-3
@@ -1,7 +1,11 @@
|
|||||||
package cn.novalon.gym.manage.sys.handler.permission;
|
package cn.novalon.gym.manage.sys.handler.permission;
|
||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysPermission;
|
import cn.novalon.gym.manage.sys.core.domain.SysPermission;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -22,10 +26,19 @@ import java.util.List;
|
|||||||
@Tag(name = "权限管理", description = "权限相关操作")
|
@Tag(name = "权限管理", description = "权限相关操作")
|
||||||
public class SysPermissionHandler {
|
public class SysPermissionHandler {
|
||||||
|
|
||||||
private final ISysPermissionService permissionService;
|
private static final Long BUILTIN_ROLE_ID = 1L;
|
||||||
|
|
||||||
public SysPermissionHandler(ISysPermissionService permissionService) {
|
private final ISysPermissionService permissionService;
|
||||||
|
private final ISysRoleService roleService;
|
||||||
|
private final ISysUserService userService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
|
public SysPermissionHandler(ISysPermissionService permissionService, ISysRoleService roleService,
|
||||||
|
ISysUserService userService, AuthUtil authUtil) {
|
||||||
this.permissionService = permissionService;
|
this.permissionService = permissionService;
|
||||||
|
this.roleService = roleService;
|
||||||
|
this.userService = userService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有权限", description = "获取系统中所有权限列表")
|
@Operation(summary = "获取所有权限", description = "获取系统中所有权限列表")
|
||||||
@@ -97,12 +110,27 @@ public class SysPermissionHandler {
|
|||||||
.body(permissionService.getPermissionsByRoleId(roleId), SysPermission.class);
|
.body(permissionService.getPermissionsByRoleId(roleId), SysPermission.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表")
|
@Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表,需验证管理员密码,超级管理员角色不可被分配")
|
||||||
public Mono<ServerResponse> assignPermissionsToRole(ServerRequest request) {
|
public Mono<ServerResponse> assignPermissionsToRole(ServerRequest request) {
|
||||||
Long roleId = Long.valueOf(request.pathVariable("id"));
|
Long roleId = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return 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)
|
return request.bodyToMono(AssignPermissionsRequest.class)
|
||||||
.flatMap(req -> permissionService.assignPermissionsToRole(roleId, req.permissionIds()))
|
.flatMap(req -> permissionService.assignPermissionsToRole(roleId, req.permissionIds()))
|
||||||
.then(ServerResponse.ok().build());
|
.then(ServerResponse.ok().build());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Boolean> verifyAdminPassword(ServerRequest request) {
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
return userService.verifyPassword(adminId, adminPassword);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record AssignPermissionsRequest(List<Long> permissionIds) {}
|
private record AssignPermissionsRequest(List<Long> permissionIds) {}
|
||||||
|
|||||||
+34
-8
@@ -2,6 +2,8 @@ package cn.novalon.gym.manage.sys.handler.role;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.RoleCreateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.RoleCreateRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
||||||
@@ -30,12 +32,18 @@ import java.util.Map;
|
|||||||
@Tag(name = "角色管理", description = "角色相关操作")
|
@Tag(name = "角色管理", description = "角色相关操作")
|
||||||
public class SysRoleHandler {
|
public class SysRoleHandler {
|
||||||
|
|
||||||
|
private static final Long BUILTIN_ROLE_ID = 1L;
|
||||||
|
|
||||||
private final ISysRoleService roleService;
|
private final ISysRoleService roleService;
|
||||||
private final Validator validator;
|
private final Validator validator;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
private final ISysUserService userService;
|
||||||
|
|
||||||
public SysRoleHandler(ISysRoleService roleService, Validator validator) {
|
public SysRoleHandler(ISysRoleService roleService, Validator validator, AuthUtil authUtil, ISysUserService userService) {
|
||||||
this.roleService = roleService;
|
this.roleService = roleService;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
|
this.authUtil = authUtil;
|
||||||
|
this.userService = userService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有角色", description = "获取系统中所有角色列表")
|
@Operation(summary = "获取所有角色", description = "获取系统中所有角色列表")
|
||||||
@@ -115,30 +123,39 @@ public class SysRoleHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新角色", description = "更新角色信息")
|
@Operation(summary = "更新角色", description = "更新角色信息,需验证管理员密码,超级管理员角色不可被编辑")
|
||||||
@OperationLog(operation = "更新角色", module = "角色管理")
|
@OperationLog(operation = "更新角色", module = "角色管理")
|
||||||
public Mono<ServerResponse> updateRole(ServerRequest request) {
|
public Mono<ServerResponse> updateRole(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return 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)
|
return request.bodyToMono(RoleUpdateRequest.class)
|
||||||
.map(req -> UpdateRoleCommand.of(
|
.map(req -> UpdateRoleCommand.of(
|
||||||
id,
|
id, req.getRoleName(), req.getRoleKey(),
|
||||||
req.getRoleName(),
|
req.getRoleSort(), req.getStatus()
|
||||||
req.getRoleKey(),
|
|
||||||
req.getRoleSort(),
|
|
||||||
req.getStatus()
|
|
||||||
))
|
))
|
||||||
.flatMap(roleService::updateRole)
|
.flatMap(roleService::updateRole)
|
||||||
.flatMap(updatedRole -> ServerResponse.ok().bodyValue(updatedRole))
|
.flatMap(updatedRole -> ServerResponse.ok().bodyValue(updatedRole))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除角色", description = "逻辑删除角色")
|
@Operation(summary = "删除角色", description = "逻辑删除角色,需验证管理员密码,超级管理员角色不可被删除")
|
||||||
@OperationLog(operation = "删除角色", module = "角色管理")
|
@OperationLog(operation = "删除角色", module = "角色管理")
|
||||||
public Mono<ServerResponse> deleteRole(ServerRequest request) {
|
public Mono<ServerResponse> deleteRole(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return verifyAdminPassword(request)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
|
if (BUILTIN_ROLE_ID.equals(id)) return ServerResponse.badRequest().bodyValue("超级管理员角色不可删除");
|
||||||
return roleService.logicalDeleteRole(id)
|
return roleService.logicalDeleteRole(id)
|
||||||
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "恢复角色", description = "恢复被逻辑删除的角色")
|
@Operation(summary = "恢复角色", description = "恢复被逻辑删除的角色")
|
||||||
@@ -148,4 +165,13 @@ public class SysRoleHandler {
|
|||||||
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
.flatMap(role -> ServerResponse.ok().bodyValue(role))
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Mono<Boolean> verifyAdminPassword(ServerRequest request) {
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
return userService.verifyPassword(adminId, adminPassword);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+80
-20
@@ -2,6 +2,7 @@ package cn.novalon.gym.manage.sys.handler.user;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.AssignRolesRequest;
|
import cn.novalon.gym.manage.sys.dto.request.AssignRolesRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.PasswordChangeRequest;
|
import cn.novalon.gym.manage.sys.dto.request.PasswordChangeRequest;
|
||||||
@@ -42,10 +43,12 @@ public class SysUserHandler {
|
|||||||
private static final Logger logger = LoggerFactory.getLogger(SysUserHandler.class);
|
private static final Logger logger = LoggerFactory.getLogger(SysUserHandler.class);
|
||||||
private final ISysUserService userService;
|
private final ISysUserService userService;
|
||||||
private final Validator validator;
|
private final Validator validator;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
public SysUserHandler(ISysUserService userService, Validator validator) {
|
public SysUserHandler(ISysUserService userService, Validator validator, AuthUtil authUtil) {
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
|
this.authUtil = authUtil;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取所有用户", description = "获取系统中所有用户列表")
|
@Operation(summary = "获取所有用户", description = "获取系统中所有用户列表")
|
||||||
@@ -152,39 +155,63 @@ public class SysUserHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新用户", description = "更新用户信息")
|
@Operation(summary = "更新用户", description = "更新用户信息,需验证管理员密码,超级管理员不可编辑")
|
||||||
@OperationLog(operation = "更新用户", module = "用户管理")
|
@OperationLog(operation = "更新用户", module = "用户管理")
|
||||||
public Mono<ServerResponse> updateUser(ServerRequest request) {
|
public Mono<ServerResponse> updateUser(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return 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)
|
return request.bodyToMono(UserUpdateRequest.class)
|
||||||
.map(req -> {
|
.map(req -> {
|
||||||
boolean clearRole = Boolean.TRUE.equals(req.getClearRole()) ||
|
boolean clearRole = Boolean.TRUE.equals(req.getClearRole()) ||
|
||||||
(req.getRoleId() == null && req.getClearRole() != null);
|
(req.getRoleId() == null && req.getClearRole() != null);
|
||||||
return UpdateUserCommand.of(
|
return UpdateUserCommand.of(
|
||||||
id,
|
id, null, null, req.getEmail(),
|
||||||
null,
|
req.getRoleId(), req.getStatus(), clearRole
|
||||||
null,
|
|
||||||
req.getEmail(),
|
|
||||||
req.getRoleId(),
|
|
||||||
req.getStatus(),
|
|
||||||
clearRole
|
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
.flatMap(userService::updateUser)
|
.flatMap(userService::updateUser)
|
||||||
.flatMap(user -> ServerResponse.ok().bodyValue(user))
|
.flatMap(updated -> ServerResponse.ok().bodyValue(updated));
|
||||||
|
})
|
||||||
.switchIfEmpty(ServerResponse.notFound().build());
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "删除用户", description = "物理删除用户")
|
@Operation(summary = "删除用户", description = "物理删除用户,需验证管理员密码,超级管理员不可删除")
|
||||||
@OperationLog(operation = "删除用户", module = "用户管理")
|
@OperationLog(operation = "删除用户", module = "用户管理")
|
||||||
public Mono<ServerResponse> deleteUser(ServerRequest request) {
|
public Mono<ServerResponse> deleteUser(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return verifyAdminPassword(request)
|
||||||
|
.flatMap(valid -> {
|
||||||
|
if (!valid) {
|
||||||
|
return ServerResponse.badRequest().bodyValue("管理员密码不能为空或错误");
|
||||||
|
}
|
||||||
return userService.findById(id)
|
return userService.findById(id)
|
||||||
.flatMap(user -> userService.deleteUser(id)
|
.flatMap(user -> {
|
||||||
.then(ServerResponse.noContent().build()))
|
if ("admin".equals(user.getUsername())) {
|
||||||
.switchIfEmpty(Mono.error(new RuntimeException("User not found")))
|
return Mono.<ServerResponse>error(new RuntimeException("超级管理员不可删除"));
|
||||||
|
}
|
||||||
|
return userService.deleteUser(id)
|
||||||
|
.then(ServerResponse.noContent().build());
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("User not found")));
|
||||||
|
})
|
||||||
.onErrorResume(RuntimeException.class, ex -> {
|
.onErrorResume(RuntimeException.class, ex -> {
|
||||||
if (ex.getMessage().contains("not found")) {
|
String msg = ex.getMessage();
|
||||||
|
if ("超级管理员不可删除".equals(msg) || "超级管理员不可编辑".equals(msg)) {
|
||||||
|
return ServerResponse.badRequest().bodyValue(msg);
|
||||||
|
}
|
||||||
|
if ("User not found".equals(msg)) {
|
||||||
return ServerResponse.notFound().build();
|
return ServerResponse.notFound().build();
|
||||||
}
|
}
|
||||||
return Mono.error(ex);
|
return Mono.error(ex);
|
||||||
@@ -258,16 +285,37 @@ public class SysUserHandler {
|
|||||||
.flatMap(exists -> ServerResponse.ok().bodyValue(exists));
|
.flatMap(exists -> ServerResponse.ok().bodyValue(exists));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "为用户分配角色", description = "为指定用户分配角色列表")
|
@Operation(summary = "为用户分配角色", description = "为指定用户分配角色列表,需验证管理员密码,超级管理员不可分配")
|
||||||
@OperationLog(operation = "分配角色", module = "用户管理")
|
@OperationLog(operation = "分配角色", module = "用户管理")
|
||||||
public Mono<ServerResponse> assignRoles(ServerRequest request) {
|
public Mono<ServerResponse> assignRoles(ServerRequest request) {
|
||||||
Long id = Long.valueOf(request.pathVariable("id"));
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return 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)
|
return request.bodyToMono(AssignRolesRequest.class)
|
||||||
.flatMap(req -> userService.assignRolesToUser(id, req.getRoleIdsAsLong()))
|
.flatMap(req -> userService.assignRolesToUser(id, req.getRoleIdsAsLong()))
|
||||||
.then(ServerResponse.ok().build())
|
.then(ServerResponse.ok().build());
|
||||||
.onErrorResume(error -> {
|
})
|
||||||
logger.error("分配角色失败", error);
|
.switchIfEmpty(Mono.error(new RuntimeException("User not found")));
|
||||||
return ServerResponse.status(500).bodyValue("分配角色失败: " + error.getMessage());
|
})
|
||||||
|
.onErrorResume(RuntimeException.class, ex -> {
|
||||||
|
String msg = ex.getMessage();
|
||||||
|
if ("超级管理员不可被分配角色".equals(msg)) {
|
||||||
|
return ServerResponse.badRequest().bodyValue(msg);
|
||||||
|
}
|
||||||
|
if ("User not found".equals(msg)) {
|
||||||
|
return ServerResponse.notFound().build();
|
||||||
|
}
|
||||||
|
logger.error("分配角色失败", ex);
|
||||||
|
return ServerResponse.status(500).bodyValue("分配角色失败: " + msg);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,4 +325,16 @@ public class SysUserHandler {
|
|||||||
return ServerResponse.ok()
|
return ServerResponse.ok()
|
||||||
.body(userService.getUserRoles(id), cn.novalon.gym.manage.sys.core.domain.SysRole.class);
|
.body(userService.getUserRoles(id), cn.novalon.gym.manage.sys.core.domain.SysRole.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证管理员密码
|
||||||
|
*/
|
||||||
|
private Mono<Boolean> verifyAdminPassword(ServerRequest request) {
|
||||||
|
String adminPassword = request.queryParam("adminPassword").orElse(null);
|
||||||
|
if (adminPassword == null || adminPassword.isBlank()) {
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
Long adminId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
return userService.verifyPassword(adminId, adminPassword);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -8,7 +8,7 @@ class AuthResponseTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testConstructorWithParameters() {
|
void testConstructorWithParameters() {
|
||||||
AuthResponse response = new AuthResponse("test-token", 1L, "testuser");
|
AuthResponse response = new AuthResponse("test-token", 1L, "testuser", null, null);
|
||||||
|
|
||||||
assertEquals("test-token", response.getToken());
|
assertEquals("test-token", response.getToken());
|
||||||
assertEquals(1L, response.getUserId());
|
assertEquals(1L, response.getUserId());
|
||||||
@@ -63,7 +63,7 @@ class AuthResponseTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testConstructorWithNullValues() {
|
void testConstructorWithNullValues() {
|
||||||
AuthResponse response = new AuthResponse(null, null, null);
|
AuthResponse response = new AuthResponse(null, null, null, null, null);
|
||||||
|
|
||||||
assertNull(response.getToken());
|
assertNull(response.getToken());
|
||||||
assertNull(response.getUserId());
|
assertNull(response.getUserId());
|
||||||
@@ -72,7 +72,7 @@ class AuthResponseTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testConstructorWithEmptyStrings() {
|
void testConstructorWithEmptyStrings() {
|
||||||
AuthResponse response = new AuthResponse("", 1L, "");
|
AuthResponse response = new AuthResponse("", 1L, "", null, null);
|
||||||
|
|
||||||
assertEquals("", response.getToken());
|
assertEquals("", response.getToken());
|
||||||
assertEquals(1L, response.getUserId());
|
assertEquals(1L, response.getUserId());
|
||||||
@@ -164,7 +164,7 @@ class AuthResponseTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testConstructorWithZeroUserId() {
|
void testConstructorWithZeroUserId() {
|
||||||
AuthResponse response = new AuthResponse("token", 0L, "user");
|
AuthResponse response = new AuthResponse("token", 0L, "user", null, null);
|
||||||
|
|
||||||
assertEquals("token", response.getToken());
|
assertEquals("token", response.getToken());
|
||||||
assertEquals(0L, response.getUserId());
|
assertEquals(0L, response.getUserId());
|
||||||
|
|||||||
+10
-1
@@ -6,9 +6,11 @@ import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
|||||||
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysLoginLog;
|
import cn.novalon.gym.manage.sys.core.domain.SysLoginLog;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.SysPermission;
|
||||||
import cn.novalon.gym.manage.sys.util.TestDataFactory;
|
import cn.novalon.gym.manage.sys.util.TestDataFactory;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysLoginLogService;
|
import cn.novalon.gym.manage.sys.core.service.ISysLoginLogService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
|
||||||
import cn.novalon.gym.manage.sys.util.UserAgentParser;
|
import cn.novalon.gym.manage.sys.util.UserAgentParser;
|
||||||
import cn.novalon.gym.manage.sys.util.IpLocationParser;
|
import cn.novalon.gym.manage.sys.util.IpLocationParser;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -47,6 +49,9 @@ class SysAuthHandlerTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private ISysLoginLogService loginLogService;
|
private ISysLoginLogService loginLogService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ISysPermissionService permissionService;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private UserAgentParser userAgentParser;
|
private UserAgentParser userAgentParser;
|
||||||
|
|
||||||
@@ -59,7 +64,7 @@ class SysAuthHandlerTest {
|
|||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
authHandler = new SysAuthHandler(userService, passwordEncoder, jwtTokenProvider, loginLogService,
|
authHandler = new SysAuthHandler(userService, passwordEncoder, jwtTokenProvider, loginLogService,
|
||||||
userAgentParser, ipLocationParser);
|
permissionService, userAgentParser, ipLocationParser);
|
||||||
|
|
||||||
testUser = TestDataFactory.createTestUser();
|
testUser = TestDataFactory.createTestUser();
|
||||||
}
|
}
|
||||||
@@ -88,6 +93,10 @@ class SysAuthHandlerTest {
|
|||||||
when(userService.getUserRoles(1L)).thenReturn(Flux.just(mockRole));
|
when(userService.getUserRoles(1L)).thenReturn(Flux.just(mockRole));
|
||||||
when(loginLogService.save(any())).thenReturn(Mono.just(new SysLoginLog()));
|
when(loginLogService.save(any())).thenReturn(Mono.just(new SysLoginLog()));
|
||||||
|
|
||||||
|
SysPermission mockPermission = new SysPermission();
|
||||||
|
mockPermission.setPermissionCode("system:user:view");
|
||||||
|
when(permissionService.findByRoleIds(anyList())).thenReturn(Flux.just(mockPermission));
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.body(Mono.just(loginRequest));
|
.body(Mono.just(loginRequest));
|
||||||
Mono<ServerResponse> response = authHandler.login(request);
|
Mono<ServerResponse> response = authHandler.login(request);
|
||||||
|
|||||||
+25
-5
@@ -2,6 +2,8 @@ package cn.novalon.gym.manage.sys.handler.role;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
import cn.novalon.gym.manage.sys.core.service.ISysRoleService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.RoleCreateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.RoleCreateRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.RoleUpdateRequest;
|
||||||
import cn.novalon.gym.manage.sys.core.command.CreateRoleCommand;
|
import cn.novalon.gym.manage.sys.core.command.CreateRoleCommand;
|
||||||
@@ -35,12 +37,18 @@ class SysRoleHandlerTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private Validator validator;
|
private Validator validator;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AuthUtil authUtil;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ISysUserService userService;
|
||||||
|
|
||||||
private SysRoleHandler roleHandler;
|
private SysRoleHandler roleHandler;
|
||||||
private SysRole testRole;
|
private SysRole testRole;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
roleHandler = new SysRoleHandler(roleService, validator);
|
roleHandler = new SysRoleHandler(roleService, validator, authUtil, userService);
|
||||||
|
|
||||||
testRole = new SysRole();
|
testRole = new SysRole();
|
||||||
testRole.setId(1L);
|
testRole.setId(1L);
|
||||||
@@ -251,10 +259,13 @@ class SysRoleHandlerTest {
|
|||||||
updateRequest.setRoleSort(3);
|
updateRequest.setRoleSort(3);
|
||||||
updateRequest.setStatus(0);
|
updateRequest.setStatus(0);
|
||||||
|
|
||||||
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
when(roleService.updateRole(any(UpdateRoleCommand.class))).thenReturn(Mono.just(testRole));
|
when(roleService.updateRole(any(UpdateRoleCommand.class))).thenReturn(Mono.just(testRole));
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "1")
|
.pathVariable("id", "2")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.body(Mono.just(updateRequest));
|
.body(Mono.just(updateRequest));
|
||||||
Mono<ServerResponse> response = roleHandler.updateRole(request);
|
Mono<ServerResponse> response = roleHandler.updateRole(request);
|
||||||
|
|
||||||
@@ -271,10 +282,13 @@ class SysRoleHandlerTest {
|
|||||||
RoleUpdateRequest updateRequest = new RoleUpdateRequest();
|
RoleUpdateRequest updateRequest = new RoleUpdateRequest();
|
||||||
updateRequest.setRoleName("UPDATED_ROLE");
|
updateRequest.setRoleName("UPDATED_ROLE");
|
||||||
|
|
||||||
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
when(roleService.updateRole(any(UpdateRoleCommand.class))).thenReturn(Mono.empty());
|
when(roleService.updateRole(any(UpdateRoleCommand.class))).thenReturn(Mono.empty());
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "999")
|
.pathVariable("id", "999")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.body(Mono.just(updateRequest));
|
.body(Mono.just(updateRequest));
|
||||||
Mono<ServerResponse> response = roleHandler.updateRole(request);
|
Mono<ServerResponse> response = roleHandler.updateRole(request);
|
||||||
|
|
||||||
@@ -288,10 +302,13 @@ class SysRoleHandlerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDeleteRole() {
|
void testDeleteRole() {
|
||||||
when(roleService.logicalDeleteRole(1L)).thenReturn(Mono.just(testRole));
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
|
when(roleService.logicalDeleteRole(2L)).thenReturn(Mono.just(testRole));
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "1")
|
.pathVariable("id", "2")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.build();
|
.build();
|
||||||
Mono<ServerResponse> response = roleHandler.deleteRole(request);
|
Mono<ServerResponse> response = roleHandler.deleteRole(request);
|
||||||
|
|
||||||
@@ -300,15 +317,18 @@ class SysRoleHandlerTest {
|
|||||||
serverResponse.statusCode() == HttpStatus.OK)
|
serverResponse.statusCode() == HttpStatus.OK)
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
|
|
||||||
verify(roleService).logicalDeleteRole(1L);
|
verify(roleService).logicalDeleteRole(2L);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testDeleteRole_NotFound() {
|
void testDeleteRole_NotFound() {
|
||||||
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
when(roleService.logicalDeleteRole(999L)).thenReturn(Mono.empty());
|
when(roleService.logicalDeleteRole(999L)).thenReturn(Mono.empty());
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "999")
|
.pathVariable("id", "999")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.build();
|
.build();
|
||||||
Mono<ServerResponse> response = roleHandler.deleteRole(request);
|
Mono<ServerResponse> response = roleHandler.deleteRole(request);
|
||||||
|
|
||||||
|
|||||||
+17
-3
@@ -2,6 +2,7 @@ package cn.novalon.gym.manage.sys.handler.user;
|
|||||||
|
|
||||||
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||||
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
import cn.novalon.gym.manage.sys.core.service.ISysUserService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.PasswordChangeRequest;
|
import cn.novalon.gym.manage.sys.dto.request.PasswordChangeRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.UserRegisterRequest;
|
import cn.novalon.gym.manage.sys.dto.request.UserRegisterRequest;
|
||||||
import cn.novalon.gym.manage.sys.dto.request.UserUpdateRequest;
|
import cn.novalon.gym.manage.sys.dto.request.UserUpdateRequest;
|
||||||
@@ -42,12 +43,15 @@ class SysUserHandlerTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private Validator validator;
|
private Validator validator;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AuthUtil authUtil;
|
||||||
|
|
||||||
private SysUserHandler userHandler;
|
private SysUserHandler userHandler;
|
||||||
private SysUser testUser;
|
private SysUser testUser;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
userHandler = new SysUserHandler(userService, validator);
|
userHandler = new SysUserHandler(userService, validator, authUtil);
|
||||||
|
|
||||||
testUser = new SysUser();
|
testUser = new SysUser();
|
||||||
testUser.setId(1L);
|
testUser.setId(1L);
|
||||||
@@ -191,9 +195,12 @@ class SysUserHandlerTest {
|
|||||||
void testDeleteUser() {
|
void testDeleteUser() {
|
||||||
when(userService.findById(1L)).thenReturn(Mono.just(testUser));
|
when(userService.findById(1L)).thenReturn(Mono.just(testUser));
|
||||||
when(userService.deleteUser(1L)).thenReturn(Mono.empty());
|
when(userService.deleteUser(1L)).thenReturn(Mono.empty());
|
||||||
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "1")
|
.pathVariable("id", "1")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.build();
|
.build();
|
||||||
Mono<ServerResponse> response = userHandler.deleteUser(request);
|
Mono<ServerResponse> response = userHandler.deleteUser(request);
|
||||||
|
|
||||||
@@ -379,10 +386,14 @@ class SysUserHandlerTest {
|
|||||||
updateRequest.setRoleId(2L);
|
updateRequest.setRoleId(2L);
|
||||||
updateRequest.setStatus(0);
|
updateRequest.setStatus(0);
|
||||||
|
|
||||||
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
|
when(userService.findById(1L)).thenReturn(Mono.just(testUser));
|
||||||
when(userService.updateUser(any(UpdateUserCommand.class))).thenReturn(Mono.just(testUser));
|
when(userService.updateUser(any(UpdateUserCommand.class))).thenReturn(Mono.just(testUser));
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "1")
|
.pathVariable("id", "1")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.body(Mono.just(updateRequest));
|
.body(Mono.just(updateRequest));
|
||||||
Mono<ServerResponse> response = userHandler.updateUser(request);
|
Mono<ServerResponse> response = userHandler.updateUser(request);
|
||||||
|
|
||||||
@@ -399,10 +410,13 @@ class SysUserHandlerTest {
|
|||||||
UserUpdateRequest updateRequest = new UserUpdateRequest();
|
UserUpdateRequest updateRequest = new UserUpdateRequest();
|
||||||
updateRequest.setEmail("updated@example.com");
|
updateRequest.setEmail("updated@example.com");
|
||||||
|
|
||||||
when(userService.updateUser(any(UpdateUserCommand.class))).thenReturn(Mono.empty());
|
when(authUtil.getMemberIdOrThrow(any())).thenReturn(1L);
|
||||||
|
when(userService.verifyPassword(1L, "password123")).thenReturn(Mono.just(true));
|
||||||
|
when(userService.findById(999L)).thenReturn(Mono.empty());
|
||||||
|
|
||||||
ServerRequest request = MockServerRequest.builder()
|
ServerRequest request = MockServerRequest.builder()
|
||||||
.pathVariable("id", "999")
|
.pathVariable("id", "999")
|
||||||
|
.queryParam("adminPassword", "password123")
|
||||||
.body(Mono.just(updateRequest));
|
.body(Mono.just(updateRequest));
|
||||||
Mono<ServerResponse> response = userHandler.updateUser(request);
|
Mono<ServerResponse> response = userHandler.updateUser(request);
|
||||||
|
|
||||||
@@ -411,7 +425,7 @@ class SysUserHandlerTest {
|
|||||||
serverResponse.statusCode() == HttpStatus.NOT_FOUND)
|
serverResponse.statusCode() == HttpStatus.NOT_FOUND)
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
|
|
||||||
verify(userService).updateUser(any(UpdateUserCommand.class));
|
verify(userService).findById(999L);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -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')
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user