#pragma once // Spec: INV-posts 9 (PollView+ViewModel). Optimistic single choice with rollback and an alert on failure. #include #include #include #include #include #include "model/Poll.hpp" namespace dp { class PollViewModel { public: explicit PollViewModel(const Poll& poll); // Cached per poll id. A poll that differs from the one passed last time overwrites options, total and choice. static std::shared_ptr shared(const Poll& poll); static void clearCache(); const std::string& question() const { return question_; } const std::vector& options() const { return options_; } std::int64_t total() const { return total_; } const std::optional& myChoice() const { return myChoice_; } bool isLoading() const { return loading_; } bool userCanVote() const; // "1 vote" / "N votes" (singular only when total == 1). std::string votesLabel() const; void select(const std::string& optionId); struct Recomputed { std::vector options; std::int64_t total = 0; }; // PVM.swift:66-92. pct = round(count / total * 100) half away from zero, 0 when total <= 0. static Recomputed recompute(const std::vector& options, std::int64_t total, const std::optional& previousChoice, const std::optional& newChoice); private: void syncProps(const Poll& poll); std::string pollId_; std::string question_; std::vector options_; std::int64_t total_; std::optional myChoice_; Poll prop_; bool loading_ = false; std::weak_ptr self_; }; } // namespace dp