Skip to content
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
@@ -0,0 +1,21 @@
package com.example.RealMatch.notification.application.dto;

import com.example.RealMatch.notification.domain.entity.enums.NotificationKind;
import com.example.RealMatch.notification.domain.entity.enums.ReferenceType;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class CreateNotificationCommand {

private final Long userId;
private final NotificationKind kind;
private final String title;
private final String body;
private final ReferenceType referenceType;
private final String referenceId;
private final Long campaignId;
private final Long proposalId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package com.example.RealMatch.notification.application.service;

import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.RealMatch.global.exception.CustomException;
import com.example.RealMatch.notification.domain.entity.Notification;
import com.example.RealMatch.notification.domain.entity.enums.NotificationCategory;
import com.example.RealMatch.notification.domain.entity.enums.NotificationKind;
import com.example.RealMatch.notification.domain.repository.NotificationRepository;
import com.example.RealMatch.notification.exception.NotificationErrorCode;
import com.example.RealMatch.notification.presentation.dto.response.NotificationDateGroup;
import com.example.RealMatch.notification.presentation.dto.response.NotificationListResponse;
import com.example.RealMatch.notification.presentation.dto.response.NotificationResponse;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class NotificationQueryService {

private final NotificationRepository notificationRepository;

private static final DateTimeFormatter DATE_LABEL_FORMATTER =
DateTimeFormatter.ofPattern("yy.MM.dd (E)", Locale.KOREAN);

public NotificationListResponse getNotifications(Long userId, String filter, int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));

List<NotificationKind> kinds = resolveKinds(filter);

Page<Notification> notificationPage;
if (kinds == null) {
notificationPage = notificationRepository.findByUserId(userId, pageRequest);
} else {
notificationPage = notificationRepository.findByUserIdAndKindIn(userId, kinds, pageRequest);
}

List<NotificationResponse> items = notificationPage.getContent().stream()
.map(NotificationResponse::from)
.toList();

List<NotificationDateGroup> groups = buildDateGroups(notificationPage.getContent());

long unreadCount = notificationRepository.countUnreadByUserId(userId);

return new NotificationListResponse(
items,
groups,
unreadCount,
notificationPage.getTotalElements(),
notificationPage.getTotalPages(),
notificationPage.getNumber(),
notificationPage.getSize()
);
}

public long getUnreadCount(Long userId) {
return notificationRepository.countUnreadByUserId(userId);
}

private List<NotificationKind> resolveKinds(String filter) {
if (filter == null || "ALL".equalsIgnoreCase(filter)) {
return null;
}

try {
NotificationCategory category = NotificationCategory.valueOf(filter.toUpperCase());
return category.getKinds();
} catch (IllegalArgumentException e) {
throw new CustomException(NotificationErrorCode.NOTIFICATION_INVALID_FILTER);
}
Comment thread
1000hyehyang marked this conversation as resolved.
}

