-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStatisticsService.java
More file actions
74 lines (60 loc) · 2.56 KB
/
StatisticsService.java
File metadata and controls
74 lines (60 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package lv.ctco.springboottemplate.features.statistics;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lv.ctco.springboottemplate.features.statistics.dto.StatsFormatEnum;
import lv.ctco.springboottemplate.features.statistics.dto.TodoBreakdownDTO;
import lv.ctco.springboottemplate.features.statistics.dto.TodoItemDTO;
import lv.ctco.springboottemplate.features.statistics.dto.TodoStatsResponseDTO;
import lv.ctco.springboottemplate.features.todo.Todo;
import lv.ctco.springboottemplate.features.todo.TodoRepository;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class StatisticsService {
private final MongoTemplate mongoTemplate;
private final TodoRepository todoRepository;
public TodoStatsResponseDTO query(
Optional<LocalDate> from, Optional<LocalDate> to, StatsFormatEnum format) {
Criteria criteria = Criteria.where("createdAt");
;
if (from.isPresent()) criteria = criteria.gte(from.get());
if (to.isPresent()) criteria = criteria.lte(to.get());
Query query = new Query(criteria);
List<Todo> todos = mongoTemplate.find(query, Todo.class);
return buildSummaryFromTodos(todos, format);
}
private TodoStatsResponseDTO buildSummaryFromTodos(List<Todo> todos, StatsFormatEnum format) {
int total = todos.size();
int completed = (int) todos.stream().filter(Todo::completed).count();
int pending = total - completed;
List<TodoItemDTO> completedList =
todos.stream().filter(Todo::completed).map(this::toDto).toList();
List<TodoItemDTO> pendingList =
todos.stream().filter(t -> !t.completed()).map(this::toDto).toList();
Map<String, Integer> userStats =
todos.stream()
.collect(Collectors.groupingBy(Todo::createdBy, Collectors.summingInt(t -> 1)));
TodoBreakdownDTO breakdown = new TodoBreakdownDTO(completedList, pendingList);
return new TodoStatsResponseDTO(
total,
completed,
pending,
userStats,
format == StatsFormatEnum.DETAILED ? Optional.of(breakdown) : Optional.empty());
}
private TodoItemDTO toDto(Todo todo) {
return new TodoItemDTO(
todo.id(),
todo.title(),
todo.createdBy(),
todo.createdAt(),
todo.completed() ? todo.updatedAt() : null);
}
}