Skip to content

Commit

Permalink
Feat : 응답 구조 수정
Browse files Browse the repository at this point in the history
상위 DTO 작성을 통해 응답구조 변경, 날짜와 각 보낸이에 대한 정보, 그에따른 컨트롤러 자료형 수정
  • Loading branch information
Mouon committed Feb 4, 2024
1 parent 7188bd0 commit e8d4c1e
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 69 deletions.
15 changes: 5 additions & 10 deletions src/main/java/com/kuit/chatdiary/controller/SenderController.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
package com.kuit.chatdiary.controller;

import com.kuit.chatdiary.dto.chat.ChatSenderStaticResponseDTO;
import com.kuit.chatdiary.dto.chat.ChatSenderStatisticsResponseDTO;
import com.kuit.chatdiary.dto.diary.DateRangeDTO;
import com.kuit.chatdiary.service.chat.SenderService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/chat")
public class SenderController {
Expand All @@ -24,13 +20,12 @@ public SenderController(SenderService senderService) {
}

@GetMapping("/sender")
public ResponseEntity<List<ChatSenderStaticResponseDTO>> getTagStatistics(
public ResponseEntity<ChatSenderStatisticsResponseDTO> getSenderStatistics(
@RequestParam("memberId") Long memberId,
@RequestParam("type") String type){
@RequestParam("type") String type) {
DateRangeDTO dateRange = senderService.staticsType(type);
List<ChatSenderStaticResponseDTO> tagStatistics = senderService.calculateSenderStatistics(memberId, dateRange.getStartDate()
,dateRange.getEndDate());
return ResponseEntity.ok(tagStatistics);
ChatSenderStatisticsResponseDTO senderStatistics = senderService.calculateSenderStatistics(memberId, dateRange.getStartDate(), dateRange.getEndDate());
return ResponseEntity.ok(senderStatistics);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.kuit.chatdiary.dto.chat;

import com.kuit.chatdiary.domain.Sender;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ChatSenderDetailResponseDTO {
private Sender sender;
private Long chatCount;
private double percentage;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.kuit.chatdiary.dto.chat;

import com.kuit.chatdiary.domain.Sender;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -13,8 +12,8 @@
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ChatSenderStaticResponseDTO {
public class ChatSenderStatisticsResponseDTO {
private Date startDate;
private Date endDate;
private List<ChatSenderStaticResponseDTO> statistics;
}
private List<ChatSenderDetailResponseDTO> statistics;
}
88 changes: 33 additions & 55 deletions src/main/java/com/kuit/chatdiary/service/chat/SenderService.java
Original file line number Diff line number Diff line change
@@ -1,96 +1,74 @@
package com.kuit.chatdiary.service.chat;

import com.kuit.chatdiary.domain.Sender;
import com.kuit.chatdiary.dto.chat.ChatSenderStaticResponseDTO;
import com.kuit.chatdiary.dto.chat.ChatSenderDetailResponseDTO;
import com.kuit.chatdiary.dto.chat.ChatSenderStatisticsResponseDTO;
import com.kuit.chatdiary.dto.diary.DateRangeDTO;
import com.kuit.chatdiary.repository.statics.SenderRepository;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SenderService {

public final SenderRepository senderRepository;
private final SenderRepository senderRepository;

public SenderService(SenderRepository senderRepository) {
this.senderRepository = senderRepository;
}
public List<ChatSenderStaticResponseDTO> calculateSenderStatistics(Long memberId, Date startDate, Date endDate) {
public ChatSenderStatisticsResponseDTO calculateSenderStatistics(Long memberId, Date startDate, Date endDate) {
List<Object[]> chatStatistics = senderRepository.countChatsBySenderAndDate(memberId, startDate, endDate);

/** value를 count로 활용해서 연산 쉽게 */
Map<Sender, Long> chatCountMap = new HashMap<>();
Map<Sender, Long> chatCountMap = new EnumMap<>(Sender.class);
long totalChats = 0;
for (Object[] result : chatStatistics) {
String senderName = (String) result[0];
Sender sender = Sender.valueOf((String) result[0]);
Long count = (Long) result[1];

if (!senderName.equals(Sender.USER.name())) {
Sender sender = Sender.valueOf(senderName);
chatCountMap.put(sender, count);
totalChats += count;
}
}
/** 이미 키 있으면 업데이트 안하기
* 0개 처리
* */
for (Sender sender : Sender.values()) {
chatCountMap.putIfAbsent(sender, 0L);
chatCountMap.merge(sender, count, Long::sum);
totalChats += count;
}

List<ChatSenderStaticResponseDTO> statisticsList = new ArrayList<>();
for (Map.Entry<Sender, Long> entry : chatCountMap.entrySet()) {
if (entry.getKey() != Sender.USER) {
double percentage = calculatePercent(entry.getValue(), totalChats);
statisticsList.add(new ChatSenderStaticResponseDTO(entry.getKey(), entry.getValue(), percentage, startDate, endDate));
}
}
final long finalTotalChats = totalChats;
List<ChatSenderDetailResponseDTO> details = chatCountMap.entrySet().stream()
.filter(entry -> entry.getKey() != Sender.USER)
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(entry -> new ChatSenderDetailResponseDTO(entry.getKey(), entry.getValue(), calculatePercent(entry.getValue(), finalTotalChats)))
.collect(Collectors.toList());

return statisticsList;
return new ChatSenderStatisticsResponseDTO(startDate, endDate, details);
}

/** 나중에 메서드 합쳐서 리펙토링 필요 */
public double calculatePercent(long count,long totalTags){
double percentage = (double) count / totalTags * 100;
return Math.round(percentage*10)/10.0;
private double calculatePercent(long count, long totalChats) {
if (totalChats == 0) return 0.0;
return Math.round((double) count / totalChats * 1000) / 10.0;
}

/** 나중에 메서드 합쳐서 리펙토링 필요 */
public DateRangeDTO staticsType(String type){
LocalDate localDate = LocalDate.now();
Calendar calendar = Calendar.getInstance();
calendar.setTime(java.sql.Date.valueOf(localDate));
Date startDate, endDate;
public DateRangeDTO staticsType(String type) {
LocalDate now = LocalDate.now();
LocalDate startDate;
LocalDate endDate;

switch (type) {
case "weekly":
/** 주간 -> 해당 주의 시작일과 종료일을 계산 */
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
startDate = new Date(calendar.getTimeInMillis());
calendar.add(Calendar.DAY_OF_WEEK, 6);
endDate = new Date(calendar.getTimeInMillis());
startDate = now.with(java.time.DayOfWeek.MONDAY);
endDate = now.with(java.time.DayOfWeek.SUNDAY);
break;
case "monthly":
/** 월간 -> 해당 월의 시작일과 종료일을 계산 */
calendar.set(Calendar.DAY_OF_MONTH, 1);
startDate = new Date(calendar.getTimeInMillis());
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_MONTH, -1);
endDate = new Date(calendar.getTimeInMillis());
startDate = now.withDayOfMonth(1);
endDate = now.withDayOfMonth(now.lengthOfMonth());
break;
case "yearly":
/** 연간 -> 해당 연도의 시작일과 종료일을 계산 */
calendar.set(Calendar.DAY_OF_YEAR, 1);
startDate = new Date(calendar.getTimeInMillis());
calendar.add(Calendar.YEAR, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
endDate = new Date(calendar.getTimeInMillis());
startDate = now.withDayOfYear(1);
endDate = now.withDayOfYear(now.lengthOfYear());
break;
default:
throw new IllegalArgumentException("Invalid type: " + type);
}
return new DateRangeDTO(startDate, endDate);

return new DateRangeDTO(Date.valueOf(startDate), Date.valueOf(endDate));
}
}
}

0 comments on commit e8d4c1e

Please sign in to comment.