移除流程中的支付相关和会员卡相关
This commit was merged in pull request #48.
This commit is contained in:
@@ -94,11 +94,20 @@
|
||||
<version>3.5.3</version>
|
||||
</dependency>
|
||||
<!-- 阿里云OSS SDK -->
|
||||
<!--
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>3.17.4</version>
|
||||
</dependency>
|
||||
-->
|
||||
|
||||
<!-- 文件管理模块(统一文件存储) -->
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-file</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+2
@@ -161,6 +161,7 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
entity.setCoverImage(row.get("cover_image", String.class));
|
||||
entity.setDescription(row.get("description", String.class));
|
||||
entity.setStoredValueAmount(row.get("stored_value_amount", java.math.BigDecimal.class));
|
||||
entity.setQrCodePath(row.get("qr_code_path", String.class));
|
||||
entity.setCreateBy(row.get("create_by", String.class));
|
||||
entity.setUpdateBy(row.get("update_by", String.class));
|
||||
entity.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||
@@ -283,6 +284,7 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
entity.setCoverImage(row.get("cover_image", String.class));
|
||||
entity.setDescription(row.get("description", String.class));
|
||||
entity.setStoredValueAmount(row.get("stored_value_amount", java.math.BigDecimal.class));
|
||||
entity.setQrCodePath(row.get("qr_code_path", String.class));
|
||||
entity.setCreateBy(row.get("create_by", String.class));
|
||||
entity.setUpdateBy(row.get("update_by", String.class));
|
||||
entity.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||
|
||||
+27
-57
@@ -2,7 +2,6 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||
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.tags.Tag;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -24,12 +23,9 @@ import java.util.Map;
|
||||
public class GroupCourseBookingHandler {
|
||||
|
||||
private final IGroupCourseBookingService bookingService;
|
||||
private final IMemberStoredCardService memberStoredCardService;
|
||||
|
||||
public GroupCourseBookingHandler(IGroupCourseBookingService bookingService,
|
||||
IMemberStoredCardService memberStoredCardService) {
|
||||
public GroupCourseBookingHandler(IGroupCourseBookingService bookingService) {
|
||||
this.bookingService = bookingService;
|
||||
this.memberStoredCardService = memberStoredCardService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,38 +42,23 @@ public class GroupCourseBookingHandler {
|
||||
if (body.get("memberId") == null) {
|
||||
return buildErrorResponse("请提供会员ID");
|
||||
}
|
||||
if (body.get("memberCardRecordId") == null) {
|
||||
return buildErrorResponse("请提供会员卡记录ID");
|
||||
}
|
||||
if (body.get("payPassword") == null || body.get("payPassword").toString().isEmpty()) {
|
||||
return buildErrorResponse("请输入支付密码");
|
||||
}
|
||||
|
||||
Long courseId = toLong(body.get("courseId"), "courseId");
|
||||
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||
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)
|
||||
.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 -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
return bookingService.bookCourse(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 -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -92,31 +73,20 @@ public class GroupCourseBookingHandler {
|
||||
return request.bodyToMono(Map.class)
|
||||
.flatMap(body -> {
|
||||
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)
|
||||
.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 -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
return bookingService.cancelBooking(bookingId, 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 -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+22
-19
@@ -1,5 +1,6 @@
|
||||
package cn.novalon.gym.manage.groupcourse.initializer;
|
||||
|
||||
import cn.novalon.gym.manage.file.core.service.ISysFileService;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.util.QRCodeUtil;
|
||||
@@ -10,15 +11,12 @@ import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 项目启动时补全缺失的团课二维码
|
||||
* 遍历所有未删除的团课,对qrCodePath为空的课程生成二维码并上传至阿里云OSS
|
||||
* 遍历所有未删除的团课,对qrCodePath为空的课程生成二维码并通过统一文件服务保存
|
||||
*/
|
||||
@Component
|
||||
public class QrCodeInitializer implements CommandLineRunner {
|
||||
@@ -27,11 +25,14 @@ public class QrCodeInitializer implements CommandLineRunner {
|
||||
|
||||
private final IGroupCourseRepository groupCourseRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ISysFileService fileService;
|
||||
|
||||
public QrCodeInitializer(IGroupCourseRepository groupCourseRepository,
|
||||
ObjectMapper objectMapper) {
|
||||
ObjectMapper objectMapper,
|
||||
ISysFileService fileService) {
|
||||
this.groupCourseRepository = groupCourseRepository;
|
||||
this.objectMapper = objectMapper;
|
||||
this.fileService = fileService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -58,20 +59,22 @@ public class QrCodeInitializer implements CommandLineRunner {
|
||||
|
||||
String jsonContent = objectMapper.writeValueAsString(qrCodeContent);
|
||||
|
||||
// 生成二维码并上传到阿里云OSS
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
|
||||
String fileName = "qr_" + uuid + "_" + timestamp + ".png";
|
||||
String ossUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent, fileName);
|
||||
|
||||
course.setQrCodePath(ossUrl);
|
||||
|
||||
// 更新数据库
|
||||
return groupCourseRepository.update(course)
|
||||
.doOnSuccess(updated -> logger.info("团课二维码补全成功 - id={}, name={}, ossUrl={}",
|
||||
updated.getId(), updated.getCourseName(), ossUrl))
|
||||
.doOnError(error -> logger.error("团课二维码补全失败(更新DB) - id={}, name={}, error: {}",
|
||||
course.getId(), course.getCourseName(), error.getMessage()));
|
||||
// 生成二维码字节数组,通过统一文件服务保存
|
||||
return Mono.fromCallable(() -> QRCodeUtil.generateQrCodeBytes(jsonContent))
|
||||
.flatMap(qrCodeBytes -> {
|
||||
String fileName = "qrcode_" + course.getId() + ".png";
|
||||
return fileService.saveBytes(qrCodeBytes, fileName, "image/png", "system");
|
||||
})
|
||||
.flatMap(sysFile -> {
|
||||
String qrCodeUrl = "/api/files/" + sysFile.getId() + "/preview";
|
||||
course.setQrCodePath(qrCodeUrl);
|
||||
|
||||
return groupCourseRepository.update(course)
|
||||
.doOnSuccess(updated -> logger.info("团课二维码补全成功 - id={}, name={}, url={}",
|
||||
updated.getId(), updated.getCourseName(), qrCodeUrl))
|
||||
.doOnError(error -> logger.error("团课二维码补全失败(更新DB) - id={}, name={}, error: {}",
|
||||
course.getId(), course.getCourseName(), error.getMessage()));
|
||||
});
|
||||
} catch (Exception e) {
|
||||
logger.error("团课二维码补全失败(生成) - id={}, name={}, error: {}",
|
||||
course.getId(), course.getCourseName(), e.getMessage(), e);
|
||||
|
||||
+1
-2
@@ -17,10 +17,9 @@ public interface IGroupCourseBookingService {
|
||||
*
|
||||
* @param courseId 团课ID
|
||||
* @param memberId 会员ID
|
||||
* @param memberCardRecordId 会员卡记录ID
|
||||
* @return 预约记录
|
||||
*/
|
||||
Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId, Long memberCardRecordId);
|
||||
Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId);
|
||||
|
||||
/**
|
||||
* 取消预约
|
||||
|
||||
+91
-112
@@ -3,7 +3,6 @@ package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||
import cn.novalon.gym.manage.groupcourse.event.BookingReminderEventPublisher;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.BookingSagaHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||
@@ -13,7 +12,6 @@ import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
@@ -26,7 +24,6 @@ import java.util.UUID;
|
||||
* - 取消预约需在课程开始前至少2小时
|
||||
* - 每节课最多20人
|
||||
* - 预约成功后发送提醒
|
||||
* - 预约成功后扣减权益
|
||||
*
|
||||
* 技术要点:
|
||||
* - 使用Redis缓存团课信息
|
||||
@@ -45,7 +42,6 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
private final IGroupCourseRepository courseRepository;
|
||||
private final GroupCourseRedisService redisService;
|
||||
private final BookingReminderEventPublisher bookingReminderEventPublisher;
|
||||
private final BookingSagaHandler bookingSagaHandler;
|
||||
|
||||
// 预约提前时间限制(分钟)
|
||||
private static final long BOOKING_MIN_ADVANCE_MINUTES = 30;
|
||||
@@ -55,18 +51,16 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
public GroupCourseBookingService(IGroupCourseBookingRepository bookingRepository,
|
||||
IGroupCourseRepository courseRepository,
|
||||
GroupCourseRedisService redisService,
|
||||
BookingReminderEventPublisher bookingReminderEventPublisher,
|
||||
BookingSagaHandler bookingSagaHandler) {
|
||||
BookingReminderEventPublisher bookingReminderEventPublisher) {
|
||||
this.bookingRepository = bookingRepository;
|
||||
this.courseRepository = courseRepository;
|
||||
this.redisService = redisService;
|
||||
this.bookingReminderEventPublisher = bookingReminderEventPublisher;
|
||||
this.bookingSagaHandler = bookingSagaHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId, Long memberCardRecordId) {
|
||||
logger.info("开始预约团课:courseId={}, memberId={}, memberCardRecordId={}", courseId, memberId, memberCardRecordId);
|
||||
public Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId) {
|
||||
logger.info("开始预约团课:courseId={}, memberId={}", courseId, memberId);
|
||||
|
||||
// 生成唯一请求ID用于分布式锁
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
@@ -82,14 +76,14 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
return getCourseWithCache(courseId)
|
||||
.flatMap(course -> {
|
||||
// 3. 验证课程状态
|
||||
Long status = course.getStatus();
|
||||
if (status == null || status != 0L) {
|
||||
Long courseStatus = course.getStatus();
|
||||
if (courseStatus == null || courseStatus != 0L) {
|
||||
String errorMessage;
|
||||
if (status == null) {
|
||||
if (courseStatus == null) {
|
||||
errorMessage = "课程状态异常";
|
||||
} else if (status == 1L) {
|
||||
} else if (courseStatus == 1L) {
|
||||
errorMessage = "课程已取消,无法预约";
|
||||
} else if (status == 2L) {
|
||||
} else if (courseStatus == 2L) {
|
||||
errorMessage = "课程已结束,无法预约";
|
||||
} else {
|
||||
errorMessage = "课程状态不可预约";
|
||||
@@ -132,57 +126,61 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
|
||||
// 7. 验证是否已预约
|
||||
return bookingRepository.findValidBooking(courseId, memberId)
|
||||
.flatMap(existingBooking -> {
|
||||
return releaseLockAndError(courseId, requestId, "您已预约该课程");
|
||||
})
|
||||
.flatMap(existingBooking ->
|
||||
releaseLockAndError(courseId, requestId, "您已预约该课程")
|
||||
)
|
||||
.switchIfEmpty(
|
||||
// 8. 使用Redis原子操作验证课程人数是否已满
|
||||
validateAndIncrementBookingCount(courseId, course.getMaxMembers())
|
||||
.flatMap(countValid -> {
|
||||
if (countValid > course.getMaxMembers()) {
|
||||
return releaseLockAndError(courseId, requestId, "课程已满");
|
||||
}
|
||||
// 8. 创建预约记录
|
||||
Mono.defer(() -> {
|
||||
GroupCourseBooking booking = new GroupCourseBooking();
|
||||
booking.setCourseId(courseId);
|
||||
booking.setMemberId(memberId);
|
||||
booking.setBookingTime(LocalDateTime.now());
|
||||
booking.setStatus("0"); // 0-已预约
|
||||
|
||||
// 9. 创建预约记录
|
||||
GroupCourseBooking booking = new GroupCourseBooking();
|
||||
booking.setCourseId(courseId);
|
||||
booking.setMemberId(memberId);
|
||||
booking.setMemberCardRecordId(memberCardRecordId);
|
||||
booking.setBookingTime(LocalDateTime.now());
|
||||
booking.setStatus("0"); // 0-已预约
|
||||
// 添加课程信息到预约记录
|
||||
booking.setCourseName(course.getCourseName());
|
||||
booking.setCourseStartTime(course.getStartTime());
|
||||
booking.setCourseEndTime(course.getEndTime());
|
||||
booking.setLocation(course.getLocation());
|
||||
|
||||
// 添加课程信息到预约记录
|
||||
booking.setCourseName(course.getCourseName());
|
||||
booking.setCourseStartTime(course.getStartTime());
|
||||
booking.setCourseEndTime(course.getEndTime());
|
||||
booking.setLocation(course.getLocation());
|
||||
|
||||
// 10. 使用Saga事务执行预约(包含权益扣减)
|
||||
BigDecimal courseAmount = course.getStoredValueAmount() != null ? course.getStoredValueAmount() : BigDecimal.ZERO;
|
||||
return bookingSagaHandler.executeBooking(booking, memberCardRecordId, courseAmount)
|
||||
.flatMap(savedBooking -> {
|
||||
// 11. 释放锁
|
||||
return redisService.releaseLock(courseId, requestId)
|
||||
.then(Mono.just(savedBooking));
|
||||
})
|
||||
.doOnSuccess(savedBooking -> {
|
||||
logger.info("预约成功:bookingId={}, courseId={}, memberId={}",
|
||||
savedBooking.getId(), courseId, memberId);
|
||||
// 发布预约成功事件
|
||||
bookingReminderEventPublisher.publishBookingSuccessEvent(
|
||||
savedBooking.getId(),
|
||||
savedBooking.getMemberId(),
|
||||
savedBooking.getCourseName(),
|
||||
savedBooking.getCourseStartTime().toString()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
// 回滚Redis计数
|
||||
redisService.decrementBookingCount(courseId).subscribe();
|
||||
logger.error("预约失败:courseId={}, memberId={}, error={}",
|
||||
courseId, memberId, error.getMessage());
|
||||
});
|
||||
})
|
||||
// 9. 保存预约记录
|
||||
return bookingRepository.save(booking)
|
||||
.flatMap(saved -> {
|
||||
if (saved.getId() == null) {
|
||||
return Mono.error(new RuntimeException("保存预约记录失败"));
|
||||
}
|
||||
// 10. 更新课程当前人数
|
||||
return courseRepository.updateCurrentMembers(courseId, 1)
|
||||
.flatMap(updatedCourse -> {
|
||||
// 11. 更新Redis预约计数
|
||||
return redisService.incrementBookingCount(courseId)
|
||||
.flatMap(count -> {
|
||||
// 12. 释放锁
|
||||
return redisService.releaseLock(courseId, requestId)
|
||||
.then(Mono.just(saved));
|
||||
});
|
||||
})
|
||||
.doOnSuccess(savedBooking -> {
|
||||
logger.info("预约成功:bookingId={}, courseId={}, memberId={}",
|
||||
saved.getId(), courseId, memberId);
|
||||
// 发布预约成功事件
|
||||
bookingReminderEventPublisher.publishBookingSuccessEvent(
|
||||
saved.getId(),
|
||||
saved.getMemberId(),
|
||||
saved.getCourseName(),
|
||||
saved.getCourseStartTime().toString()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
// 失败时回滚Redis计数和课程人数
|
||||
redisService.decrementBookingCount(courseId).subscribe();
|
||||
courseRepository.updateCurrentMembers(courseId, -1).subscribe();
|
||||
logger.error("预约失败:courseId={}, memberId={}, error={}",
|
||||
courseId, memberId, error.getMessage());
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
})
|
||||
@@ -210,29 +208,6 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证并增加预约人数(使用Redis原子操作)
|
||||
*/
|
||||
private Mono<Integer> validateAndIncrementBookingCount(Long courseId, Integer maxMembers) {
|
||||
// 先获取当前Redis中的预约计数
|
||||
return redisService.getBookingCount(courseId)
|
||||
.flatMap(currentCount -> {
|
||||
// 如果Redis中计数为0,可能是首次访问,需要从数据库同步
|
||||
if (currentCount == 0) {
|
||||
// 从数据库查询实际预约人数
|
||||
return bookingRepository.countValidBookings(courseId)
|
||||
.flatMap(dbCount -> {
|
||||
// 将数据库中的实际预约人数同步到Redis
|
||||
return redisService.setBookingCount(courseId, dbCount.intValue())
|
||||
.then(Mono.just(dbCount.intValue()));
|
||||
});
|
||||
}
|
||||
return Mono.just(currentCount);
|
||||
})
|
||||
// 递增预约计数
|
||||
.flatMap(count -> redisService.incrementBookingCount(courseId).map(Long::intValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放锁并返回错误
|
||||
*/
|
||||
@@ -292,33 +267,37 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
"需在课程开始前" + CANCEL_MIN_ADVANCE_HOURS + "小时取消");
|
||||
}
|
||||
|
||||
// 5. 查询课程金额和已取消次数,使用Saga事务执行取消预约
|
||||
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 -> {
|
||||
// 6. 释放锁
|
||||
return redisService.releaseLock(bookingId, requestId)
|
||||
.then(Mono.just(updatedBooking));
|
||||
})
|
||||
.doOnSuccess(updatedBooking -> {
|
||||
logger.info("取消预约成功:bookingId={}, memberId={}", bookingId, memberId);
|
||||
// 发布预约取消事件
|
||||
bookingReminderEventPublisher.publishBookingCancelEvent(
|
||||
updatedBooking.getId(),
|
||||
updatedBooking.getMemberId(),
|
||||
updatedBooking.getCourseName()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
logger.error("取消预约失败:bookingId={}, memberId={}, error={}",
|
||||
bookingId, memberId, error.getMessage());
|
||||
});
|
||||
// 5. 更新预约状态为已取消
|
||||
return bookingRepository.updateStatus(bookingId, "1")
|
||||
.flatMap(rows -> {
|
||||
if (rows == 0) {
|
||||
return Mono.error(new RuntimeException("更新预约状态失败"));
|
||||
}
|
||||
// 6. 减少课程当前人数
|
||||
return courseRepository.updateCurrentMembers(booking.getCourseId(), -1)
|
||||
.flatMap(updatedCourse -> {
|
||||
// 7. 更新Redis预约计数
|
||||
return redisService.decrementBookingCount(booking.getCourseId())
|
||||
.flatMap(count -> {
|
||||
// 8. 释放锁
|
||||
return redisService.releaseLock(bookingId, requestId)
|
||||
.then(bookingRepository.findById(bookingId));
|
||||
});
|
||||
})
|
||||
.doOnSuccess(updatedBooking -> {
|
||||
logger.info("取消预约成功:bookingId={}, memberId={}", bookingId, memberId);
|
||||
// 发布预约取消事件
|
||||
bookingReminderEventPublisher.publishBookingCancelEvent(
|
||||
updatedBooking.getId(),
|
||||
updatedBooking.getMemberId(),
|
||||
updatedBooking.getCourseName()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
logger.error("取消预约失败:bookingId={}, memberId={}, error={}",
|
||||
bookingId, memberId, error.getMessage());
|
||||
});
|
||||
});
|
||||
})
|
||||
.onErrorResume(error -> {
|
||||
redisService.releaseLock(bookingId, requestId).subscribe();
|
||||
|
||||
+28
-33
@@ -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.service.IGroupCourseService;
|
||||
import cn.novalon.gym.manage.groupcourse.util.QRCodeUtil;
|
||||
import cn.novalon.gym.manage.file.core.service.ISysFileService;
|
||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||
@@ -51,6 +52,7 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final GroupCourseStateMachine stateMachine;
|
||||
private final DatabaseClient databaseClient;
|
||||
private final ISysFileService fileService;
|
||||
|
||||
private static final String CACHE_KEY_PREFIX = "group_course:page:";
|
||||
private static final String CACHE_KEY_ID_PREFIX = "group_course:id:";
|
||||
@@ -68,7 +70,8 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
RedisUtil redisUtil,
|
||||
ObjectMapper objectMapper,
|
||||
GroupCourseStateMachine stateMachine,
|
||||
DatabaseClient databaseClient){
|
||||
DatabaseClient databaseClient,
|
||||
ISysFileService fileService){
|
||||
this.groupCourseRepository = groupCourseRepository;
|
||||
this.bookingRepository = bookingRepository;
|
||||
this.groupCourseTypeRepository = groupCourseTypeRepository;
|
||||
@@ -79,6 +82,7 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
this.objectMapper = objectMapper;
|
||||
this.stateMachine = stateMachine;
|
||||
this.databaseClient = databaseClient;
|
||||
this.fileService = fileService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -288,15 +292,21 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
|
||||
String jsonContent = objectMapper.writeValueAsString(qrCodeContent);
|
||||
|
||||
// 生成二维码并上传到阿里云OSS
|
||||
String qrCodeUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent);
|
||||
course.setQrCodePath(qrCodeUrl);
|
||||
|
||||
logger.info("团课二维码上传到OSS成功 - id={}, qrCodeUrl={}", course.getId(), qrCodeUrl);
|
||||
|
||||
// 更新团课信息,保存二维码路径
|
||||
return groupCourseRepository.update(course)
|
||||
.doOnSuccess(updatedCourse -> logger.info("团课创建成功 - id={}, name={}", updatedCourse.getId(), updatedCourse.getCourseName()));
|
||||
// 生成二维码字节数组,通过统一文件服务保存
|
||||
return Mono.fromCallable(() -> QRCodeUtil.generateQrCodeBytes(jsonContent))
|
||||
.flatMap(qrCodeBytes -> {
|
||||
String fileName = "qrcode_" + course.getId() + ".png";
|
||||
return fileService.saveBytes(qrCodeBytes, fileName, "image/png", "system");
|
||||
})
|
||||
.flatMap(sysFile -> {
|
||||
String qrCodeUrl = "/api/files/" + sysFile.getId() + "/preview";
|
||||
course.setQrCodePath(qrCodeUrl);
|
||||
|
||||
logger.info("团课二维码已保存 - id={}, fileId={}, url={}", course.getId(), sysFile.getId(), qrCodeUrl);
|
||||
|
||||
return groupCourseRepository.update(course)
|
||||
.doOnSuccess(updatedCourse -> logger.info("团课创建成功 - id={}, name={}", updatedCourse.getId(), updatedCourse.getCourseName()));
|
||||
});
|
||||
} catch (Exception e) {
|
||||
logger.error("团课二维码生成失败 - id={}, error: {}", course.getId(), e.getMessage(), e);
|
||||
// 即使二维码生成失败,也返回成功创建的团课
|
||||
@@ -504,29 +514,14 @@ public class GroupCourseService implements IGroupCourseService {
|
||||
return Mono.error(new RuntimeException("课程已满员,无法签到"));
|
||||
}
|
||||
|
||||
// 校验5:用户今日是否已到店签到(直接查询sign_in_record表)
|
||||
LocalDateTime todayStart = LocalDateTime.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 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()
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("请先完成到店签到")))
|
||||
.flatMap(status -> {
|
||||
if (!"SUCCESS".equals(status)) {
|
||||
return Mono.error(new RuntimeException("到店签到未成功,请重新签到"));
|
||||
}
|
||||
// 校验6:用户已预约此课程(有效预约,状态为0-已预约)
|
||||
return bookingRepository.findValidBooking(courseId, memberId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("您未预约此课程,无法签到")))
|
||||
.flatMap(booking -> {
|
||||
return groupCourseRepository.updateCurrentMembers(courseId, 1)
|
||||
.flatMap(updatedCourse -> {
|
||||
return bookingRepository.updateStatus(booking.getId(), "2")
|
||||
.thenReturn(updatedCourse);
|
||||
});
|
||||
// 校验5:用户已预约此课程(有效预约,状态为0-已预约)
|
||||
return bookingRepository.findValidBooking(courseId, memberId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("您未预约此团课")))
|
||||
.flatMap(booking -> {
|
||||
return groupCourseRepository.updateCurrentMembers(courseId, 1)
|
||||
.flatMap(updatedCourse -> {
|
||||
return bookingRepository.updateStatus(booking.getId(), "2")
|
||||
.thenReturn(updatedCourse);
|
||||
});
|
||||
});
|
||||
})
|
||||
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
package cn.novalon.gym.manage.groupcourse.util;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 阿里云OSS工具类
|
||||
*/
|
||||
public class OSSUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
|
||||
|
||||
// OSS配置信息
|
||||
private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
|
||||
private static final String ACCESS_KEY_ID = "LTAI5t9TFh9Vayeahz45kZjg";
|
||||
private static final String ACCESS_KEY_SECRET = "zD6NlCeH5UhjBs4vnQVqn8Ksi3CaZz";
|
||||
private static final String BUCKET_NAME = "ycc-filesaver";
|
||||
|
||||
// OSS访问地址前缀
|
||||
private static final String OSS_URL_PREFIX = "https://" + BUCKET_NAME + "." + ENDPOINT + "/";
|
||||
|
||||
// 文件存储目录
|
||||
private static final String QRCODE_DIR = "qrcode/";
|
||||
|
||||
/**
|
||||
* 上传文件到阿里云OSS
|
||||
*
|
||||
* @param localFilePath 本地文件路径
|
||||
* @param fileName 文件名(不含路径)
|
||||
* @return OSS访问地址
|
||||
*/
|
||||
public static String uploadToOSS(String localFilePath, String fileName) {
|
||||
OSS ossClient = null;
|
||||
try {
|
||||
// 创建OSS客户端
|
||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||
|
||||
// 构建OSS文件路径:qrcode/2026/06/18/xxx.png
|
||||
String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
||||
String ossFilePath = QRCODE_DIR + datePath + "/" + fileName;
|
||||
|
||||
// 创建上传请求
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||
|
||||
// 上传文件
|
||||
ossClient.putObject(putObjectRequest);
|
||||
|
||||
// 构建访问地址
|
||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
||||
|
||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
||||
|
||||
return accessUrl;
|
||||
} catch (Exception e) {
|
||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (ossClient != null) {
|
||||
ossClient.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到阿里云OSS(自定义存储路径)
|
||||
*
|
||||
* @param localFilePath 本地文件路径
|
||||
* @param ossDirectory OSS存储目录
|
||||
* @param fileName 文件名(不含路径)
|
||||
* @return OSS访问地址
|
||||
*/
|
||||
public static String uploadToOSS(String localFilePath, String ossDirectory, String fileName) {
|
||||
OSS ossClient = null;
|
||||
try {
|
||||
// 创建OSS客户端
|
||||
ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
|
||||
|
||||
// 构建OSS文件路径
|
||||
String ossFilePath = ossDirectory + fileName;
|
||||
|
||||
// 创建上传请求
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossFilePath, new File(localFilePath));
|
||||
|
||||
// 上传文件
|
||||
ossClient.putObject(putObjectRequest);
|
||||
|
||||
// 构建访问地址
|
||||
String accessUrl = OSS_URL_PREFIX + ossFilePath;
|
||||
|
||||
logger.info("文件上传到OSS成功: localPath={}, ossUrl={}", localFilePath, accessUrl);
|
||||
|
||||
return accessUrl;
|
||||
} catch (Exception e) {
|
||||
logger.error("文件上传到OSS失败 - localPath: {}, error: {}", localFilePath, e.getMessage(), e);
|
||||
throw new RuntimeException("文件上传到OSS失败: " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (ossClient != null) {
|
||||
ossClient.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-107
@@ -10,46 +10,33 @@ import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 二维码生成工具类
|
||||
* 生成二维码的字节数组,由调用方统一通过文件服务保存
|
||||
*/
|
||||
public class QRCodeUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
|
||||
|
||||
// 二维码默认保存路径(本地临时路径)
|
||||
private static final String DEFAULT_SAVE_PATH = "D:\\Games\\exmp\\image";
|
||||
|
||||
// 二维码尺寸
|
||||
private static final int QR_CODE_WIDTH = 300;
|
||||
private static final int QR_CODE_HEIGHT = 300;
|
||||
|
||||
/**
|
||||
* 生成二维码并保存到指定路径
|
||||
* 生成二维码图片的字节数组
|
||||
*
|
||||
* @param content 二维码内容
|
||||
* @param savePath 保存路径
|
||||
* @param fileName 文件名(不含扩展名)
|
||||
* @return 生成的二维码文件完整路径
|
||||
* @return PNG格式的二维码图片字节数组
|
||||
*/
|
||||
public static String generateQRCode(String content, String savePath, String fileName) {
|
||||
public static byte[] generateQrCodeBytes(String content) {
|
||||
try {
|
||||
Path directory = Paths.get(savePath);
|
||||
if (!Files.exists(directory)) {
|
||||
Files.createDirectories(directory);
|
||||
logger.info("创建二维码保存目录: {}", savePath);
|
||||
}
|
||||
|
||||
Map<EncodeHintType, Object> hints = new HashMap<>();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
|
||||
@@ -58,99 +45,21 @@ public class QRCodeUtil {
|
||||
QRCodeWriter qrCodeWriter = new QRCodeWriter();
|
||||
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_WIDTH, QR_CODE_HEIGHT, hints);
|
||||
|
||||
String filePath = Paths.get(savePath, fileName + ".png").toString();
|
||||
Path path = Paths.get(filePath);
|
||||
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
|
||||
|
||||
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
|
||||
logger.info("二维码生成成功: {}", filePath);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "PNG", baos);
|
||||
byte[] bytes = baos.toByteArray();
|
||||
baos.close();
|
||||
|
||||
return filePath;
|
||||
logger.info("二维码字节数组生成成功, size={} bytes", bytes.length);
|
||||
return bytes;
|
||||
} catch (WriterException e) {
|
||||
logger.error("二维码生成失败 - WriterException: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("二维码生成失败: " + e.getMessage(), e);
|
||||
} catch (IOException e) {
|
||||
logger.error("二维码保存失败 - IOException: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("二维码保存失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码并保存到默认路径
|
||||
* 文件名格式: UUID + 创建时间
|
||||
*
|
||||
* @param content 二维码内容
|
||||
* @return 生成的二维码文件完整路径
|
||||
*/
|
||||
public static String generateQRCode(String content) {
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
|
||||
String fileName = uuid + "_" + timestamp;
|
||||
|
||||
return generateQRCode(content, DEFAULT_SAVE_PATH, fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码并保存到默认路径,使用自定义文件名
|
||||
*
|
||||
* @param content 二维码内容
|
||||
* @param fileName 文件名(不含扩展名)
|
||||
* @return 生成的二维码文件完整路径
|
||||
*/
|
||||
public static String generateQRCodeWithFileName(String content, String fileName) {
|
||||
return generateQRCode(content, DEFAULT_SAVE_PATH, fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码并上传到阿里云OSS
|
||||
* 文件名格式: UUID + 创建时间
|
||||
*
|
||||
* @param content 二维码内容
|
||||
* @return 阿里云OSS访问地址
|
||||
*/
|
||||
public static String generateQRCodeAndUploadToOSS(String content) {
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
|
||||
String fileName = uuid + "_" + timestamp + ".png";
|
||||
|
||||
return generateQRCodeAndUploadToOSS(content, fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码并上传到阿里云OSS
|
||||
*
|
||||
* @param content 二维码内容
|
||||
* @param fileName 文件名(含扩展名)
|
||||
* @return 阿里云OSS访问地址
|
||||
*/
|
||||
public static String generateQRCodeAndUploadToOSS(String content, String fileName) {
|
||||
try {
|
||||
Path tempDir = Files.createTempDirectory("qrcode_temp");
|
||||
String tempFilePath = tempDir.resolve(fileName).toString();
|
||||
|
||||
Map<EncodeHintType, Object> hints = new HashMap<>();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
|
||||
hints.put(EncodeHintType.MARGIN, 1);
|
||||
|
||||
QRCodeWriter qrCodeWriter = new QRCodeWriter();
|
||||
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_WIDTH, QR_CODE_HEIGHT, hints);
|
||||
|
||||
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(tempFilePath));
|
||||
logger.info("二维码临时文件生成成功: {}", tempFilePath);
|
||||
|
||||
String ossUrl = OSSUtil.uploadToOSS(tempFilePath, fileName);
|
||||
|
||||
Files.deleteIfExists(Paths.get(tempFilePath));
|
||||
Files.deleteIfExists(tempDir);
|
||||
logger.info("临时文件已删除: {}", tempFilePath);
|
||||
|
||||
return ossUrl;
|
||||
} catch (WriterException e) {
|
||||
logger.error("二维码生成失败 - WriterException: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("二维码生成失败: " + e.getMessage(), e);
|
||||
} catch (IOException e) {
|
||||
logger.error("二维码处理失败 - IOException: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("二维码处理失败: " + e.getMessage(), e);
|
||||
logger.error("二维码输出失败 - IOException: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("二维码输出失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-43
@@ -1,9 +1,6 @@
|
||||
package cn.novalon.gym.manage.groupcourse.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -12,60 +9,41 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
*/
|
||||
class QRCodeUtilTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void testGenerateQRCode() {
|
||||
void testGenerateQrCodeBytes() {
|
||||
String content = "测试二维码内容";
|
||||
String qrCodePath = QRCodeUtil.generateQRCode(content);
|
||||
byte[] bytes = QRCodeUtil.generateQrCodeBytes(content);
|
||||
|
||||
assertNotNull(qrCodePath, "二维码路径不应为空");
|
||||
assertTrue(qrCodePath.endsWith(".png"), "二维码文件应为PNG格式");
|
||||
assertTrue(qrCodePath.contains("D:\\Games\\exmp\\image"), "二维码应保存到指定路径");
|
||||
assertNotNull(bytes, "二维码字节数组不应为空");
|
||||
assertTrue(bytes.length > 0, "二维码字节数组应包含数据");
|
||||
|
||||
System.out.println("生成的二维码路径: " + qrCodePath);
|
||||
System.out.println("生成的二维码字节大小: " + bytes.length + " bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGenerateQRCodeWithCustomPath() {
|
||||
String content = "自定义路径测试";
|
||||
String customPath = tempDir.toString();
|
||||
String fileName = "test_qrcode";
|
||||
void testGenerateQrCodeBytesWithJsonContent() {
|
||||
String jsonContent = "{\"id\":1,\"courseName\":\"瑜伽课\",\"coachId\":100,\"startTime\":\"2026-07-14T10:00:00\"}";
|
||||
|
||||
String qrCodePath = QRCodeUtil.generateQRCode(content, customPath, fileName);
|
||||
byte[] bytes = QRCodeUtil.generateQrCodeBytes(jsonContent);
|
||||
|
||||
assertNotNull(qrCodePath, "二维码路径不应为空");
|
||||
assertTrue(qrCodePath.endsWith(".png"), "二维码文件应为PNG格式");
|
||||
assertTrue(qrCodePath.contains(fileName), "二维码文件名应包含指定名称");
|
||||
assertNotNull(bytes, "二维码字节数组不应为空");
|
||||
assertTrue(bytes.length > 0, "二维码字节数组应包含数据");
|
||||
|
||||
System.out.println("生成的二维码路径: " + qrCodePath);
|
||||
System.out.println("JSON内容二维码字节大小: " + bytes.length + " bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGenerateQRCodeWithJsonContent() {
|
||||
String jsonContent = "{\"id\":1,\"courseName\":\"瑜伽课\",\"coachId\":100,\"startTime\":\"2026-06-18T10:00:00\"}";
|
||||
void testGenerateQrCodeBytesWithLongContent() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
sb.append("这是第").append(i).append("行测试数据\n");
|
||||
}
|
||||
|
||||
String qrCodePath = QRCodeUtil.generateQRCode(jsonContent);
|
||||
byte[] bytes = QRCodeUtil.generateQrCodeBytes(sb.toString());
|
||||
|
||||
assertNotNull(qrCodePath, "二维码路径不应为空");
|
||||
assertTrue(qrCodePath.endsWith(".png"), "二维码文件应为PNG格式");
|
||||
assertNotNull(bytes, "二维码字节数组不应为空");
|
||||
assertTrue(bytes.length > 0, "长内容二维码应正常生成");
|
||||
|
||||
System.out.println("JSON内容二维码路径: " + qrCodePath);
|
||||
System.out.println("长内容二维码字节大小: " + bytes.length + " bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGenerateQRCodeAndUploadToOSS() {
|
||||
String jsonContent = "{\"id\":1,\"courseName\":\"瑜伽课\",\"coachId\":100,\"startTime\":\"2026-06-18T10:00:00\"}";
|
||||
|
||||
String ossUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent);
|
||||
|
||||
assertNotNull(ossUrl, "OSS访问地址不应为空");
|
||||
assertTrue(ossUrl.startsWith("https://"), "OSS访问地址应为HTTPS");
|
||||
assertTrue(ossUrl.contains("ycc-filesaver.oss-cn-beijing.aliyuncs.com"), "OSS访问地址应包含正确的域名");
|
||||
assertTrue(ossUrl.contains("/qrcode/"), "OSS访问地址应包含qrcode目录");
|
||||
assertTrue(ossUrl.endsWith(".png"), "OSS访问地址应为PNG格式");
|
||||
|
||||
System.out.println("上传到OSS的二维码地址: " + ossUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user