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

🚑 Hot Fix - Article UI Error & Push Notification #77

Merged
merged 2 commits into from
Dec 9, 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
Expand Up @@ -19,7 +19,7 @@ class ArticleBriefDefaultItemView extends StatelessWidget {
return GestureDetector(
onTap: onTap,
child: Container(
height: 160,
height: 176,
padding: const EdgeInsets.symmetric(vertical: 16),
color: ColorSystem.white,
child: Column(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ArticleSummaryDefaultItemView extends StatelessWidget {
return GestureDetector(
onTap: onTap,
child: Container(
height: 180,
height: 196,
padding: const EdgeInsets.symmetric(vertical: 16),
color: ColorSystem.white,
child: Row(
Expand Down Expand Up @@ -54,9 +54,7 @@ class ArticleSummaryDefaultItemView extends StatelessWidget {
const SizedBox(height: 4),
Text(
state.preview,
style: FontSystem.Sub3.copyWith(
fontSize: 16,
),
style: FontSystem.Sub3,
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
Expand Down
2 changes: 1 addition & 1 deletion client-app/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: wooahan
description: "Senior Care Service – We're Still Going Strong"

version: 1.0.3+3
version: 1.0.3+6

environment:
sdk: '>=3.4.3 <4.0.0'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,9 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.dongguk.dscd.wooahan.api.core.exception.error.ErrorCode;
import org.dongguk.dscd.wooahan.api.core.exception.type.CommonException;
import org.dongguk.dscd.wooahan.api.question.domain.mysql.Answer;
import org.dongguk.dscd.wooahan.api.question.domain.mysql.Question;
import org.dongguk.dscd.wooahan.api.question.event.CreateQuestionEvent;
import org.dongguk.dscd.wooahan.api.question.repository.mysql.AnswerRepository;
import org.dongguk.dscd.wooahan.api.question.repository.mysql.QuestionRepository;
import org.dongguk.dscd.wooahan.api.question.service.CreateAnswerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
Expand All @@ -27,8 +21,7 @@ public class GenerationListener {
@Value("${inner-services.generation.url}")
String generationServiceUrl;

private final QuestionRepository questionRepository;
private final AnswerRepository answerRepository;
private final CreateAnswerService createAnswerService;

private final ObjectMapper objectMapper;

Expand All @@ -37,9 +30,6 @@ public class GenerationListener {
@Async
@EventListener(classes = {CreateQuestionEvent.class})
public void handleCreateQuestionEvent(CreateQuestionEvent event) {
Question question = questionRepository.findById(event.questionId())
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_RESOURCE));

String similarAnswer = "";

try {
Expand All @@ -48,20 +38,18 @@ public void handleCreateQuestionEvent(CreateQuestionEvent event) {
.headers(httpHeaders -> {
httpHeaders.set("Content-Type", "application/json");
})
.body(generateMessageJson(question.getContent()))
.body(generateMessageJson(event.content()))
.retrieve()
.body(GenerationResult.class);

similarAnswer = (String) response.data().get("result");
} catch (Exception ignored) {
}

Answer answer = Answer.builder()
.question(question)
.content(similarAnswer)
.build();

answerRepository.save(answer);
createAnswerService.execute(
event.questionId(),
similarAnswer
);
}

private String generateMessageJson(String content) throws JsonProcessingException {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.dongguk.dscd.wooahan.api.core.listener;

import lombok.RequiredArgsConstructor;
import org.dongguk.dscd.wooahan.api.notification.service.NotificationService;
import org.dongguk.dscd.wooahan.api.question.event.CreateAnswerEvent;
import org.dongguk.dscd.wooahan.api.question.event.CreateQuestionEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class NotificationListener {

private final NotificationService notificationService;

@Async
@EventListener(classes = {CreateAnswerEvent.class})
public void handleCreateAnswerEvent(
CreateAnswerEvent event
) {
notificationService.sendPushNotification(event.userId());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public void sendPushNotificationOnBreakfast() {

// 3. 사용자 목록을 통해 알림 메시지 생성
List<Message> messageList = recieverList.stream()
.map(user -> convertToMap(user, ETime.BREAKFAST))
.map(user -> convertToMapForMedication(user, ETime.BREAKFAST))
.toList();

// 4. 알림 메시지 전송
Expand All @@ -66,7 +66,7 @@ public void sendPushNotificationOnLunch() {

// 3. 사용자 목록을 통해 알림 메시지 생성
List<Message> messageList = recieverList.stream()
.map(user -> convertToMap(user, ETime.LUNCH))
.map(user -> convertToMapForMedication(user, ETime.LUNCH))
.toList();

// 4. 알림 메시지 전송
Expand All @@ -93,7 +93,7 @@ public void sendPushNotificationOnDinner() {

// 3. 사용자 목록을 통해 알림 메시지 생성
List<Message> messageList = recieverList.stream()
.map(user -> convertToMap(user, ETime.DINNER))
.map(user -> convertToMapForMedication(user, ETime.DINNER))
.toList();

// 4. 알림 메시지 전송
Expand All @@ -105,7 +105,44 @@ public void sendPushNotificationOnDinner() {
}
}

Message convertToMap(User user, ETime time) {
public void sendPushNotification(
UUID userId,
ETime time
) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_USER));

if (!user.getIsAllowedNotification() || user.getDeviceToken() == null) {
return;
}

Message message = convertToMapForMedication(user, time);

try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
}

public void sendPushNotification(
UUID userId
){
User user = userRepository.findById(userId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_USER));

if (!user.getIsAllowedNotification() || user.getDeviceToken() == null) {
return;
}

Message message = convertToMapForMedication(user);

try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
}

Message convertToMapForMedication(User user, ETime time) {
String content = switch (time) {
case BREAKFAST -> String.format(BREAKFAST_NOTIFICATION_CONTENT_FORM, user.getNickname());
case LUNCH -> String.format(LUNCH_NOTIFICATION_CONTENT_FORM, user.getNickname());
Expand Down Expand Up @@ -148,18 +185,24 @@ Message convertToMap(User user, ETime time) {
.build();
}

public void sendPushNotification(
UUID userId,
ETime time
) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_USER));

Message message = convertToMap(user, time);

try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
Message convertToMapForMedication(User user) {
return Message.builder()
.setToken(user.getDeviceToken())
.setNotification(
Notification.builder()
.setTitle("우아한")
.setBody("작성한 질문에 답변이 등록되었어요!")
.build()
)
.setApnsConfig(
ApnsConfig.builder()
.setAps(
Aps.builder()
.setSound("default")
.build()
)
.build()
)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.dongguk.dscd.wooahan.api.question.event;

import java.util.UUID;

public record CreateAnswerEvent(
UUID userId
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.dongguk.dscd.wooahan.api.question.domain.mysql.Question;
import org.dongguk.dscd.wooahan.api.question.dto.projection.ReadQuestionProjection;
import org.dongguk.dscd.wooahan.api.question.repository.mysql.custom.QuestionRepositoryCustom;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

Expand All @@ -20,4 +21,8 @@ public interface QuestionRepository extends JpaRepository<Question, Long>, Quest
WHERE q.id = :id
""")
Optional<ReadQuestionProjection> findByIdWithDetail(Long id);


@EntityGraph(attributePaths = {"creator"})
Optional<Question> findWithUserById(Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
import org.dongguk.dscd.wooahan.api.question.domain.mysql.Answer;
import org.dongguk.dscd.wooahan.api.question.domain.mysql.Question;
import org.dongguk.dscd.wooahan.api.question.dto.request.CreateAnswerDto;
import org.dongguk.dscd.wooahan.api.question.event.CreateAnswerEvent;
import org.dongguk.dscd.wooahan.api.question.repository.mysql.AnswerRepository;
import org.dongguk.dscd.wooahan.api.question.repository.mysql.QuestionRepository;
import org.dongguk.dscd.wooahan.api.question.usecase.CreateAnswerUseCase;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.UUID;
Expand All @@ -27,6 +29,7 @@ public class CreateAnswerService implements CreateAnswerUseCase {
private final ExpertRepository expertRepository;

private final UpdaterScheduler updaterScheduler;
private final ApplicationEventPublisher applicationEventPublisher;

@Override
public void execute(
Expand All @@ -37,7 +40,7 @@ public void execute(
Expert expert = expertRepository.findById(accountId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_EXPERT));

Question question = questionRepository.findById(questionId)
Question question = questionRepository.findWithUserById(questionId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_QUESTION));

Answer answer = Answer.builder()
Expand All @@ -49,5 +52,32 @@ public void execute(
answerRepository.save(answer);

updaterScheduler.removeQuestionTask(questionId);

applicationEventPublisher.publishEvent(
new CreateAnswerEvent(
question.getCreator().getId()
)
);
}

public void execute(
Long questionId,
String similarAnswer
) {
Question question = questionRepository.findWithUserById(questionId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_QUESTION));

Answer answer = Answer.builder()
.question(question)
.content(similarAnswer)
.build();

answerRepository.save(answer);

applicationEventPublisher.publishEvent(
new CreateAnswerEvent(
question.getCreator().getId()
)
);
}
}