Sobes.tech
Senior
79

/* L'entreprise fournit un service d'envoi massif de notifications à d'autres entreprises. Un propriétaire de produit a demandé de créer un système de filtrage des notifications en tenant compte des préférences des utilisateurs. ## Définitions Notification: - id de la notification - type de notification (EMAIL, SMS, PUSH) - destinataire (id de l'utilisateur) - texte du message Le destinataire peut avoir des paramètres de préférences: - canaux de notification autorisés (liste de types) - expéditeurs bloqués (liste d'ids d'expéditeurs) Historique des notifications envoyées: - liste des notifications envoyées à l'utilisateur ## Important Les paramètres des utilisateurs et l'historique des notifications sont fournis par d'autres composants du système. Vous devez concevoir des contrats pour obtenir ces données. Il n'est pas nécessaire de faire de stockage. ## Tâche Écrire un système de filtrage des notifications qui: - reçoit une liste de notifications à filtrer et l'id de l'expéditeur - exclut les notifications qui ne correspondent pas aux préférences de l'utilisateur - met en œuvre une protection contre les messages en double, y compris ceux envoyés dans les dernières 24 heures. Les doublons sont considérés comme des messages avec le même id destinés à un même utilisateur - retourne la liste filtrée de notifications prêtes à être envoyées. L'envoi des notifications ne fait pas partie de votre tâche; une autre équipe s'en chargera. Votre tâche est uniquement le filtrage. */ class NotificationFilter { UserSettingsService userSettingsService; NotificationHistoryService notificationHistoryService; public ??? filter(??? senderId, List<???> msgs) { // TODO implement } } interface UserSettingsService { // TODO any functions } interface NotificationHistoryService { // TODO any functions }

Entreprises à qui on a demandé
Яндекс

Réponse de l'IA

sobes.tech IA

java import java.time.Instant; import java.time.Duration; import java.util.*; import java.util.stream.Collectors;

class Notification { String id; NotificationType type; String recipientId; String text;

// Конструктор, геттеры, сеттеры

}

enum NotificationType { EMAIL, SMS, PUSH }

interface UserSettingsService { /** * Возвращает разрешённые каналы уведомлений для пользователя. */ Set<NotificationType> getAllowedChannels(String userId);

/**
 * Возвращает список заблокированных отправителей для пользователя.
 */
Set<String> getBlockedSenders(String userId);

}

interface NotificationHistoryService { /** * Возвращает список уведомлений, отправленных пользователю за последние 24 часа. */ List<Notification> getNotificationsLast24h(String userId); }

class NotificationFilter { private final UserSettingsService userSettingsService; private final NotificationHistoryService notificationHistoryService;

public NotificationFilter(UserSettingsService userSettingsService, NotificationHistoryService notificationHistoryService) {
    this.userSettingsService = userSettingsService;
    this.notificationHistoryService = notificationHistoryService;
}

/**
 * Фильтрует список уведомлений по предпочтениям пользователей и исключает дубликаты.
 * 
 * @param senderId id отправителя
 * @param msgs список уведомлений для фильтрации
 * @return отфильтрованный список уведомлений
 */
public List<Notification> filter(String senderId, List<Notification> msgs) {
    // Группируем уведомления по получателям
    Map<String, List<Notification>> byRecipient = msgs.stream()
        .collect(Collectors.groupingBy(n -> n.recipientId));

    List<Notification> result = new ArrayList<>();

    for (Map.Entry<String, List<Notification>> entry : byRecipient.entrySet()) {
        String userId = entry.getKey();
        List<Notification> userNotifications = entry.getValue();

        Set<NotificationType> allowedChannels = userSettingsService.getAllowedChannels(userId);
        Set<String> blockedSenders = userSettingsService.getBlockedSenders(userId);

        // Если отправитель заблокирован, пропускаем все уведомления для этого пользователя
        if (blockedSenders.contains(senderId)) {
            continue;
        }

        // Получаем историю уведомлений за последние 24 часа
        List<Notification> history = notificationHistoryService.getNotificationsLast24h(userId);
        Set<String> recentNotificationIds = history.stream()
            .map(n -> n.id)
            .collect(Collectors.toSet());

        // Для защиты от дубликатов учитываем также текущие уведомления
        Set<String> currentNotificationIds = new HashSet<>();

        for (Notification n : userNotifications) {
            // Фильтрация по разрешённым каналам
            if (!allowedChannels.contains(n.type)) {
                continue;
            }

            // Проверка на дубликаты (id + пользователь)
            if (recentNotificationIds.contains(n.id) || currentNotificationIds.contains(n.id)) {
                continue;
            }

            currentNotificationIds.add(n.id);
            result.add(n);
        }
    }

    return result;
}

}


**Объяснение:**
- Интерфейсы `UserSettingsService` и `NotificationHistoryService` предоставляют методы для получения настроек пользователя и истории уведомлений.
- В методе `filter` уведомления группируются по получателям.
- Для каждого пользователя проверяется, разрешён ли канал уведомления и не заблокирован ли отправитель.
- Исключаются дубликаты, учитывая историю за последние 24 часа и текущие уведомления.
- Возвращается список уведомлений, соответствующих предпочтениям и без дубликатов.