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
Expand Up @@ -3,7 +3,13 @@
import java.util.List;
import kr.ac.kookmin.stream.api.admin.welfare.rental.response.AdminRentalHistoryResponse;
import kr.ac.kookmin.stream.common.LockExecutor;
import kr.ac.kookmin.stream.common.OutboxWriter;
import kr.ac.kookmin.stream.common.Role;
import kr.ac.kookmin.stream.common.event.DomainEvent;
import kr.ac.kookmin.stream.common.event.RentalApproved;
import kr.ac.kookmin.stream.common.event.RentalRejected;
import kr.ac.kookmin.stream.common.event.RentalReturnApproved;
import kr.ac.kookmin.stream.common.event.RentalReturnCompleted;
import kr.ac.kookmin.stream.member.domain.member.domain.Member;
import kr.ac.kookmin.stream.member.domain.member.service.MemberService;
import kr.ac.kookmin.stream.common.BusinessException;
Expand All @@ -27,6 +33,7 @@ public class AdminRentalStatusUpdateUseCase {
private final MemberService memberService;
private final ItemService itemService;
private final AdminRentalHistoryService adminRentalHistoryService;
private final OutboxWriter outboxWriter;

public AdminRentalHistoryResponse updateStatus(Long historyId, RentalStatus requestedStatus, Long workerId) {
return lockExecutor.executeOptimistic(() -> {
Expand All @@ -35,6 +42,7 @@ public AdminRentalHistoryResponse updateStatus(Long historyId, RentalStatus requ
RentalRecord current = adminRentalHistoryService.getById(historyId);
RentalStatus previousStatus = current.history().getRentalStatus();
Item item = current.item();
String itemName = item != null ? item.getName() : null;

boolean isConsumable = requestedStatus == RentalStatus.CONFIRMED
&& item != null && item.getType() == ItemType.CONSUMABLE;
Expand All @@ -52,6 +60,10 @@ public AdminRentalHistoryResponse updateStatus(Long historyId, RentalStatus requ
item = itemService.decreaseStock(history.getItemId(), history.getRentedCount());
}

if (previousStatus != newStatus) {
recordStatusChangeEvent(requestedStatus, history.getMemberId(), history.getId(), itemName);
}

Member renter = memberService.getMapByIds(List.of(history.getMemberId())).get(history.getMemberId());
return AdminRentalHistoryResponse.from(new RentalRecord(history, item), renter);
});
Expand All @@ -63,4 +75,19 @@ private void validateIsAdmin(Long workerId) {
throw new BusinessException(RentalErrorCode.WORKER_NOT_ADMIN);
}
}

// 소모품은 승인 즉시 RETURNED로 저장되지만(위 isConsumable), 학생에게는 "반납 완료"가 아니라
// "승인" 알림을 보낸다. 그래서 저장된 newStatus가 아니라 admin이 실제로 요청한 requestedStatus로 알림 종류를 정한다
private void recordStatusChangeEvent(RentalStatus requestedStatus, Long memberId, Long historyId, String itemName) {
DomainEvent event = switch (requestedStatus) {
case CONFIRMED -> new RentalApproved(memberId, historyId, itemName);
case REJECTED -> new RentalRejected(memberId, historyId, itemName);
case RETURN_CONFIRMED -> new RentalReturnApproved(memberId, historyId, itemName);
case RETURNED -> new RentalReturnCompleted(memberId, historyId, itemName);
default -> null;
};
if (event != null) {
outboxWriter.record(event);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
import java.time.LocalDateTime;
import kr.ac.kookmin.stream.common.BusinessException;
import kr.ac.kookmin.stream.common.LockExecutor;
import kr.ac.kookmin.stream.common.OutboxWriter;
import kr.ac.kookmin.stream.common.event.RentalApplied;
import kr.ac.kookmin.stream.internal.domain.config.service.AdminConfigValueService;
import kr.ac.kookmin.stream.welfare.domain.fee.service.PayerService;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.Item;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalBlockPeriodConfigKeys;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalErrorCode;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalHistory;
import kr.ac.kookmin.stream.welfare.domain.rental.service.ItemService;
import kr.ac.kookmin.stream.welfare.domain.rental.service.RentalHistoryService;
import lombok.RequiredArgsConstructor;
Expand All @@ -24,6 +27,7 @@ public class RentalApplyUseCase {
private final ItemService itemService;
private final RentalHistoryService rentalHistoryService;
private final AdminConfigValueService adminConfigValueService;
private final OutboxWriter outboxWriter;

public void apply(Long memberId, Long itemId, int count, int rentAtHour, int rentAtMinute, boolean ignoreDuplicate) {
validateNotBlocked();
Expand All @@ -39,7 +43,10 @@ public void apply(Long memberId, Long itemId, int count, int rentAtHour, int ren

LocalDateTime now = LocalDateTime.now();
LocalDateTime rentAt = LocalDate.now().atTime(rentAtHour, rentAtMinute);
rentalHistoryService.create(item, memberId, null, count, now, rentAt);
RentalHistory history = rentalHistoryService.create(item, memberId, null, count, now, rentAt);

outboxWriter.record(new RentalApplied(
memberId, history.getId(), item.getName(), "%02d:%02d".formatted(rentAtHour, rentAtMinute)));
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.usecase;

import kr.ac.kookmin.stream.common.LockExecutor;
import kr.ac.kookmin.stream.common.OutboxWriter;
import kr.ac.kookmin.stream.common.event.RentalApplicationCanceled;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.Item;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalHistory;
import kr.ac.kookmin.stream.welfare.domain.rental.service.ItemService;
import kr.ac.kookmin.stream.welfare.domain.rental.service.RentalHistoryService;
Expand All @@ -15,11 +18,14 @@ public class RentalCancelUseCase {
private final LockExecutor lockExecutor;
private final RentalHistoryService rentalHistoryService;
private final ItemService itemService;
private final OutboxWriter outboxWriter;

public void cancel(Long memberId, Long historyId) {
lockExecutor.executeOptimistic(() -> {
RentalHistory history = rentalHistoryService.cancel(memberId, historyId);
itemService.increaseStock(history.getItemId(), history.getRentedCount());
Item item = itemService.increaseStock(history.getItemId(), history.getRentedCount());

outboxWriter.record(new RentalApplicationCanceled(memberId, history.getId(), item.getName()));
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package kr.ac.kookmin.stream.common.event;

/** 회원이 자신의 대여 신청(승인 전)을 취소했다. 운영진 공용 알림에만 쓰인다. */
public record RentalApplicationCanceled(
Long memberId, Long rentalHistoryId, String itemName
) implements DomainEvent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package kr.ac.kookmin.stream.common.event;

/** 회원이 물품 대여를 신청했다. 물품명·대여 시각은 알림 문구에 쓰려고 신청 시점의 값을 싣는다. */
public record RentalApplied(
Long memberId, Long rentalHistoryId, String itemName, String rentAtTime
) implements DomainEvent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package kr.ac.kookmin.stream.common.event;

/** 운영진이 대여 신청을 승인했다. */
public record RentalApproved(Long memberId, Long rentalHistoryId, String itemName) implements DomainEvent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package kr.ac.kookmin.stream.common.event;

/** 운영진이 대여 신청을 반려했다. */
public record RentalRejected(Long memberId, Long rentalHistoryId, String itemName) implements DomainEvent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package kr.ac.kookmin.stream.common.event;

/** 회원이 반납을 신청했다. */
public record RentalReturnApplied(
Long memberId, Long rentalHistoryId, String itemName
) implements DomainEvent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package kr.ac.kookmin.stream.common.event;

/** 운영진이 반납 신청을 승인했다. */
public record RentalReturnApproved(Long memberId, Long rentalHistoryId, String itemName) implements DomainEvent {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package kr.ac.kookmin.stream.common.event;

/** 반납이 완료됐다. 급하게 확인할 내용이 아니라 알림함에만 남기고 푸시는 보내지 않는다. */
public record RentalReturnCompleted(Long memberId, Long rentalHistoryId, String itemName) implements DomainEvent {}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ public enum NotificationType {
RENTAL_DUE_SOON(NotificationCategory.BILLILGE, "반납까지 1시간 남았어요.", "늦지 않게 %s을(를) 반납해 주세요."),
RENTAL_OVERDUE(NotificationCategory.BILLILGE, "반납 기한이 지났어요.", "학생회실에 방문해 %s을(를) 반납해 주세요."),

// 운영진 공용 알림. 값: 이름, 학번, (APPLY만)대여 시각, 물품명
ADMIN_RENTAL_APPLY(NotificationCategory.BILLILGE, "%s(%s) 님이 %s에 %s 대여를 신청했어요.", null),
Comment thread
jjunh33 marked this conversation as resolved.
Resolved
ADMIN_RENTAL_CANCEL(NotificationCategory.BILLILGE, "%s(%s) 님이 %s 대여 신청을 취소했어요.", null),
ADMIN_RETURN_APPLY(NotificationCategory.BILLILGE, "%s(%s) 님이 %s 반납을 신청했어요.", null),

// 값: 물품명
RENTAL_APPLY(NotificationCategory.BILLILGE, "%s 대여를 신청했어요!", "관리자가 처리할 때까지 잠시만 기다려 주세요."),
RENTAL_APPROVED(NotificationCategory.BILLILGE, "관리자가 %s 대여 신청을 승인했어요!", "대여 시각에 과방으로 오시면 물품을 빌릴 수 있어요."),
RENTAL_REJECTED(NotificationCategory.BILLILGE, "%s 대여 신청이 반려되었어요.", "자세한 사항은 소프트웨어융합대학 카카오톡에 문의해 주세요."),
RETURN_APPLY(NotificationCategory.BILLILGE, "%s 반납을 신청했어요!", "관리자가 처리할 때까지 잠시만 기다려 주세요."),
RETURN_APPROVED(NotificationCategory.BILLILGE, "관리자가 %s 반납 신청을 승인했어요!", "과방으로 오시면 물품을 반납할 수 있어요."),
RETURN_COMPLETED(NotificationCategory.BILLILGE, "%s 반납을 완료했어요.", null),

// 값: 없음
NOTICE_CREATED(NotificationCategory.NOTICE, "새로운 공지사항이 올라왔어요.", "자세한 내용을 확인해 주세요.");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,7 @@ public interface NotificationRecipientRepository {
List<Long> findAllActiveMemberIds();
List<PushTarget> findPushTargets(Collection<Long> memberIds);
List<PushTarget> findAllPushTargets();
/** 운영진(Role.ADMIN) 전체의 푸시 대상. 관리자 공용 알림을 보낼 때 쓴다. */
List<PushTarget> findAllAdminPushTargets();
int clearFcmTokens(Collection<String> fcmTokens);
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

/**
* 알림 한 건을 수신자에게 보낸다. 알림함에는 수신자 전원에게 저장하고, 푸시는 그 카테고리를 켜 두고 토큰이 있는 회원에게만 보낸다.
* 운영진 업무 알림({@link #dispatchToAdmins})은 예외로, 개인 알림 설정과 무관하게 전원에게 보낸다.
* <p>
* 아웃박스 릴레이가 부르는 리스너에서 트랜잭션 없이 호출된다. 알림함 저장은 {@code saveAll}의 트랜잭션으로 한꺼번에 반영하고,
* 저장이 끝난 뒤 트랜잭션 밖에서 푸시를 보낸다. 알림함 저장이 실패하면 예외가 리스너까지 올라가 아웃박스가 다시 발행한다.
Expand Down Expand Up @@ -54,6 +55,22 @@ void dispatchToAll(NotificationType type, List<String> formatValues, long target
send(type, formatValues, targetId, recipients, pushTargets);
}

/**
* 특정 회원이 아니라 운영진 전체가 공동으로 보는 알림 한 건을 만든다.
* 운영진 수만큼 행을 만들지 않고 {@code memberId}가 없는 행 하나만 저장하므로, 읽음 여부도 운영진 전체가 공유한다.
*/
void dispatchToAdmins(NotificationType type, List<String> formatValues, long targetId) {
notificationRepository.saveAll(List.of(Notification.create(null, type, formatValues, targetId)));
// 운영진 업무 알림(신청/취소/반납신청 등)은 개인 알림 설정과 무관하게 전원에게 보낸다
sendPush(type, formatValues, targetId, notificationRecipientRepository.findAllAdminPushTargets(), 1);
}

/** 지정한 회원에게 알림함에만 저장한다(푸시 없음). 급하게 확인할 내용이 아닌 알림에 쓴다. */
void dispatchWithoutPush(NotificationType type, List<String> formatValues, long targetId, Collection<Long> memberIds) {
List<Long> recipients = List.copyOf(new LinkedHashSet<>(memberIds));
saveNotifications(type, formatValues, targetId, recipients);
}

private void send(
NotificationType type,
List<String> formatValues,
Expand All @@ -64,13 +81,22 @@ private void send(
if (recipients.isEmpty()) {
return;
}
notificationRepository.saveAll(recipients.stream()
.map(memberId -> Notification.create(memberId, type, formatValues, targetId))
.toList());
saveNotifications(type, formatValues, targetId, recipients);
List<PushTarget> accepting = pushTargets.stream()
.filter(target -> target.accepts(type.getCategory()))
.toList();
sendPush(type, formatValues, targetId, accepting, recipients.size());
}

// 한 기기의 토큰이 여러 회원 행에 남아 있을 수 있어 토큰 단위로 중복을 지운다. 그대로 보내면 같은 기기에 여러 번 간다
// 한 기기의 토큰이 여러 회원 행에 남아 있을 수 있어 토큰 단위로 중복을 지운다. 그대로 보내면 같은 기기에 여러 번 간다
private void sendPush(
NotificationType type,
List<String> formatValues,
long targetId,
List<PushTarget> pushTargets,
int recipientCount
) {
List<String> tokens = pushTargets.stream()
.filter(target -> target.accepts(type.getCategory()))
.map(PushTarget::fcmToken)
.distinct()
.toList();
Expand All @@ -80,7 +106,16 @@ private void send(
invalidTokenCount = clearInvalidTokens(result.tokensWith(PushSendStatus.INVALID_TOKEN));
}
log.info("알림 발송: type={}, targetId={}, recipientCount={}, pushTokenCount={}, invalidTokenCount={}",
type, targetId, recipients.size(), tokens.size(), invalidTokenCount);
type, targetId, recipientCount, tokens.size(), invalidTokenCount);
}

private void saveNotifications(NotificationType type, List<String> formatValues, long targetId, List<Long> recipients) {
if (recipients.isEmpty()) {
return;
}
notificationRepository.saveAll(recipients.stream()
.map(memberId -> Notification.create(memberId, type, formatValues, targetId))
.toList());
}

private PushMessage toPushMessage(NotificationType type, List<String> formatValues, long targetId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,17 @@
import kr.ac.kookmin.stream.common.event.LockerAssignmentCanceled;
import kr.ac.kookmin.stream.common.event.LockerUsageEndingSoon;
import kr.ac.kookmin.stream.common.event.NoticeCreated;
import kr.ac.kookmin.stream.common.event.RentalApplicationCanceled;
import kr.ac.kookmin.stream.common.event.RentalApplied;
import kr.ac.kookmin.stream.common.event.RentalApproved;
import kr.ac.kookmin.stream.common.event.RentalDueSoon;
import kr.ac.kookmin.stream.common.event.RentalOverdue;
import kr.ac.kookmin.stream.common.event.RentalRejected;
import kr.ac.kookmin.stream.common.event.RentalReturnApplied;
import kr.ac.kookmin.stream.common.event.RentalReturnApproved;
import kr.ac.kookmin.stream.common.event.RentalReturnCompleted;
import kr.ac.kookmin.stream.member.domain.member.domain.Member;
import kr.ac.kookmin.stream.member.domain.member.service.MemberService;
import kr.ac.kookmin.stream.member.domain.notification.domain.NotificationType;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
Expand All @@ -27,6 +36,7 @@
class NotificationEventListener {

private final NotificationDispatcher notificationDispatcher;
private final MemberService memberService;

// 신청·취소 알림은 누르면 신청 내역 상세로 가야 하므로 행사가 아니라 신청 ID를 대상으로 준다
@EventListener
Expand Down Expand Up @@ -102,4 +112,64 @@ public void on(RentalOverdue event) {
notificationDispatcher.dispatch(
NotificationType.RENTAL_OVERDUE, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));
}

// 신청은 본인과 운영진 모두에게 간다
@EventListener
public void on(RentalApplied event) {
notificationDispatcher.dispatch(
NotificationType.RENTAL_APPLY, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));

Member member = memberService.getById(event.memberId());
notificationDispatcher.dispatchToAdmins(
NotificationType.ADMIN_RENTAL_APPLY,
List.of(member.getName(), member.getStudentId(), event.rentAtTime(), event.itemName()),
event.rentalHistoryId());
}

// 본인이 취소한 신청이라 본인에게는 알림이 가지 않는다. 운영진만 안다
@EventListener
public void on(RentalApplicationCanceled event) {
Member member = memberService.getById(event.memberId());
notificationDispatcher.dispatchToAdmins(
NotificationType.ADMIN_RENTAL_CANCEL,
List.of(member.getName(), member.getStudentId(), event.itemName()),
event.rentalHistoryId());
}

@EventListener
public void on(RentalReturnApplied event) {
notificationDispatcher.dispatch(
NotificationType.RETURN_APPLY, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));

Member member = memberService.getById(event.memberId());
notificationDispatcher.dispatchToAdmins(
NotificationType.ADMIN_RETURN_APPLY,
List.of(member.getName(), member.getStudentId(), event.itemName()),
event.rentalHistoryId());
}

@EventListener
public void on(RentalApproved event) {
notificationDispatcher.dispatch(
NotificationType.RENTAL_APPROVED, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));
}

@EventListener
public void on(RentalRejected event) {
notificationDispatcher.dispatch(
NotificationType.RENTAL_REJECTED, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));
}

@EventListener
public void on(RentalReturnApproved event) {
notificationDispatcher.dispatch(
NotificationType.RETURN_APPROVED, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));
}

// 급하게 확인할 내용이 아니라 알림함에만 남기고 푸시는 보내지 않는다
@EventListener
public void on(RentalReturnCompleted event) {
notificationDispatcher.dispatchWithoutPush(
NotificationType.RETURN_COMPLETED, List.of(event.itemName()), event.rentalHistoryId(), List.of(event.memberId()));
}
}
Loading