完成模块4,4.1基础数据统计的部分功能
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
|
||||
@@ -0,0 +1,101 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-manage-api</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-dataCount</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>gym-dataCount</name>
|
||||
<description>Data Statistics Module</description>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-common</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-db</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-annotations-jakarta</artifactId>
|
||||
<version>2.2.43</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Redis依赖-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 会员模块依赖 -->
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-member</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 团课模块依赖 -->
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-groupCourse</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package cn.novalon.gym.manage.datacount;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = "cn.novalon.gym.manage", exclude = {
|
||||
ReactiveUserDetailsServiceAutoConfiguration.class })
|
||||
@EnableR2dbcRepositories(basePackages = {
|
||||
"cn.novalon.gym.manage.db.dao",
|
||||
"cn.novalon.gym.manage.member.repository",
|
||||
"cn.novalon.gym.manage.groupcourse.dao",
|
||||
"cn.novalon.gym.manage.datacount.dao"
|
||||
})
|
||||
@ComponentScan(basePackages = "cn.novalon.gym.manage")
|
||||
public class GymDataCountApplication {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(GymDataCountApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
logger.info("数据统计模块启动中...");
|
||||
SpringApplication.run(GymDataCountApplication.class, args);
|
||||
logger.info("数据统计模块启动完成");
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package cn.novalon.gym.manage.datacount.config;
|
||||
|
||||
import cn.novalon.gym.manage.datacount.handler.DataCountHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
|
||||
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
|
||||
|
||||
@Configuration
|
||||
public class DataCountRouter {
|
||||
|
||||
@Bean
|
||||
public RouterFunction<ServerResponse> dataCountRoutes(DataCountHandler dataCountHandler) {
|
||||
return route()
|
||||
// ========== 会员数据统计路由 ==========
|
||||
.GET("/api/stats/member/date/{date}", dataCountHandler::getMemberStatisticsByDate)
|
||||
.GET("/api/stats/member/range", dataCountHandler::getMemberStatisticsByDateRange)
|
||||
.GET("/api/stats/member/summary", dataCountHandler::getMemberStatisticsSummary)
|
||||
|
||||
// ========== 预约数据统计路由 ==========
|
||||
.GET("/api/stats/booking/date/{date}", dataCountHandler::getBookingStatisticsByDate)
|
||||
.GET("/api/stats/booking/range", dataCountHandler::getBookingStatisticsByDateRange)
|
||||
.GET("/api/stats/booking/summary", dataCountHandler::getBookingStatisticsSummary)
|
||||
|
||||
// ========== 数据导出路由 ==========
|
||||
.GET("/api/stats/export/member", dataCountHandler::exportMemberStatistics)
|
||||
.GET("/api/stats/export/booking", dataCountHandler::exportBookingStatistics)
|
||||
.GET("/api/stats/export/all", dataCountHandler::exportAllStatistics)
|
||||
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package cn.novalon.gym.manage.datacount.dao;
|
||||
|
||||
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.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 统计数据访问层
|
||||
* 使用 R2dbcEntityTemplate 执行原生SQL查询
|
||||
*
|
||||
* @author 数据统计模块
|
||||
* @date 2026-06-06
|
||||
*/
|
||||
@Repository
|
||||
public class StatisticsDao {
|
||||
|
||||
private final R2dbcEntityTemplate r2dbcEntityTemplate;
|
||||
|
||||
public StatisticsDao(R2dbcEntityTemplate r2dbcEntityTemplate) {
|
||||
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
|
||||
}
|
||||
|
||||
// ========== 会员数据统计 ==========
|
||||
|
||||
public Mono<Integer> countTotalMembers() {
|
||||
String sql = "SELECT COUNT(*) FROM member_user WHERE is_deleted = FALSE";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countNewMembersByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(*) FROM member_user WHERE is_deleted = FALSE AND DATE(created_at) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countActiveMembersByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(DISTINCT m.id) FROM member_user m LEFT JOIN member_card_record r ON m.id = r.member_id WHERE m.is_deleted = FALSE AND r.deleted_at IS NULL AND DATE(r.created_at) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countMaleMembers() {
|
||||
String sql = "SELECT COUNT(*) FROM member_user WHERE is_deleted = FALSE AND gender = 1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countFemaleMembers() {
|
||||
String sql = "SELECT COUNT(*) FROM member_user WHERE is_deleted = FALSE AND gender = 2";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countCardPurchaseByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(DISTINCT r.member_id) FROM member_card_record r WHERE r.deleted_at IS NULL AND DATE(r.created_at) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Double> calculateAverageAge() {
|
||||
String sql = "SELECT AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, birthday))) FROM member_user WHERE is_deleted = FALSE AND birthday IS NOT NULL";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.map(row -> row.get(0, Double.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countActiveMembersByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
String sql = "SELECT COUNT(*) FROM member_user WHERE is_deleted = FALSE AND last_login_at >= $1 AND last_login_at < $2";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, startTime)
|
||||
.bind(1, endTime)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
// ========== 预约数据统计 ==========
|
||||
|
||||
public Mono<Integer> countTotalBookingsByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(*) FROM group_course_booking WHERE deleted_at IS NULL AND DATE(created_at) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countCancelledBookingsByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(*) FROM group_course_booking WHERE deleted_at IS NULL AND status = '1' AND DATE(cancel_time) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countAttendedBookingsByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(*) FROM group_course_booking WHERE deleted_at IS NULL AND status = '2' AND DATE(created_at) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countTotalCoursesByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(*) FROM group_course WHERE deleted_at IS NULL AND DATE(start_time) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Integer> countFullCoursesByDate(LocalDate date) {
|
||||
String sql = "SELECT COUNT(*) FROM group_course WHERE deleted_at IS NULL AND current_members = max_members AND DATE(start_time) = $1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> row.get(0, Integer.class))
|
||||
.one();
|
||||
}
|
||||
|
||||
public Mono<Object[]> findMostPopularCourseByDate(LocalDate date) {
|
||||
String sql = "SELECT c.course_name, COUNT(b.id) as booking_count FROM group_course_booking b LEFT JOIN group_course c ON b.course_id = c.id WHERE b.deleted_at IS NULL AND c.deleted_at IS NULL AND DATE(b.created_at) = $1 GROUP BY c.id, c.course_name ORDER BY booking_count DESC LIMIT 1";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, date)
|
||||
.map(row -> new Object[]{row.get(0, String.class), row.get(1, Integer.class)})
|
||||
.one();
|
||||
}
|
||||
|
||||
// ========== 日期范围查询 ==========
|
||||
|
||||
public Flux<Object[]> findMemberStatisticsByDateRange(LocalDate startDate, LocalDate endDate) {
|
||||
String sql = "SELECT DATE(m.created_at) as date, COUNT(*) as new_members FROM member_user m WHERE m.is_deleted = FALSE AND DATE(m.created_at) BETWEEN $1 AND $2 GROUP BY DATE(m.created_at) ORDER BY date";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, startDate)
|
||||
.bind(1, endDate)
|
||||
.map(row -> new Object[]{row.get(0, LocalDate.class), row.get(1, Integer.class)})
|
||||
.all();
|
||||
}
|
||||
|
||||
public Flux<Object[]> findBookingStatisticsByDateRange(LocalDate startDate, LocalDate endDate) {
|
||||
String sql = "SELECT DATE(b.created_at) as date, COUNT(*) as total_bookings, SUM(CASE WHEN b.status = '1' THEN 1 ELSE 0 END) as cancelled_bookings, SUM(CASE WHEN b.status = '2' THEN 1 ELSE 0 END) as attended_bookings FROM group_course_booking b WHERE b.deleted_at IS NULL AND DATE(b.created_at) BETWEEN $1 AND $2 GROUP BY DATE(b.created_at) ORDER BY date";
|
||||
return r2dbcEntityTemplate.getDatabaseClient()
|
||||
.sql(sql)
|
||||
.bind(0, startDate)
|
||||
.bind(1, endDate)
|
||||
.map(row -> new Object[]{row.get(0, LocalDate.class), row.get(1, Integer.class), row.get(2, Integer.class), row.get(3, Integer.class)})
|
||||
.all();
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package cn.novalon.gym.manage.datacount.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Schema(description = "预约数据统计")
|
||||
public class BookingStatistics {
|
||||
|
||||
@Schema(description = "统计日期", example = "2026-01-01")
|
||||
private LocalDate date;
|
||||
|
||||
@Schema(description = "预约总数", example = "100")
|
||||
private Integer totalBookings;
|
||||
|
||||
@Schema(description = "取消预约数", example = "10")
|
||||
private Integer cancelledBookings;
|
||||
|
||||
@Schema(description = "实际到场数", example = "85")
|
||||
private Integer attendedBookings;
|
||||
|
||||
@Schema(description = "预约成功率", example = "0.85")
|
||||
private Double bookingSuccessRate;
|
||||
|
||||
@Schema(description = "取消率", example = "0.10")
|
||||
private Double cancellationRate;
|
||||
|
||||
@Schema(description = "到场率", example = "0.85")
|
||||
private Double attendanceRate;
|
||||
|
||||
@Schema(description = "热门课程名称", example = "动感单车")
|
||||
private String popularCourseName;
|
||||
|
||||
@Schema(description = "热门课程预约数", example = "25")
|
||||
private Integer popularCourseCount;
|
||||
|
||||
@Schema(description = "团课总数", example = "20")
|
||||
private Integer totalCourses;
|
||||
|
||||
@Schema(description = "满员课程数", example = "5")
|
||||
private Integer fullCourses;
|
||||
|
||||
@Schema(description = "开始日期(用于汇总统计)")
|
||||
private LocalDate startDate;
|
||||
|
||||
@Schema(description = "结束日期(用于汇总统计)")
|
||||
private LocalDate endDate;
|
||||
|
||||
public BookingStatistics() {
|
||||
}
|
||||
|
||||
public BookingStatistics(LocalDate date) {
|
||||
this.date = date;
|
||||
this.totalBookings = 0;
|
||||
this.cancelledBookings = 0;
|
||||
this.attendedBookings = 0;
|
||||
this.bookingSuccessRate = 0.0;
|
||||
this.cancellationRate = 0.0;
|
||||
this.attendanceRate = 0.0;
|
||||
this.popularCourseName = "";
|
||||
this.popularCourseCount = 0;
|
||||
this.totalCourses = 0;
|
||||
this.fullCourses = 0;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(LocalDate date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Integer getTotalBookings() {
|
||||
return totalBookings;
|
||||
}
|
||||
|
||||
public void setTotalBookings(Integer totalBookings) {
|
||||
this.totalBookings = totalBookings;
|
||||
}
|
||||
|
||||
public Integer getCancelledBookings() {
|
||||
return cancelledBookings;
|
||||
}
|
||||
|
||||
public void setCancelledBookings(Integer cancelledBookings) {
|
||||
this.cancelledBookings = cancelledBookings;
|
||||
}
|
||||
|
||||
public Integer getAttendedBookings() {
|
||||
return attendedBookings;
|
||||
}
|
||||
|
||||
public void setAttendedBookings(Integer attendedBookings) {
|
||||
this.attendedBookings = attendedBookings;
|
||||
}
|
||||
|
||||
public Double getBookingSuccessRate() {
|
||||
return bookingSuccessRate;
|
||||
}
|
||||
|
||||
public void setBookingSuccessRate(Double bookingSuccessRate) {
|
||||
this.bookingSuccessRate = bookingSuccessRate;
|
||||
}
|
||||
|
||||
public Double getCancellationRate() {
|
||||
return cancellationRate;
|
||||
}
|
||||
|
||||
public void setCancellationRate(Double cancellationRate) {
|
||||
this.cancellationRate = cancellationRate;
|
||||
}
|
||||
|
||||
public Double getAttendanceRate() {
|
||||
return attendanceRate;
|
||||
}
|
||||
|
||||
public void setAttendanceRate(Double attendanceRate) {
|
||||
this.attendanceRate = attendanceRate;
|
||||
}
|
||||
|
||||
public String getPopularCourseName() {
|
||||
return popularCourseName;
|
||||
}
|
||||
|
||||
public void setPopularCourseName(String popularCourseName) {
|
||||
this.popularCourseName = popularCourseName;
|
||||
}
|
||||
|
||||
public Integer getPopularCourseCount() {
|
||||
return popularCourseCount;
|
||||
}
|
||||
|
||||
public void setPopularCourseCount(Integer popularCourseCount) {
|
||||
this.popularCourseCount = popularCourseCount;
|
||||
}
|
||||
|
||||
public Integer getTotalCourses() {
|
||||
return totalCourses;
|
||||
}
|
||||
|
||||
public void setTotalCourses(Integer totalCourses) {
|
||||
this.totalCourses = totalCourses;
|
||||
}
|
||||
|
||||
public Integer getFullCourses() {
|
||||
return fullCourses;
|
||||
}
|
||||
|
||||
public void setFullCourses(Integer fullCourses) {
|
||||
this.fullCourses = fullCourses;
|
||||
}
|
||||
|
||||
public LocalDate getStartDate() {
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public void setStartDate(LocalDate startDate) {
|
||||
this.startDate = startDate;
|
||||
}
|
||||
|
||||
public LocalDate getEndDate() {
|
||||
return endDate;
|
||||
}
|
||||
|
||||
public void setEndDate(LocalDate endDate) {
|
||||
this.endDate = endDate;
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package cn.novalon.gym.manage.datacount.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Schema(description = "会员数据统计")
|
||||
public class MemberStatistics {
|
||||
|
||||
@Schema(description = "统计日期", example = "2026-01-01")
|
||||
private LocalDate date;
|
||||
|
||||
@Schema(description = "新增会员数", example = "10")
|
||||
private Integer newMembers;
|
||||
|
||||
@Schema(description = "活跃会员数", example = "50")
|
||||
private Integer activeMembers;
|
||||
|
||||
@Schema(description = "留存会员数", example = "45")
|
||||
private Integer retainedMembers;
|
||||
|
||||
@Schema(description = "总会员数", example = "200")
|
||||
private Integer totalMembers;
|
||||
|
||||
@Schema(description = "男性会员数", example = "100")
|
||||
private Integer maleMembers;
|
||||
|
||||
@Schema(description = "女性会员数", example = "100")
|
||||
private Integer femaleMembers;
|
||||
|
||||
@Schema(description = "会员卡购买人数", example = "30")
|
||||
private Integer cardPurchaseCount;
|
||||
|
||||
@Schema(description = "平均年龄", example = "28")
|
||||
private Double averageAge;
|
||||
|
||||
@Schema(description = "开始日期(用于汇总统计)")
|
||||
private LocalDate startDate;
|
||||
|
||||
@Schema(description = "结束日期(用于汇总统计)")
|
||||
private LocalDate endDate;
|
||||
|
||||
public MemberStatistics() {
|
||||
}
|
||||
|
||||
public MemberStatistics(LocalDate date) {
|
||||
this.date = date;
|
||||
this.newMembers = 0;
|
||||
this.activeMembers = 0;
|
||||
this.retainedMembers = 0;
|
||||
this.totalMembers = 0;
|
||||
this.maleMembers = 0;
|
||||
this.femaleMembers = 0;
|
||||
this.cardPurchaseCount = 0;
|
||||
this.averageAge = 0.0;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(LocalDate date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Integer getNewMembers() {
|
||||
return newMembers;
|
||||
}
|
||||
|
||||
public void setNewMembers(Integer newMembers) {
|
||||
this.newMembers = newMembers;
|
||||
}
|
||||
|
||||
public Integer getActiveMembers() {
|
||||
return activeMembers;
|
||||
}
|
||||
|
||||
public void setActiveMembers(Integer activeMembers) {
|
||||
this.activeMembers = activeMembers;
|
||||
}
|
||||
|
||||
public Integer getRetainedMembers() {
|
||||
return retainedMembers;
|
||||
}
|
||||
|
||||
public void setRetainedMembers(Integer retainedMembers) {
|
||||
this.retainedMembers = retainedMembers;
|
||||
}
|
||||
|
||||
public Integer getTotalMembers() {
|
||||
return totalMembers;
|
||||
}
|
||||
|
||||
public void setTotalMembers(Integer totalMembers) {
|
||||
this.totalMembers = totalMembers;
|
||||
}
|
||||
|
||||
public Integer getMaleMembers() {
|
||||
return maleMembers;
|
||||
}
|
||||
|
||||
public void setMaleMembers(Integer maleMembers) {
|
||||
this.maleMembers = maleMembers;
|
||||
}
|
||||
|
||||
public Integer getFemaleMembers() {
|
||||
return femaleMembers;
|
||||
}
|
||||
|
||||
public void setFemaleMembers(Integer femaleMembers) {
|
||||
this.femaleMembers = femaleMembers;
|
||||
}
|
||||
|
||||
public Integer getCardPurchaseCount() {
|
||||
return cardPurchaseCount;
|
||||
}
|
||||
|
||||
public void setCardPurchaseCount(Integer cardPurchaseCount) {
|
||||
this.cardPurchaseCount = cardPurchaseCount;
|
||||
}
|
||||
|
||||
public Double getAverageAge() {
|
||||
return averageAge;
|
||||
}
|
||||
|
||||
public void setAverageAge(Double averageAge) {
|
||||
this.averageAge = averageAge;
|
||||
}
|
||||
|
||||
public LocalDate getStartDate() {
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public void setStartDate(LocalDate startDate) {
|
||||
this.startDate = startDate;
|
||||
}
|
||||
|
||||
public LocalDate getEndDate() {
|
||||
return endDate;
|
||||
}
|
||||
|
||||
public void setEndDate(LocalDate endDate) {
|
||||
this.endDate = endDate;
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package cn.novalon.gym.manage.datacount.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Schema(description = "统计数据导出DTO")
|
||||
public class StatisticsExportDTO {
|
||||
|
||||
@Schema(description = "导出文件名", example = "statistics_report_20260101")
|
||||
private String fileName;
|
||||
|
||||
@Schema(description = "导出格式", example = "EXCEL")
|
||||
private String format;
|
||||
|
||||
@Schema(description = "开始日期", example = "2026-01-01")
|
||||
private LocalDate startDate;
|
||||
|
||||
@Schema(description = "结束日期", example = "2026-01-31")
|
||||
private LocalDate endDate;
|
||||
|
||||
@Schema(description = "导出类型", example = "MEMBER")
|
||||
private String exportType;
|
||||
|
||||
@Schema(description = "会员统计数据")
|
||||
private List<MemberStatistics> memberStatisticsList;
|
||||
|
||||
@Schema(description = "预约统计数据")
|
||||
private List<BookingStatistics> bookingStatisticsList;
|
||||
|
||||
public StatisticsExportDTO() {
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public void setFileName(String fileName) {
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
public String getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public void setFormat(String format) {
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
public LocalDate getStartDate() {
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public void setStartDate(LocalDate startDate) {
|
||||
this.startDate = startDate;
|
||||
}
|
||||
|
||||
public LocalDate getEndDate() {
|
||||
return endDate;
|
||||
}
|
||||
|
||||
public void setEndDate(LocalDate endDate) {
|
||||
this.endDate = endDate;
|
||||
}
|
||||
|
||||
public String getExportType() {
|
||||
return exportType;
|
||||
}
|
||||
|
||||
public void setExportType(String exportType) {
|
||||
this.exportType = exportType;
|
||||
}
|
||||
|
||||
public List<MemberStatistics> getMemberStatisticsList() {
|
||||
return memberStatisticsList;
|
||||
}
|
||||
|
||||
public void setMemberStatisticsList(List<MemberStatistics> memberStatisticsList) {
|
||||
this.memberStatisticsList = memberStatisticsList;
|
||||
}
|
||||
|
||||
public List<BookingStatistics> getBookingStatisticsList() {
|
||||
return bookingStatisticsList;
|
||||
}
|
||||
|
||||
public void setBookingStatisticsList(List<BookingStatistics> bookingStatisticsList) {
|
||||
this.bookingStatisticsList = bookingStatisticsList;
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package cn.novalon.gym.manage.datacount.handler;
|
||||
|
||||
import cn.novalon.gym.manage.datacount.domain.BookingStatistics;
|
||||
import cn.novalon.gym.manage.datacount.domain.MemberStatistics;
|
||||
import cn.novalon.gym.manage.datacount.service.IDataCountService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
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.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@Tag(name = "数据统计", description = "数据统计相关操作")
|
||||
public class DataCountHandler {
|
||||
|
||||
private final IDataCountService dataCountService;
|
||||
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
public DataCountHandler(IDataCountService dataCountService) {
|
||||
this.dataCountService = dataCountService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取会员数据统计(按日期)", description = "获取指定日期的会员数据统计")
|
||||
public Mono<ServerResponse> getMemberStatisticsByDate(ServerRequest request) {
|
||||
String dateStr = request.pathVariable("date");
|
||||
LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
|
||||
|
||||
return dataCountService.getMemberStatisticsByDate(date)
|
||||
.flatMap(stats -> ServerResponse.ok().bodyValue(stats))
|
||||
.switchIfEmpty(ServerResponse.notFound().build())
|
||||
.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> getMemberStatisticsByDateRange(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
return dataCountService.getMemberStatisticsByDateRange(startDate, endDate)
|
||||
.collectList()
|
||||
.flatMap(list -> ServerResponse.ok().bodyValue(list))
|
||||
.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> getMemberStatisticsSummary(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
return dataCountService.getMemberStatisticsSummary(startDate, endDate)
|
||||
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
||||
.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> getBookingStatisticsByDate(ServerRequest request) {
|
||||
String dateStr = request.pathVariable("date");
|
||||
LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
|
||||
|
||||
return dataCountService.getBookingStatisticsByDate(date)
|
||||
.flatMap(stats -> ServerResponse.ok().bodyValue(stats))
|
||||
.switchIfEmpty(ServerResponse.notFound().build())
|
||||
.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> getBookingStatisticsByDateRange(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
return dataCountService.getBookingStatisticsByDateRange(startDate, endDate)
|
||||
.collectList()
|
||||
.flatMap(list -> ServerResponse.ok().bodyValue(list))
|
||||
.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> getBookingStatisticsSummary(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
return dataCountService.getBookingStatisticsSummary(startDate, endDate)
|
||||
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
||||
.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 = "导出指定日期范围内的会员数据统计为CSV文件")
|
||||
public Mono<ServerResponse> exportMemberStatistics(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
String fileName = "member_statistics_" + startDateStr + "_" + endDateStr + ".csv";
|
||||
|
||||
return dataCountService.exportMemberStatistics(startDate, endDate)
|
||||
.flatMap(data -> ServerResponse.ok()
|
||||
.header("Content-Disposition", "attachment; filename=" + fileName)
|
||||
.header("Content-Type", "text/csv; charset=UTF-8")
|
||||
.bodyValue(data))
|
||||
.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 = "导出指定日期范围内的预约数据统计为CSV文件")
|
||||
public Mono<ServerResponse> exportBookingStatistics(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
String fileName = "booking_statistics_" + startDateStr + "_" + endDateStr + ".csv";
|
||||
|
||||
return dataCountService.exportBookingStatistics(startDate, endDate)
|
||||
.flatMap(data -> ServerResponse.ok()
|
||||
.header("Content-Disposition", "attachment; filename=" + fileName)
|
||||
.header("Content-Type", "text/csv; charset=UTF-8")
|
||||
.bodyValue(data))
|
||||
.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 = "导出指定日期范围内的会员和预约数据统计为CSV文件")
|
||||
public Mono<ServerResponse> exportAllStatistics(ServerRequest request) {
|
||||
String startDateStr = request.queryParam("startDate").orElseThrow(() -> new IllegalArgumentException("startDate必填"));
|
||||
String endDateStr = request.queryParam("endDate").orElseThrow(() -> new IllegalArgumentException("endDate必填"));
|
||||
|
||||
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
|
||||
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
|
||||
|
||||
String fileName = "all_statistics_" + startDateStr + "_" + endDateStr + ".csv";
|
||||
|
||||
return dataCountService.exportAllStatistics(startDate, endDate)
|
||||
.flatMap(data -> ServerResponse.ok()
|
||||
.header("Content-Disposition", "attachment; filename=" + fileName)
|
||||
.header("Content-Type", "text/csv; charset=UTF-8")
|
||||
.bodyValue(data))
|
||||
.onErrorResume(error -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package cn.novalon.gym.manage.datacount.scheduler;
|
||||
|
||||
import cn.novalon.gym.manage.datacount.service.IDataCountService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 数据统计定时任务
|
||||
*
|
||||
* 功能:每日凌晨1点自动计算前一天的数据统计并缓存到Redis
|
||||
*
|
||||
* @author 数据统计模块
|
||||
* @date 2026-06-06
|
||||
*/
|
||||
@Component
|
||||
public class StatisticsDailyScheduler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(StatisticsDailyScheduler.class);
|
||||
|
||||
private final IDataCountService dataCountService;
|
||||
|
||||
public StatisticsDailyScheduler(IDataCountService dataCountService) {
|
||||
this.dataCountService = dataCountService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每日凌晨1点执行前一天的统计数据计算并缓存
|
||||
* cron表达式:秒 分 时 日 月 周
|
||||
*/
|
||||
@Scheduled(cron = "0 0 1 * * ?")
|
||||
public void calculateDailyStatistics() {
|
||||
LocalDate yesterday = LocalDate.now().minusDays(1);
|
||||
logger.info("定时任务开始计算 {} 的数据统计", yesterday);
|
||||
|
||||
dataCountService.getMemberStatisticsByDate(yesterday)
|
||||
.doOnSuccess(stats -> logger.info("会员统计计算完成: date={}, newMembers={}, totalMembers={}",
|
||||
yesterday, stats.getNewMembers(), stats.getTotalMembers()))
|
||||
.doOnError(error -> logger.error("会员统计计算失败: date={}", yesterday, error))
|
||||
.subscribe();
|
||||
|
||||
dataCountService.getBookingStatisticsByDate(yesterday)
|
||||
.doOnSuccess(stats -> logger.info("预约统计计算完成: date={}, totalBookings={}, attendanceRate={}%",
|
||||
yesterday, stats.getTotalBookings(), stats.getAttendanceRate()))
|
||||
.doOnError(error -> logger.error("预约统计计算失败: date={}", yesterday, error))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
/**
|
||||
* 每周一凌晨2点执行上周的数据汇总统计
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 * * 1")
|
||||
public void calculateWeeklyStatistics() {
|
||||
LocalDate lastWeekEnd = LocalDate.now().minusDays(1);
|
||||
LocalDate lastWeekStart = lastWeekEnd.minusDays(6);
|
||||
logger.info("定时任务开始计算上周汇总统计: {} ~ {}", lastWeekStart, lastWeekEnd);
|
||||
|
||||
dataCountService.getMemberStatisticsSummary(lastWeekStart, lastWeekEnd)
|
||||
.doOnSuccess(stats -> logger.info("上周会员汇总统计完成: newMembers={}", stats.getNewMembers()))
|
||||
.doOnError(error -> logger.error("上周会员汇总统计失败", error))
|
||||
.subscribe();
|
||||
|
||||
dataCountService.getBookingStatisticsSummary(lastWeekStart, lastWeekEnd)
|
||||
.doOnSuccess(stats -> logger.info("上周预约汇总统计完成: totalBookings={}", stats.getTotalBookings()))
|
||||
.doOnError(error -> logger.error("上周预约汇总统计失败", error))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
/**
|
||||
* 每月1号凌晨3点执行上月的数据汇总统计
|
||||
*/
|
||||
@Scheduled(cron = "0 0 3 1 * ?")
|
||||
public void calculateMonthlyStatistics() {
|
||||
LocalDate lastMonthEnd = LocalDate.now().minusDays(1);
|
||||
LocalDate lastMonthStart = lastMonthEnd.withDayOfMonth(1);
|
||||
logger.info("定时任务开始计算上月汇总统计: {} ~ {}", lastMonthStart, lastMonthEnd);
|
||||
|
||||
dataCountService.getMemberStatisticsSummary(lastMonthStart, lastMonthEnd)
|
||||
.doOnSuccess(stats -> logger.info("上月会员汇总统计完成: newMembers={}", stats.getNewMembers()))
|
||||
.doOnError(error -> logger.error("上月会员汇总统计失败", error))
|
||||
.subscribe();
|
||||
|
||||
dataCountService.getBookingStatisticsSummary(lastMonthStart, lastMonthEnd)
|
||||
.doOnSuccess(stats -> logger.info("上月预约汇总统计完成: totalBookings={}", stats.getTotalBookings()))
|
||||
.doOnError(error -> logger.error("上月预约汇总统计失败", error))
|
||||
.subscribe();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package cn.novalon.gym.manage.datacount.service;
|
||||
|
||||
import cn.novalon.gym.manage.datacount.domain.BookingStatistics;
|
||||
import cn.novalon.gym.manage.datacount.domain.MemberStatistics;
|
||||
import cn.novalon.gym.manage.datacount.domain.StatisticsExportDTO;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public interface IDataCountService {
|
||||
|
||||
Mono<MemberStatistics> getMemberStatisticsByDate(LocalDate date);
|
||||
|
||||
Flux<MemberStatistics> getMemberStatisticsByDateRange(LocalDate startDate, LocalDate endDate);
|
||||
|
||||
Mono<MemberStatistics> getMemberStatisticsSummary(LocalDate startDate, LocalDate endDate);
|
||||
|
||||
Mono<BookingStatistics> getBookingStatisticsByDate(LocalDate date);
|
||||
|
||||
Flux<BookingStatistics> getBookingStatisticsByDateRange(LocalDate startDate, LocalDate endDate);
|
||||
|
||||
Mono<BookingStatistics> getBookingStatisticsSummary(LocalDate startDate, LocalDate endDate);
|
||||
|
||||
Mono<byte[]> exportMemberStatistics(LocalDate startDate, LocalDate endDate);
|
||||
|
||||
Mono<byte[]> exportBookingStatistics(LocalDate startDate, LocalDate endDate);
|
||||
|
||||
Mono<byte[]> exportAllStatistics(LocalDate startDate, LocalDate endDate);
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
package cn.novalon.gym.manage.datacount.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import cn.novalon.gym.manage.datacount.dao.StatisticsDao;
|
||||
import cn.novalon.gym.manage.datacount.domain.BookingStatistics;
|
||||
import cn.novalon.gym.manage.datacount.domain.MemberStatistics;
|
||||
import cn.novalon.gym.manage.datacount.service.IDataCountService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class DataCountServiceImpl implements IDataCountService {
|
||||
|
||||
private final StatisticsDao statisticsDao;
|
||||
private final RedisUtil redisUtil;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private static final String MEMBER_STATS_CACHE_PREFIX = "stats:member:";
|
||||
private static final String BOOKING_STATS_CACHE_PREFIX = "stats:booking:";
|
||||
private static final long CACHE_EXPIRE_SECONDS = 3600;
|
||||
|
||||
public DataCountServiceImpl(StatisticsDao statisticsDao, RedisUtil redisUtil, ObjectMapper objectMapper) {
|
||||
this.statisticsDao = statisticsDao;
|
||||
this.redisUtil = redisUtil;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<MemberStatistics> getMemberStatisticsByDate(LocalDate date) {
|
||||
String cacheKey = MEMBER_STATS_CACHE_PREFIX + date.toString();
|
||||
return redisUtil.get(cacheKey)
|
||||
.flatMap(cached -> {
|
||||
if (cached != null) {
|
||||
try {
|
||||
MemberStatistics stats = objectMapper.readValue(cached.toString(), MemberStatistics.class);
|
||||
log.debug("从缓存获取会员统计数据, date: {}", date);
|
||||
return Mono.just(stats);
|
||||
} catch (Exception e) {
|
||||
log.warn("缓存数据解析失败, date: {}", date, e);
|
||||
}
|
||||
}
|
||||
return Mono.empty();
|
||||
})
|
||||
.switchIfEmpty(fetchMemberStatisticsByDate(date)
|
||||
.flatMap(stats -> {
|
||||
try {
|
||||
String json = objectMapper.writeValueAsString(stats);
|
||||
return redisUtil.setWithExpire(cacheKey, json, CACHE_EXPIRE_SECONDS)
|
||||
.then(Mono.just(stats));
|
||||
} catch (Exception e) {
|
||||
log.warn("缓存会员统计数据失败, date: {}", date, e);
|
||||
return Mono.just(stats);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private Mono<MemberStatistics> fetchMemberStatisticsByDate(LocalDate date) {
|
||||
return Mono.zip(
|
||||
statisticsDao.countTotalMembers(),
|
||||
statisticsDao.countNewMembersByDate(date),
|
||||
statisticsDao.countActiveMembersByDate(date),
|
||||
statisticsDao.countMaleMembers(),
|
||||
statisticsDao.countFemaleMembers(),
|
||||
statisticsDao.countCardPurchaseByDate(date),
|
||||
statisticsDao.calculateAverageAge()
|
||||
).map(tuple -> {
|
||||
MemberStatistics stats = new MemberStatistics(date);
|
||||
stats.setTotalMembers(tuple.getT1());
|
||||
stats.setNewMembers(tuple.getT2());
|
||||
stats.setActiveMembers(tuple.getT3());
|
||||
stats.setMaleMembers(tuple.getT4());
|
||||
stats.setFemaleMembers(tuple.getT5());
|
||||
stats.setCardPurchaseCount(tuple.getT6());
|
||||
stats.setAverageAge(tuple.getT7() != null ? tuple.getT7() : 0.0);
|
||||
return stats;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<MemberStatistics> getMemberStatisticsByDateRange(LocalDate startDate, LocalDate endDate) {
|
||||
return statisticsDao.findMemberStatisticsByDateRange(startDate, endDate)
|
||||
.map(row -> {
|
||||
LocalDate date = (LocalDate) row[0];
|
||||
MemberStatistics stats = new MemberStatistics(date);
|
||||
stats.setNewMembers(((Number) row[1]).intValue());
|
||||
return stats;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<MemberStatistics> getMemberStatisticsSummary(LocalDate startDate, LocalDate endDate) {
|
||||
return getMemberStatisticsByDateRange(startDate, endDate)
|
||||
.collectList()
|
||||
.flatMap(list -> {
|
||||
MemberStatistics summary = new MemberStatistics();
|
||||
summary.setStartDate(startDate);
|
||||
summary.setEndDate(endDate);
|
||||
summary.setNewMembers(list.stream().mapToInt(MemberStatistics::getNewMembers).sum());
|
||||
|
||||
return Mono.zip(
|
||||
statisticsDao.countTotalMembers(),
|
||||
statisticsDao.countMaleMembers(),
|
||||
statisticsDao.countFemaleMembers(),
|
||||
statisticsDao.calculateAverageAge()
|
||||
).map(tuple -> {
|
||||
summary.setTotalMembers(tuple.getT1());
|
||||
summary.setMaleMembers(tuple.getT2());
|
||||
summary.setFemaleMembers(tuple.getT3());
|
||||
summary.setAverageAge(tuple.getT4() != null ? tuple.getT4() : 0.0);
|
||||
return summary;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BookingStatistics> getBookingStatisticsByDate(LocalDate date) {
|
||||
String cacheKey = BOOKING_STATS_CACHE_PREFIX + date.toString();
|
||||
return redisUtil.get(cacheKey)
|
||||
.flatMap(cached -> {
|
||||
if (cached != null) {
|
||||
try {
|
||||
BookingStatistics stats = objectMapper.readValue(cached.toString(), BookingStatistics.class);
|
||||
log.debug("从缓存获取预约统计数据, date: {}", date);
|
||||
return Mono.just(stats);
|
||||
} catch (Exception e) {
|
||||
log.warn("缓存数据解析失败, date: {}", date, e);
|
||||
}
|
||||
}
|
||||
return Mono.empty();
|
||||
})
|
||||
.switchIfEmpty(fetchBookingStatisticsByDate(date)
|
||||
.flatMap(stats -> {
|
||||
try {
|
||||
String json = objectMapper.writeValueAsString(stats);
|
||||
return redisUtil.setWithExpire(cacheKey, json, CACHE_EXPIRE_SECONDS)
|
||||
.then(Mono.just(stats));
|
||||
} catch (Exception e) {
|
||||
log.warn("缓存预约统计数据失败, date: {}", date, e);
|
||||
return Mono.just(stats);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private Mono<BookingStatistics> fetchBookingStatisticsByDate(LocalDate date) {
|
||||
return Mono.zip(
|
||||
statisticsDao.countTotalBookingsByDate(date),
|
||||
statisticsDao.countCancelledBookingsByDate(date),
|
||||
statisticsDao.countAttendedBookingsByDate(date),
|
||||
statisticsDao.countTotalCoursesByDate(date),
|
||||
statisticsDao.countFullCoursesByDate(date),
|
||||
statisticsDao.findMostPopularCourseByDate(date)
|
||||
).map(tuple -> {
|
||||
int totalBookings = tuple.getT1();
|
||||
int cancelledBookings = tuple.getT2();
|
||||
int attendedBookings = tuple.getT3();
|
||||
|
||||
BookingStatistics stats = new BookingStatistics(date);
|
||||
stats.setTotalBookings(totalBookings);
|
||||
stats.setCancelledBookings(cancelledBookings);
|
||||
stats.setAttendedBookings(attendedBookings);
|
||||
stats.setTotalCourses(tuple.getT4());
|
||||
stats.setFullCourses(tuple.getT5());
|
||||
|
||||
if (totalBookings > 0) {
|
||||
stats.setCancellationRate(Math.round(cancelledBookings * 10000.0 / totalBookings) / 100.0);
|
||||
stats.setAttendanceRate(Math.round(attendedBookings * 10000.0 / totalBookings) / 100.0);
|
||||
}
|
||||
|
||||
Object[] popularCourse = tuple.getT6();
|
||||
if (popularCourse != null && popularCourse.length >= 2) {
|
||||
stats.setPopularCourseName((String) popularCourse[0]);
|
||||
stats.setPopularCourseCount(((Number) popularCourse[1]).intValue());
|
||||
}
|
||||
|
||||
return stats;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<BookingStatistics> getBookingStatisticsByDateRange(LocalDate startDate, LocalDate endDate) {
|
||||
return statisticsDao.findBookingStatisticsByDateRange(startDate, endDate)
|
||||
.map(row -> {
|
||||
LocalDate date = (LocalDate) row[0];
|
||||
int totalBookings = ((Number) row[1]).intValue();
|
||||
int cancelledBookings = ((Number) row[2]).intValue();
|
||||
int attendedBookings = ((Number) row[3]).intValue();
|
||||
|
||||
BookingStatistics stats = new BookingStatistics(date);
|
||||
stats.setTotalBookings(totalBookings);
|
||||
stats.setCancelledBookings(cancelledBookings);
|
||||
stats.setAttendedBookings(attendedBookings);
|
||||
|
||||
if (totalBookings > 0) {
|
||||
stats.setCancellationRate(Math.round(cancelledBookings * 10000.0 / totalBookings) / 100.0);
|
||||
stats.setAttendanceRate(Math.round(attendedBookings * 10000.0 / totalBookings) / 100.0);
|
||||
}
|
||||
|
||||
return stats;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BookingStatistics> getBookingStatisticsSummary(LocalDate startDate, LocalDate endDate) {
|
||||
return getBookingStatisticsByDateRange(startDate, endDate)
|
||||
.collectList()
|
||||
.map(list -> {
|
||||
BookingStatistics summary = new BookingStatistics();
|
||||
summary.setStartDate(startDate);
|
||||
summary.setEndDate(endDate);
|
||||
summary.setTotalBookings(list.stream().mapToInt(BookingStatistics::getTotalBookings).sum());
|
||||
summary.setCancelledBookings(list.stream().mapToInt(BookingStatistics::getCancelledBookings).sum());
|
||||
summary.setAttendedBookings(list.stream().mapToInt(BookingStatistics::getAttendedBookings).sum());
|
||||
|
||||
int total = summary.getTotalBookings();
|
||||
if (total > 0) {
|
||||
summary.setCancellationRate(Math.round(summary.getCancelledBookings() * 10000.0 / total) / 100.0);
|
||||
summary.setAttendanceRate(Math.round(summary.getAttendedBookings() * 10000.0 / total) / 100.0);
|
||||
}
|
||||
|
||||
return summary;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<byte[]> exportMemberStatistics(LocalDate startDate, LocalDate endDate) {
|
||||
return getMemberStatisticsByDateRange(startDate, endDate)
|
||||
.collectList()
|
||||
.map(this::generateMemberStatisticsCSV);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<byte[]> exportBookingStatistics(LocalDate startDate, LocalDate endDate) {
|
||||
return getBookingStatisticsByDateRange(startDate, endDate)
|
||||
.collectList()
|
||||
.map(this::generateBookingStatisticsCSV);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<byte[]> exportAllStatistics(LocalDate startDate, LocalDate endDate) {
|
||||
return Mono.zip(
|
||||
getMemberStatisticsByDateRange(startDate, endDate).collectList(),
|
||||
getBookingStatisticsByDateRange(startDate, endDate).collectList()
|
||||
).map(tuple -> {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PrintWriter writer = new PrintWriter(new OutputStreamWriter(baos, StandardCharsets.UTF_8));
|
||||
|
||||
writer.println("=== 会员数据统计 ===");
|
||||
writer.println(generateMemberStatisticsCSVContent(tuple.getT1()));
|
||||
writer.println();
|
||||
writer.println("=== 预约数据统计 ===");
|
||||
writer.println(generateBookingStatisticsCSVContent(tuple.getT2()));
|
||||
|
||||
writer.flush();
|
||||
return baos.toByteArray();
|
||||
});
|
||||
}
|
||||
|
||||
private byte[] generateMemberStatisticsCSV(List<MemberStatistics> statsList) {
|
||||
return generateMemberStatisticsCSVContent(statsList).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String generateMemberStatisticsCSVContent(List<MemberStatistics> statsList) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("统计日期,新增会员数,活跃会员数,总会员数,男性会员数,女性会员数,购卡人数,平均年龄\n");
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
for (MemberStatistics stats : statsList) {
|
||||
sb.append(stats.getDate().format(formatter)).append(",");
|
||||
sb.append(stats.getNewMembers()).append(",");
|
||||
sb.append(stats.getActiveMembers()).append(",");
|
||||
sb.append(stats.getTotalMembers()).append(",");
|
||||
sb.append(stats.getMaleMembers()).append(",");
|
||||
sb.append(stats.getFemaleMembers()).append(",");
|
||||
sb.append(stats.getCardPurchaseCount()).append(",");
|
||||
sb.append(String.format("%.1f", stats.getAverageAge())).append("\n");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private byte[] generateBookingStatisticsCSV(List<BookingStatistics> statsList) {
|
||||
return generateBookingStatisticsCSVContent(statsList).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String generateBookingStatisticsCSVContent(List<BookingStatistics> statsList) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("统计日期,预约总数,取消预约数,实际到场数,取消率(%),到场率(%),热门课程,热门课程预约数,团课总数,满员课程数\n");
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
for (BookingStatistics stats : statsList) {
|
||||
sb.append(stats.getDate().format(formatter)).append(",");
|
||||
sb.append(stats.getTotalBookings()).append(",");
|
||||
sb.append(stats.getCancelledBookings()).append(",");
|
||||
sb.append(stats.getAttendedBookings()).append(",");
|
||||
sb.append(String.format("%.2f", stats.getCancellationRate())).append(",");
|
||||
sb.append(String.format("%.2f", stats.getAttendanceRate())).append(",");
|
||||
sb.append(stats.getPopularCourseName() != null ? stats.getPopularCourseName() : "").append(",");
|
||||
sb.append(stats.getPopularCourseCount()).append(",");
|
||||
sb.append(stats.getTotalCourses()).append(",");
|
||||
sb.append(stats.getFullCourses()).append("\n");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
spring:
|
||||
application:
|
||||
name: gym-dataCount
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package cn.novalon.gym.manage.datacount;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class GymDataCountApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user