Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/party #120

Merged
merged 6 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.HHive.hhive.domain.party.controller;

import com.HHive.hhive.domain.party.dto.MyPartyResponseDTO;
import com.HHive.hhive.domain.party.dto.PartyRequestDTO;
import com.HHive.hhive.domain.party.dto.PartyListResponseDTO;
import com.HHive.hhive.domain.party.dto.PartyResponseDTO;
import com.HHive.hhive.domain.party.dto.*;
import com.HHive.hhive.domain.party.service.PartyService;
import com.HHive.hhive.domain.user.UserDetailsImpl;
import com.HHive.hhive.global.common.CommonResponse;
Expand Down Expand Up @@ -55,10 +52,10 @@ public ResponseEntity<CommonResponse<List<PartyListResponseDTO>>> getPartyList(@

@PatchMapping("/{partyId}")
public ResponseEntity<CommonResponse<PartyResponseDTO>> updateParty(@PathVariable Long partyId,
@RequestBody PartyRequestDTO partyRequestDto,
@RequestBody PartyUpdateRequestDTO partyUpdateRequestDTO,
@AuthenticationPrincipal UserDetailsImpl userDetails) {

PartyResponseDTO responseDto = partyService.updateParty(partyId, partyRequestDto, userDetails.getUser());
PartyResponseDTO responseDto = partyService.updateParty(partyId, partyUpdateRequestDTO, userDetails.getUser());

return ResponseEntity.ok().body(CommonResponse.of("업데이트 성공", responseDto));
}
Expand All @@ -72,11 +69,11 @@ public ResponseEntity<CommonResponse<String>> deleteParty(@PathVariable Long par
return ResponseEntity.ok().body(CommonResponse.of("정상적으로 삭제 되었습니다.", null));
}

@PostMapping("/{partyId}/join")
public ResponseEntity<CommonResponse<String>> joinParty(@PathVariable Long partyId,
@PostMapping("/{partyId}/hives/{hiveId}/join")
public ResponseEntity<CommonResponse<String>> joinParty(@PathVariable Long partyId,@PathVariable Long hiveId,
@AuthenticationPrincipal UserDetailsImpl userDetails) {

partyService.joinParty(partyId, userDetails.getUser());
partyService.joinParty(partyId, hiveId, userDetails.getUser());

return ResponseEntity.ok().body(CommonResponse.of("파티 가입 성공", null));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class PartyResponseDTO {
private String username;
private String content;

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
@JsonFormat(pattern = "yyyy년 MM월 dd일 / HH시 mm분")
private LocalDateTime dateTime; // 약속 날짜,시간
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime createAt;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.HHive.hhive.domain.party.dto;

import lombok.Getter;

@Getter
public class PartyUpdateRequestDTO {

private String title;
private String content;
private Integer year;
private Integer month;
private Integer day;
private Integer hours;
private Integer minutes;

}

142 changes: 77 additions & 65 deletions src/main/java/com/HHive/hhive/domain/party/service/PartyService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@

import com.HHive.hhive.domain.hive.entity.Hive;
import com.HHive.hhive.domain.hive.repository.HiveRepository;
import com.HHive.hhive.domain.party.dto.MemberResponseDTO;
import com.HHive.hhive.domain.party.dto.MyPartyResponseDTO;
import com.HHive.hhive.domain.party.dto.PartyRequestDTO;
import com.HHive.hhive.domain.party.dto.PartyResponseDTO;
import com.HHive.hhive.domain.party.dto.*;
import com.HHive.hhive.domain.party.entity.Party;
import com.HHive.hhive.domain.party.repository.PartyRepository;
import com.HHive.hhive.domain.relationship.partyuser.entity.PartyUser;
import com.HHive.hhive.domain.relationship.partyuser.pk.PartyUserPK;
import com.HHive.hhive.domain.relationship.partyuser.repository.PartyUserRepository;
import com.HHive.hhive.domain.relationship.partyuser.service.PartyUserService;
import com.HHive.hhive.domain.user.dto.UserInfoResponseDTO;
import com.HHive.hhive.domain.user.entity.User;
import com.HHive.hhive.global.exception.hive.NotFoundHiveException;
Expand All @@ -31,34 +29,24 @@ public class PartyService {
private final PartyRepository partyRepository;
private final HiveRepository hiveRepository;
private final PartyUserRepository partyUserRepository;
private final PartyUserService partyUserService;


@Transactional
public PartyResponseDTO createParty(Long hiveId, PartyRequestDTO dto, User user) {

// Hive 존재 여부 확인
Hive hive = getHive(hiveId);

// DTO에서 날짜와 시간 정보를 가져와서 LocalDateTime 객체 생성
LocalDateTime dateTime = LocalDateTime.of(
dto.getYear(),
dto.getMonth(),
dto.getDay(),
dto.getHours(),
dto.getMinutes());

// 현재 시간을 가져옴
LocalDateTime now = LocalDateTime.now();
LocalDateTime dateTime = getDateTimeFromDto(dto);

// 설정하려는 약속 시간이 과거인지 확인
if (dateTime.isBefore(now)) {
throw new InvalidPartyTimeException();
}
validatePartyTime(dateTime);

// 파티 엔티티 생성
Party party = new Party(hive, dto, user, dateTime);
party.setUser(user);

// 파티 저장
var savedParty = partyRepository.save(party);

// 파티 생성자(호스트)를 파티의 멤버로 추가
Expand All @@ -69,25 +57,17 @@ public PartyResponseDTO createParty(Long hiveId, PartyRequestDTO dto, User user)
partyUserRepository.save(partyUser);

// 호스트 정보를 members 목록에 포함하여 PartyResponseDTO 생성
List<MemberResponseDTO> members = Collections.singletonList(
new MemberResponseDTO(user.getUsername(), user.getEmail()));
return new PartyResponseDTO(savedParty.getId(), savedParty.getTitle(),
savedParty.getUsername(), savedParty.getContent(), savedParty.getDateTime(),
savedParty.getCreatedAt(), savedParty.getModifiedAt(), members);
PartyResponseDTO partyResponseDTO = createPartyResponseDTO(savedParty);
return partyResponseDTO;
}

//단건 조회
@Transactional
public PartyResponseDTO getPartyDto(Long hiveId, Long partyId) {
Party party = getParty(hiveId, partyId);
List<MemberResponseDTO> members = getPartyMembers(partyId);

return new PartyResponseDTO(party.getId(), party.getTitle(),
party.getUsername(), party.getContent(), party.getDateTime(),
party.getCreatedAt(), party.getModifiedAt(), members);
return createPartyResponseDTO(party);
}


//전체 조회
@Transactional
public Map<UserInfoResponseDTO, List<PartyResponseDTO>> getUserPartyMap(Long hiveId) {
Expand All @@ -98,7 +78,7 @@ public Map<UserInfoResponseDTO, List<PartyResponseDTO>> getUserPartyMap(Long hiv
List<Party> partyList = partyRepository.findAll(Sort.by(Sort.Direction.DESC, "createdAt")).stream()
.filter(p -> !p.isDeleted() && p.getHive().equals(hive))
.collect(Collectors.toList());

for (Party party : partyList) {
UserInfoResponseDTO userDto = new UserInfoResponseDTO(party.getUser());
List<MemberResponseDTO> members = getPartyMembers(party.getId());
Expand All @@ -112,42 +92,31 @@ public Map<UserInfoResponseDTO, List<PartyResponseDTO>> getUserPartyMap(Long hiv
}

@Transactional
public PartyResponseDTO updateParty(Long partyId, PartyRequestDTO partyRequestDto, User user) {
public PartyResponseDTO updateParty(Long partyId, PartyUpdateRequestDTO partyUpdateRequestDto, User user) {
Party party = getUserParty(partyId, user);

if (!party.getHostId().equals(user.getId())) {
throw new UnauthorizedAccessException();
}

party.setTitle(partyRequestDto.getTitle());
party.setContent(partyRequestDto.getContent());

// DTO에서 날짜와 시간 정보를 가져와 LocalDateTime 객체 생성
LocalDateTime newDateTime = LocalDateTime.of(
partyRequestDto.getYear(),
partyRequestDto.getMonth(),
partyRequestDto.getDay(),
partyRequestDto.getHours(),
partyRequestDto.getMinutes()
);
if (partyUpdateRequestDto.getTitle() != null) {
party.setTitle(partyUpdateRequestDto.getTitle());
}
if (partyUpdateRequestDto.getContent() != null) {
party.setContent(partyUpdateRequestDto.getContent());
}

LocalDateTime now = LocalDateTime.now();
LocalDateTime newDateTime = getLocalDateTime(partyUpdateRequestDto, party);

if (newDateTime.isBefore(now)) {
throw new InvalidPartyTimeException();
}
validatePartyTime(newDateTime);

// 파티 날짜 및 시간 업데이트
party.setDateTime(newDateTime);

// 파티 저장
partyRepository.save(party);

List<MemberResponseDTO> members = getPartyMembers(partyId);

return new PartyResponseDTO(party.getId(), party.getTitle(),
party.getUsername(), party.getContent(), party.getDateTime(),
party.getCreatedAt(), party.getModifiedAt(), members);
return createPartyResponseDTO(party);
}

@Transactional
Expand All @@ -163,12 +132,17 @@ public void deleteParty(Long partyId, User user) {
}

@Transactional
public void joinParty(Long partyId, User user) {
public void joinParty(Long partyId, Long hiveId, User user) {
Party party = getUserParty(partyId, user);

// 현재 날짜를 가져옵니다.
// 현재 날짜를 가져옴
LocalDateTime now = LocalDateTime.now();

// Hive에 가입되어 있는지 확인
if (!partyUserService.isUserMemberOfHive(user.getId(), hiveId)) {
throw new NotMemberOfHiveException();
}

// 파티 호스트가 파티에 가입하는 것을 방지
if (party.getHostId().equals(user.getId())) {
throw new PartyHostNotJoinException();
Expand All @@ -184,8 +158,7 @@ public void joinParty(Long partyId, User user) {
throw new AlreadyJoinException();
}
else {
PartyUser partyUser = new PartyUser(user, party);
partyUserRepository.save(partyUser);
partyUserService.addPartyUser(user, party);
}
}

Expand All @@ -200,25 +173,28 @@ public void resignParty(Long partyId, User user) {
if (!partyUserRepository.existsByPartyUserPK_UserIdAndPartyUserPK_PartyId(user.getId(), party.getId())) {
throw new PartyNotResignException();
}
// 파티 탈퇴 처리
PartyUserPK partyUserPK = new PartyUserPK(user.getId(), party.getId());
partyUserRepository.deleteById(partyUserPK);

partyUserService.removePartyUser(user.getId(), party.getId());
}


//공통 메서드
private Party getUserParty(Long partyId, User user) {
return partyRepository.findById(partyId)
.orElseThrow(PartyNotFoundException::new);
}

private Hive getHive(Long hiveId) {

return hiveRepository.findById(hiveId)
.orElseThrow(NotFoundHiveException::new);
}

private Party getUserParty(Long partyId, User user) {

return partyRepository.findById(partyId)
.orElseThrow(PartyNotFoundException::new);
}

// 파티 조회 및 예외 처리
private Party getParty(Long hiveId, Long partyId) {

Hive hive = hiveRepository.findById(hiveId)
.orElseThrow(NotFoundHiveException::new);

Expand All @@ -229,9 +205,8 @@ private Party getParty(Long hiveId, Long partyId) {

// 파티에 속한 사용자 목록 조회
private List<MemberResponseDTO> getPartyMembers(Long partyId) {
return partyUserRepository.findUsersByPartyId(partyId).stream()
.map(partyUser -> new MemberResponseDTO(partyUser.getUser().getUsername(), partyUser.getUser().getEmail()))
.collect(Collectors.toList());

return partyUserService.getPartyMembers(partyId);
}

public List<MyPartyResponseDTO> getPartiesByUserId(Long userId) {
Expand All @@ -241,4 +216,41 @@ public List<MyPartyResponseDTO> getPartiesByUserId(Long userId) {
party.getContent(),party.getHive().getId(),party.getHostId(), party.getDateTime(), party.getCreatedAt(),
party.getModifiedAt(), getPartyMembers(party.getId()))).toList();
}

// 날짜와 시간 정보를 가져와 LocalDateTime 객체 생성
private LocalDateTime getDateTimeFromDto(PartyRequestDTO dto) {
return LocalDateTime.of(
dto.getYear(),
dto.getMonth(),
dto.getDay(),
dto.getHours(),
dto.getMinutes());
}

private LocalDateTime getLocalDateTime(PartyUpdateRequestDTO dto, Party party) {
LocalDateTime currentDateTime = party.getDateTime();
int year = dto.getYear() != null ? dto.getYear() : currentDateTime.getYear();
int month = dto.getMonth() != null ? dto.getMonth() : currentDateTime.getMonthValue();
int day = dto.getDay() != null ? dto.getDay() : currentDateTime.getDayOfMonth();
int hours = dto.getHours() != null ? dto.getHours() : currentDateTime.getHour();
int minutes = dto.getMinutes() != null ? dto.getMinutes() : currentDateTime.getMinute();

return LocalDateTime.of(year, month, day, hours, minutes);
}

// 설정한 파티 시간의 유효성 검증
private void validatePartyTime(LocalDateTime dateTime) {
if (dateTime.isBefore(LocalDateTime.now())) {
throw new InvalidPartyTimeException();
}
}

// PartyResponseDTO 생성 로직
private PartyResponseDTO createPartyResponseDTO(Party party) {
List<MemberResponseDTO> members = getPartyMembers(party.getId());
return new PartyResponseDTO(party.getId(), party.getTitle(),
party.getUsername(), party.getContent(), party.getDateTime(),
party.getCreatedAt(), party.getModifiedAt(), members);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,6 @@ public interface HiveUserRepository extends JpaRepository<HiveUser, HiveUserPK>,

@Query("SELECT hu.hive FROM HiveUser hu WHERE hu.user.id = :userId and hu.hive.isDeleted = false ")
List<Hive> findAllHiveByHiveUser(Long userId);

boolean existsByUserIdAndHiveId(Long userId, Long hiveId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.HHive.hhive.domain.relationship.partyuser.service;

import com.HHive.hhive.domain.party.dto.MemberResponseDTO;
import com.HHive.hhive.domain.party.entity.Party;
import com.HHive.hhive.domain.relationship.hiveuser.repository.HiveUserRepository;
import com.HHive.hhive.domain.relationship.partyuser.entity.PartyUser;
import com.HHive.hhive.domain.relationship.partyuser.pk.PartyUserPK;
import com.HHive.hhive.domain.relationship.partyuser.repository.PartyUserRepository;
import com.HHive.hhive.domain.user.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Transactional
public class PartyUserService {

private final HiveUserRepository hiveUserRepository;
private final PartyUserRepository partyUserRepository;

// Hive 가입 여부 확인 메서드
public boolean isUserMemberOfHive(Long userId, Long hiveId) {
return hiveUserRepository.existsByUserIdAndHiveId(userId, hiveId);
}

public void addPartyUser(User user, Party party) {
PartyUser partyUser = new PartyUser(user, party);
partyUserRepository.save(partyUser);
}

public void removePartyUser(Long userId, Long partyId) {
PartyUserPK partyUserPK = new PartyUserPK(userId, partyId);
partyUserRepository.deleteById(partyUserPK);
}

public List<MemberResponseDTO> getPartyMembers(Long partyId) {
return partyUserRepository.findUsersByPartyId(partyId).stream()
.map(partyUser -> new MemberResponseDTO(partyUser.getUser().getUsername(), partyUser.getUser().getEmail()))
.collect(Collectors.toList());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public enum ErrorCode {
//Party
PARTY_NOT_FOUND_EXCEPTION(404, "해당 파티를 찾을 수 없습니다."),
UNAUTHORIZED_ACCESS_EXCEPTION(403,"해당 파티에 대한 권한이 없습니다."),
NOT_MEMBER_OF_HIVE_EXCEPTION(403,"하이브에 가입 되어 있지 않습니다."),
PARTY_HOST_NOT_RESIGN_EXCEPTION(403,"리더는 파티 탈퇴가 불가능합니다."),
PARTY_HOST_NOT_JOIN_EXCEPTION(403,"리더는 파티 가입이 불가능합니다."),
END_PARTY_NOT_JOIN_EXCEPTION(403,"가입 기간이 끝난 파티 입니다."),
Expand Down
Loading
Loading