1.Controller层 (ReportController.java)
@GetMapping("/turnoverStatistics")
public Result<TurnoverReportVO> turnoverStatistics(
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
return Result.success(reportService.getTurnover(begin, end));
}
2.Service层 (ReportServiceImpl.java)
public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
// 1. 生成日期列表
List<LocalDate> dateList = new ArrayList<>();
// [2023-01-01, 2023-01-02, ..., 2023-01-31]
// 2. 遍历每一天,查询营业额
for (LocalDate date : dateList) {
LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN); // 00:00:00
LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX); // 23:59:59
// 3. 构建查询条件
Map map = new HashMap();
map.put("status", Orders.COMPLETED); // 只统计已完成的订单
map.put("begin", beginTime);
map.put("end", endTime);
// 4. 调用Mapper查询当日营业额
Double turnover = orderMapper.sumByMap(map);
}
// 5. 封装结果
return TurnoverReportVO.builder()
.dateList(StringUtils.join(dateList, ","))
.turnoverList(StringUtils.join(turnoverList, ","))
.build();
}
3.Mapper层 (OrderMapper.java)
// 接口声明
Double sumByMap(Map map);
4.XML映射 (OrderMapper.xml)
<select id="sumByMap" resultType="java.lang.Double">
SELECT SUM(amount) FROM orders
<where>
<if test="status != null">
AND status = #{status} <!-- 订单状态:已完成 -->
</if>
<if test="begin != null">
AND order_time >= #{begin} <!-- 订单开始时间 -->
</if>
<if test="end != null">
AND order_time <= #{end} <!-- 订单结束时间 -->
</if>
</where>
</select>
用户统计同理,不在赘述。