sakthivikram/geo-location
0
1package com.georeport.service;2 3import com.georeport.dto.NotificationResponse;4import com.georeport.entity.Issue;5import com.georeport.entity.Notification;6import com.georeport.entity.User;7import com.georeport.mapper.IssueMapper;8import com.georeport.repository.NotificationRepository;9import org.springframework.beans.factory.annotation.Autowired;10import org.springframework.stereotype.Service;11import org.springframework.transaction.annotation.Transactional;12 13import java.util.List;14import java.util.stream.Collectors;15 16/**17 * Service for notification operations.18 */19@Service20public class NotificationService {21 22 @Autowired23 private NotificationRepository notificationRepository;24 25 @Autowired26 private IssueMapper issueMapper;27 28 /**29 * Get all notifications for a user30 */31 @Transactional(readOnly = true)32 public List<NotificationResponse> getUserNotifications(Long userId) {33 return notificationRepository.findByUserIdOrderByCreatedAtDesc(userId)34 .stream()35 .map(issueMapper::toNotificationResponse)36 .collect(Collectors.toList());37 }38 39 /**40 * Get unread notifications for a user41 */42 @Transactional(readOnly = true)43 public List<NotificationResponse> getUnreadNotifications(Long userId) {44 return notificationRepository.findByUserIdAndIsReadFalseOrderByCreatedAtDesc(userId)45 .stream()46 .map(issueMapper::toNotificationResponse)47 .collect(Collectors.toList());48 }49 50 /**51 * Get unread notification count52 */53 @Transactional(readOnly = true)54 public long getUnreadCount(Long userId) {55 return notificationRepository.countByUserIdAndIsReadFalse(userId);56 }57 58 /**59 * Mark notification as read60 */61 @Transactional62 public void markAsRead(Long notificationId) {63 notificationRepository.findById(notificationId).ifPresent(notification -> {64 notification.setIsRead(true);65 notificationRepository.save(notification);66 });67 }68 69 /**70 * Mark all notifications as read for a user71 */72 @Transactional73 public void markAllAsRead(Long userId) {74 notificationRepository.markAllAsRead(userId);75 }76 77 /**78 * Create a new notification for a user79 */80 @Transactional81 public Notification createNotification(User user, String title, String message, String type, Long issueId) {82 Notification notification = Notification.builder()83 .user(user)84 .title(title)85 .message(message)86 .type(type)87 .isRead(false)88 .build();89 90 // Set issue if provided91 if (issueId != null) {92 // We need to set the issue, but we don't want to inject IssueRepository here93 // Instead, we'll use a reference94 Issue issue = new Issue();95 issue.setId(issueId);96 notification.setIssue(issue);97 }98 99 return notificationRepository.save(notification);100 }101}102 