Skip to content
Repos

DevPlaceApp

C++ 2.2 KB61 lines Opens in site

Directory Raw Download

#pragma once
// Spec: INV-social 15.5 (NotificationsView.ViewModel): load, refresh, load more with merge and dedupe, open and
// route, mark read, mark all read.
#include <functional>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <vector>

#include "api/DevPlaceApi.hpp"
#include "core/AlertMessage.hpp"
#include "model/Notifications.hpp"
#include "screens/notifications/NotificationRoute.hpp"

namespace dp {

class NotificationsModel {
 public:
  using AlertSink = std::function<void(const AlertMessage&)>;

  explicit NotificationsModel(DevPlaceApi& api, AlertSink alertSink = nullptr);
  ~NotificationsModel() { *alive_ = false; }
  NotificationsModel(const NotificationsModel&) = delete;
  NotificationsModel& operator=(const NotificationsModel&) = delete;

  const std::optional<Notifications>& notifications() const { return notifications_; }
  const std::vector<NotificationGroup>& groups() const;
  bool isLoadingMore() const { return isLoadingMore_; }
  bool isRefreshing() const { return refreshing_ > 0; }
  bool isBusy() const { return pending_ > 0; }
  // A footer spinner is shown while an older page exists and the entry cap is not reached.
  bool hasMore() const;
  std::size_t entryCount() const;

  void load(std::function<void()> done = nullptr);
  void refresh(std::function<void()> done = nullptr);
  void loadMore();
  // GET notifications/open/<uid>, then reload and recount; `done` gets the route (nullopt on error or no route).
  void open(const Notification& notification, std::function<void(std::optional<NotificationRoute>)> done);
  void markRead(const std::string& uid);
  void markAllRead();

  // Pure helpers (unit tested).
  static Notifications merged(const Notifications& existing, const Notifications& older, std::vector<std::string>* duplicates = nullptr);
  static Notifications applyingRead(const Notifications& n, const std::set<std::string>& uids);

 private:
  void refreshUnreadCount(std::function<void()> done);

  DevPlaceApi& api_;
  AlertSink alertSink_;
  std::optional<Notifications> notifications_;
  bool isLoadingMore_ = false;
  bool loadMoreFailed_ = false;
  int pending_ = 0;
  int refreshing_ = 0;
  std::shared_ptr<bool> alive_ = std::make_shared<bool>(true);
};

}  // namespace dp
51.9ms