private List<NotificationDateGroup> buildDateGroups(List<Notification> notifications) {
return notifications.stream()
.collect(Collectors.groupingBy(
n -> n.getCreatedAt().toLocalDate(),
LinkedHashMap::new,
Collectors.counting()
))
.entrySet().stream()
.map(entry -> NotificationDateGroup.of(
entry.getKey(),
entry.getValue().intValue(),
DATE_LABEL_FORMATTER))
.toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.example.RealMatch.notification.application.service;

import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.RealMatch.global.exception.CustomException;
import com.example.RealMatch.notification.application.dto.CreateNotificationCommand;
import com.example.RealMatch.notification.domain.entity.Notification;
import com.example.RealMatch.notification.domain.repository.NotificationRepository;
import com.example.RealMatch.notification.exception.NotificationErrorCode;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
@Transactional
public class NotificationService {

private final NotificationRepository notificationRepository;

public Notification create(CreateNotificationCommand command) {
Notification notification = Notification.builder()
.userId(command.getUserId())
.kind(command.getKind())
.title(command.getTitle())
.body(command.getBody())
.referenceType(command.getReferenceType())
.referenceId(command.getReferenceId())
.campaignId(command.getCampaignId())
.proposalId(command.getProposalId())
.build();

return notificationRepository.save(notification);
}

public void markAsRead(Long userId, UUID notificationId) {
Notification notification = findNotificationForUser(userId, notificationId);
notification.markAsRead();
}

public int markAllAsRead(Long userId) {
return notificationRepository.markAllAsRead(userId);
}

public void softDelete(Long userId, UUID notificationId) {
Notification notification = findNotificationForUser(userId, notificationId);
notification.softDelete();
}

private Notification findNotificationForUser(Long userId, UUID notificationId) {
Notification notification = notificationRepository.findById(notificationId)
.orElseThrow(() -> new CustomException(NotificationErrorCode.NOTIFICATION_NOT_FOUND));

if (!notification.getUserId().equals(userId)) {
throw new CustomException(NotificationErrorCode.NOTIFICATION_FORBIDDEN);
}

return notification;
}
Comment thread
1000hyehyang marked this conversation as resolved.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.example.RealMatch.notification.domain.entity;

import java.util.UUID;

import com.example.RealMatch.global.common.DeleteBaseEntity;
import com.example.RealMatch.notification.domain.entity.enums.NotificationKind;
import com.example.RealMatch.notification.domain.entity.enums.ReferenceType;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Table(name = "notification", indexes = {
@Index(name = "idx_notification_user_read_created", columnList = "user_id, is_read, created_at"),
@Index(name = "idx_notification_user_created", columnList = "user_id, created_at"),
@Index(name = "idx_notification_user_kind", columnList = "user_id, kind")
})
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Notification extends DeleteBaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
@Column(columnDefinition = "BINARY(16)")
private UUID id;

@Column(name = "user_id", nullable = false)
private Long userId;

@Enumerated(EnumType.STRING)
@Column(name = "kind", nullable = false, length = 30)
private NotificationKind kind;

@Column(name = "title", nullable = false)
private String title;

@Column(name = "body", nullable = false, length = 1000)
private String body;

@Enumerated(EnumType.STRING)
@Column(name = "reference_type", length = 30)
private ReferenceType referenceType;

@Column(name = "reference_id", length = 36)
private String referenceId;

@Column(name = "campaign_id")
private Long campaignId;

@Column(name = "proposal_id")
private Long proposalId;

@Column(name = "is_read", nullable = false)
private boolean isRead = false;

@Builder
protected Notification(Long userId, NotificationKind kind, String title, String body,
ReferenceType referenceType, String referenceId,
Long campaignId, Long proposalId) {
this.userId = userId;
this.kind = kind;
this.title = title;
this.body = body;
this.referenceType = referenceType;
this.referenceId = referenceId;
this.campaignId = campaignId;
this.proposalId = proposalId;
}

public void markAsRead() {
this.isRead = true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.example.RealMatch.notification.domain.entity.enums;

import java.util.Arrays;
import java.util.List;

public enum NotificationCategory {

PROPOSAL,
MATCHING,
SETTLEMENT,
CHAT;

public List<NotificationKind> getKinds() {
return Arrays.stream(NotificationKind.values())
.filter(kind -> kind.getCategory() == this)
.toList();
}
Comment thread
1000hyehyang marked this conversation as resolved.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example.RealMatch.notification.domain.entity.enums;

public enum NotificationKind {

// 제안 관련 (PROPOSAL 카테고리)
PROPOSAL_RECEIVED(NotificationCategory.PROPOSAL),
PROPOSAL_SENT(NotificationCategory.PROPOSAL),
CAMPAIGN_APPLIED(NotificationCategory.PROPOSAL),

// 매칭 관련 (MATCHING 카테고리)
CAMPAIGN_MATCHED(NotificationCategory.MATCHING),
AUTO_CONFIRMED(NotificationCategory.MATCHING),

// 정산 관련 (SETTLEMENT 카테고리)
CAMPAIGN_COMPLETED(NotificationCategory.SETTLEMENT),
SETTLEMENT_READY(NotificationCategory.SETTLEMENT),

// 채팅 (CHAT 카테고리)
CHAT_MESSAGE(NotificationCategory.CHAT);

private final NotificationCategory category;

NotificationKind(NotificationCategory category) {
this.category = category;
}

public NotificationCategory getCategory() {
return category;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.example.RealMatch.notification.domain.entity.enums;

public enum ReferenceType {

CAMPAIGN_PROPOSAL,
CAMPAIGN_APPLY,
CAMPAIGN
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.example.RealMatch.notification.domain.repository;

import java.util.Collection;
import java.util.UUID;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.example.RealMatch.notification.domain.entity.Notification;
import com.example.RealMatch.notification.domain.entity.enums.NotificationKind;

public interface NotificationRepository extends JpaRepository<Notification, UUID> {

Page<Notification> findByUserId(Long userId, Pageable pageable);

Page<Notification> findByUserIdAndKindIn(Long userId, Collection<NotificationKind> kinds, Pageable pageable);

@Query("SELECT COUNT(n) FROM Notification n WHERE n.userId = :userId AND n.isRead = false AND n.isDeleted = false")
long countUnreadByUserId(@Param("userId") Long userId);

/**
* 해당 유저의 미읽음 알림을 모두 읽음 처리한다 (벌크 UPDATE)
*/
@Modifying(clearAutomatically = true)
@Query("UPDATE Notification n SET n.isRead = true WHERE n.userId = :userId AND n.isRead = false AND n.isDeleted = false")
int markAllAsRead(@Param("userId") Long userId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.example.RealMatch.notification.exception;

import org.springframework.http.HttpStatus;

import com.example.RealMatch.global.presentation.code.BaseErrorCode;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public enum NotificationErrorCode implements BaseErrorCode {

NOTIFICATION_INVALID_FILTER(HttpStatus.BAD_REQUEST, "NOTIFICATION_400_1", "유효하지 않은 필터 값입니다."),
NOTIFICATION_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTIFICATION_404_1", "알림을 찾을 수 없습니다."),
NOTIFICATION_FORBIDDEN(HttpStatus.FORBIDDEN, "NOTIFICATION_403_1", "해당 알림에 대한 권한이 없습니다.");

private final HttpStatus status;
private final String code;
private final String message;
}
Loading
Loading