feat(polls): implement group trip polling MVP

Add complete group trip polling feature allowing users to share trips
with friends for voting using Borda count scoring.

New components:
- TripPoll and PollVote domain models with share codes and rankings
- LocalTripPoll and LocalPollVote SwiftData models for persistence
- CKTripPoll and CKPollVote CloudKit record wrappers
- PollService actor for CloudKit CRUD operations and subscriptions
- PollCreation/Detail/Voting views and view models
- Deep link handling for sportstime://poll/{code} URLs
- Debug Pro status override toggle in Settings

Integration:
- HomeView shows polls section in My Trips
- SportsTimeApp registers SwiftData models and handles deep links

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-01-13 21:54:42 -06:00
parent 8e78828bde
commit 13385b6562
16 changed files with 2416 additions and 19 deletions

View File

@@ -18,6 +18,8 @@ enum CKRecordType {
static let leagueStructure = "LeagueStructure"
static let teamAlias = "TeamAlias"
static let stadiumAlias = "StadiumAlias"
static let tripPoll = "TripPoll"
static let pollVote = "PollVote"
}
// MARK: - CKTeam
@@ -472,3 +474,114 @@ struct CKTeamAlias {
)
}
}
// MARK: - CKTripPoll
struct CKTripPoll {
static let pollIdKey = "pollId"
static let titleKey = "title"
static let ownerIdKey = "ownerId"
static let shareCodeKey = "shareCode"
static let tripSnapshotsKey = "tripSnapshots"
static let tripVersionsKey = "tripVersions"
static let createdAtKey = "createdAt"
static let modifiedAtKey = "modifiedAt"
let record: CKRecord
init(record: CKRecord) {
self.record = record
}
init(poll: TripPoll) {
let record = CKRecord(recordType: CKRecordType.tripPoll, recordID: CKRecord.ID(recordName: poll.id.uuidString))
record[CKTripPoll.pollIdKey] = poll.id.uuidString
record[CKTripPoll.titleKey] = poll.title
record[CKTripPoll.ownerIdKey] = poll.ownerId
record[CKTripPoll.shareCodeKey] = poll.shareCode
// Encode trips as JSON data
if let tripsData = try? JSONEncoder().encode(poll.tripSnapshots) {
record[CKTripPoll.tripSnapshotsKey] = tripsData
}
record[CKTripPoll.tripVersionsKey] = poll.tripVersions
record[CKTripPoll.createdAtKey] = poll.createdAt
record[CKTripPoll.modifiedAtKey] = poll.modifiedAt
self.record = record
}
func toPoll() -> TripPoll? {
guard let pollIdString = record[CKTripPoll.pollIdKey] as? String,
let pollId = UUID(uuidString: pollIdString),
let title = record[CKTripPoll.titleKey] as? String,
let ownerId = record[CKTripPoll.ownerIdKey] as? String,
let shareCode = record[CKTripPoll.shareCodeKey] as? String,
let tripsData = record[CKTripPoll.tripSnapshotsKey] as? Data,
let tripSnapshots = try? JSONDecoder().decode([Trip].self, from: tripsData),
let tripVersions = record[CKTripPoll.tripVersionsKey] as? [String],
let createdAt = record[CKTripPoll.createdAtKey] as? Date,
let modifiedAt = record[CKTripPoll.modifiedAtKey] as? Date
else { return nil }
var poll = TripPoll(
id: pollId,
title: title,
ownerId: ownerId,
shareCode: shareCode,
tripSnapshots: tripSnapshots,
createdAt: createdAt,
modifiedAt: modifiedAt
)
// Preserve the actual stored versions (not recomputed)
poll.tripVersions = tripVersions
return poll
}
}
// MARK: - CKPollVote
struct CKPollVote {
static let voteIdKey = "voteId"
static let pollIdKey = "pollId"
static let voterIdKey = "voterId"
static let rankingsKey = "rankings"
static let votedAtKey = "votedAt"
static let modifiedAtKey = "modifiedAt"
let record: CKRecord
init(record: CKRecord) {
self.record = record
}
init(vote: PollVote) {
let record = CKRecord(recordType: CKRecordType.pollVote, recordID: CKRecord.ID(recordName: vote.id.uuidString))
record[CKPollVote.voteIdKey] = vote.id.uuidString
record[CKPollVote.pollIdKey] = vote.pollId.uuidString
record[CKPollVote.voterIdKey] = vote.odg
record[CKPollVote.rankingsKey] = vote.rankings
record[CKPollVote.votedAtKey] = vote.votedAt
record[CKPollVote.modifiedAtKey] = vote.modifiedAt
self.record = record
}
func toVote() -> PollVote? {
guard let voteIdString = record[CKPollVote.voteIdKey] as? String,
let voteId = UUID(uuidString: voteIdString),
let pollIdString = record[CKPollVote.pollIdKey] as? String,
let pollId = UUID(uuidString: pollIdString),
let voterId = record[CKPollVote.voterIdKey] as? String,
let rankings = record[CKPollVote.rankingsKey] as? [Int],
let votedAt = record[CKPollVote.votedAtKey] as? Date,
let modifiedAt = record[CKPollVote.modifiedAtKey] as? Date
else { return nil }
return PollVote(
id: voteId,
pollId: pollId,
odg: voterId,
rankings: rankings,
votedAt: votedAt,
modifiedAt: modifiedAt
)
}
}

View File

@@ -0,0 +1,139 @@
//
// TripPoll.swift
// SportsTime
//
import Foundation
// MARK: - Trip Poll
struct TripPoll: Identifiable, Codable, Hashable {
let id: UUID
var title: String
let ownerId: String
let shareCode: String
var tripSnapshots: [Trip]
var tripVersions: [String]
let createdAt: Date
var modifiedAt: Date
init(
id: UUID = UUID(),
title: String,
ownerId: String,
shareCode: String = TripPoll.generateShareCode(),
tripSnapshots: [Trip],
createdAt: Date = Date(),
modifiedAt: Date = Date()
) {
self.id = id
self.title = title
self.ownerId = ownerId
self.shareCode = shareCode
self.tripSnapshots = tripSnapshots
self.tripVersions = tripSnapshots.map { TripPoll.computeTripHash($0) }
self.createdAt = createdAt
self.modifiedAt = modifiedAt
}
// MARK: - Share Code Generation
private static let shareCodeCharacters = Array("ABCDEFGHJKMNPQRSTUVWXYZ23456789")
static func generateShareCode() -> String {
String((0..<6).map { _ in shareCodeCharacters.randomElement()! })
}
// MARK: - Trip Hash
static func computeTripHash(_ trip: Trip) -> String {
var hasher = Hasher()
hasher.combine(trip.stops.map { $0.city })
hasher.combine(trip.stops.flatMap { $0.games })
hasher.combine(trip.preferences.startDate)
hasher.combine(trip.preferences.endDate)
return String(hasher.finalize())
}
// MARK: - Deep Link URL
var shareURL: URL {
URL(string: "sportstime://poll/\(shareCode)")!
}
}
// MARK: - Poll Vote
struct PollVote: Identifiable, Codable, Hashable {
let id: UUID
let pollId: UUID
let odg: String // voter's userRecordID
var rankings: [Int] // trip indices in preference order
let votedAt: Date
var modifiedAt: Date
init(
id: UUID = UUID(),
pollId: UUID,
odg: String,
rankings: [Int],
votedAt: Date = Date(),
modifiedAt: Date = Date()
) {
self.id = id
self.pollId = pollId
self.odg = odg
self.rankings = rankings
self.votedAt = votedAt
self.modifiedAt = modifiedAt
}
/// Calculate Borda count scores from rankings
/// Returns array where index = trip index, value = score
static func calculateScores(rankings: [Int], tripCount: Int) -> [Int] {
var scores = Array(repeating: 0, count: tripCount)
for (rank, tripIndex) in rankings.enumerated() {
guard tripIndex < tripCount else { continue }
let points = tripCount - rank
scores[tripIndex] = points
}
return scores
}
}
// MARK: - Poll Results
struct PollResults {
let poll: TripPoll
let votes: [PollVote]
var voterCount: Int { votes.count }
var tripScores: [(tripIndex: Int, score: Int)] {
guard !votes.isEmpty else {
return poll.tripSnapshots.indices.map { ($0, 0) }
}
var totalScores = Array(repeating: 0, count: poll.tripSnapshots.count)
for vote in votes {
let scores = PollVote.calculateScores(rankings: vote.rankings, tripCount: poll.tripSnapshots.count)
for (index, score) in scores.enumerated() {
totalScores[index] += score
}
}
return totalScores.enumerated()
.map { ($0.offset, $0.element) }
.sorted { $0.score > $1.score }
}
var maxScore: Int {
tripScores.first?.score ?? 0
}
func scorePercentage(for tripIndex: Int) -> Double {
guard maxScore > 0 else { return 0 }
let score = tripScores.first { $0.tripIndex == tripIndex }?.score ?? 0
return Double(score) / Double(maxScore)
}
}

View File

@@ -0,0 +1,134 @@
//
// LocalPoll.swift
// SportsTime
//
// SwiftData models for local poll persistence
//
import Foundation
import SwiftData
// MARK: - Local Trip Poll
@Model
final class LocalTripPoll {
@Attribute(.unique) var id: UUID
var title: String
var ownerId: String
var shareCode: String
var tripSnapshotsData: Data // Encoded [Trip]
var tripVersions: [String]
var createdAt: Date
var modifiedAt: Date
var lastSyncedAt: Date?
@Relationship(deleteRule: .cascade)
var votes: [LocalPollVote]?
init(
id: UUID = UUID(),
title: String,
ownerId: String,
shareCode: String,
tripSnapshotsData: Data,
tripVersions: [String],
createdAt: Date = Date(),
modifiedAt: Date = Date(),
lastSyncedAt: Date? = nil
) {
self.id = id
self.title = title
self.ownerId = ownerId
self.shareCode = shareCode
self.tripSnapshotsData = tripSnapshotsData
self.tripVersions = tripVersions
self.createdAt = createdAt
self.modifiedAt = modifiedAt
self.lastSyncedAt = lastSyncedAt
}
var tripSnapshots: [Trip] {
(try? JSONDecoder().decode([Trip].self, from: tripSnapshotsData)) ?? []
}
func toPoll() -> TripPoll {
var poll = TripPoll(
id: id,
title: title,
ownerId: ownerId,
shareCode: shareCode,
tripSnapshots: tripSnapshots,
createdAt: createdAt,
modifiedAt: modifiedAt
)
poll.tripVersions = tripVersions
return poll
}
static func from(_ poll: TripPoll) -> LocalTripPoll? {
guard let tripsData = try? JSONEncoder().encode(poll.tripSnapshots) else { return nil }
return LocalTripPoll(
id: poll.id,
title: poll.title,
ownerId: poll.ownerId,
shareCode: poll.shareCode,
tripSnapshotsData: tripsData,
tripVersions: poll.tripVersions,
createdAt: poll.createdAt,
modifiedAt: poll.modifiedAt
)
}
}
// MARK: - Local Poll Vote
@Model
final class LocalPollVote {
@Attribute(.unique) var id: UUID
var pollId: UUID
var voterId: String
var rankings: [Int]
var votedAt: Date
var modifiedAt: Date
var lastSyncedAt: Date?
init(
id: UUID = UUID(),
pollId: UUID,
voterId: String,
rankings: [Int],
votedAt: Date = Date(),
modifiedAt: Date = Date(),
lastSyncedAt: Date? = nil
) {
self.id = id
self.pollId = pollId
self.voterId = voterId
self.rankings = rankings
self.votedAt = votedAt
self.modifiedAt = modifiedAt
self.lastSyncedAt = lastSyncedAt
}
func toVote() -> PollVote {
PollVote(
id: id,
pollId: pollId,
odg: voterId,
rankings: rankings,
votedAt: votedAt,
modifiedAt: modifiedAt
)
}
static func from(_ vote: PollVote) -> LocalPollVote {
LocalPollVote(
id: vote.id,
pollId: vote.pollId,
voterId: vote.odg,
rankings: vote.rankings,
votedAt: vote.votedAt,
modifiedAt: vote.modifiedAt
)
}
}

View File

@@ -0,0 +1,362 @@
//
// PollService.swift
// SportsTime
//
// CloudKit service for trip polls and voting
//
import Foundation
import CloudKit
import SwiftData
// MARK: - Poll Errors
enum PollError: Error, LocalizedError {
case notSignedIn
case pollNotFound
case alreadyVoted
case notPollOwner
case networkUnavailable
case encodingError
case unknown(Error)
var errorDescription: String? {
switch self {
case .notSignedIn:
return "Please sign in to iCloud to use polls."
case .pollNotFound:
return "Poll not found. It may have been deleted."
case .alreadyVoted:
return "You have already voted on this poll."
case .notPollOwner:
return "Only the poll owner can perform this action."
case .networkUnavailable:
return "Unable to connect. Please check your internet connection."
case .encodingError:
return "Failed to save poll data."
case .unknown(let error):
return "An error occurred: \(error.localizedDescription)"
}
}
}
// MARK: - Poll Service
actor PollService {
static let shared = PollService()
private let container: CKContainer
private let publicDatabase: CKDatabase
private var currentUserRecordID: String?
private var pollSubscriptionID: CKSubscription.ID?
private init() {
self.container = CKContainer(identifier: "iCloud.com.sportstime.app")
self.publicDatabase = container.publicCloudDatabase
}
// MARK: - User Identity
func getCurrentUserRecordID() async throws -> String {
if let cached = currentUserRecordID {
return cached
}
let recordID = try await container.userRecordID()
currentUserRecordID = recordID.recordName
return recordID.recordName
}
func isSignedIn() async -> Bool {
do {
_ = try await getCurrentUserRecordID()
return true
} catch {
return false
}
}
// MARK: - Poll CRUD
func createPoll(_ poll: TripPoll) async throws -> TripPoll {
let ckPoll = CKTripPoll(poll: poll)
do {
try await publicDatabase.save(ckPoll.record)
return poll
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
func fetchPoll(byShareCode shareCode: String) async throws -> TripPoll {
let predicate = NSPredicate(format: "%K == %@", CKTripPoll.shareCodeKey, shareCode.uppercased())
let query = CKQuery(recordType: CKRecordType.tripPoll, predicate: predicate)
do {
let (results, _) = try await publicDatabase.records(matching: query)
guard let result = results.first,
case .success(let record) = result.1,
let poll = CKTripPoll(record: record).toPoll()
else {
throw PollError.pollNotFound
}
return poll
} catch let error as CKError {
throw mapCloudKitError(error)
} catch let error as PollError {
throw error
} catch {
throw PollError.unknown(error)
}
}
func fetchPoll(byId pollId: UUID) async throws -> TripPoll {
let recordID = CKRecord.ID(recordName: pollId.uuidString)
do {
let record = try await publicDatabase.record(for: recordID)
guard let poll = CKTripPoll(record: record).toPoll() else {
throw PollError.pollNotFound
}
return poll
} catch let error as CKError {
if error.code == .unknownItem {
throw PollError.pollNotFound
}
throw mapCloudKitError(error)
} catch let error as PollError {
throw error
} catch {
throw PollError.unknown(error)
}
}
func fetchMyPolls() async throws -> [TripPoll] {
let userId = try await getCurrentUserRecordID()
let predicate = NSPredicate(format: "%K == %@", CKTripPoll.ownerIdKey, userId)
let query = CKQuery(recordType: CKRecordType.tripPoll, predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: CKTripPoll.createdAtKey, ascending: false)]
do {
let (results, _) = try await publicDatabase.records(matching: query)
return results.compactMap { result in
guard case .success(let record) = result.1 else { return nil }
return CKTripPoll(record: record).toPoll()
}
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
func updatePoll(_ poll: TripPoll, resetVotes: Bool = false) async throws -> TripPoll {
let userId = try await getCurrentUserRecordID()
guard poll.ownerId == userId else {
throw PollError.notPollOwner
}
var updatedPoll = poll
updatedPoll.modifiedAt = Date()
let ckPoll = CKTripPoll(poll: updatedPoll)
do {
try await publicDatabase.save(ckPoll.record)
if resetVotes {
try await deleteVotes(forPollId: poll.id)
}
return updatedPoll
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
func deletePoll(_ pollId: UUID) async throws {
let recordID = CKRecord.ID(recordName: pollId.uuidString)
do {
// Delete all votes first
try await deleteVotes(forPollId: pollId)
// Then delete the poll
try await publicDatabase.deleteRecord(withID: recordID)
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
// MARK: - Voting
func submitVote(_ vote: PollVote) async throws -> PollVote {
// Check if user already voted
let existingVote = try await fetchMyVote(forPollId: vote.pollId)
if existingVote != nil {
throw PollError.alreadyVoted
}
let ckVote = CKPollVote(vote: vote)
do {
try await publicDatabase.save(ckVote.record)
return vote
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
func updateVote(_ vote: PollVote) async throws -> PollVote {
let userId = try await getCurrentUserRecordID()
guard vote.odg == userId else {
throw PollError.notPollOwner // Using this error for now - voter can only update own vote
}
var updatedVote = vote
updatedVote.modifiedAt = Date()
let ckVote = CKPollVote(vote: updatedVote)
do {
try await publicDatabase.save(ckVote.record)
return updatedVote
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
func fetchVotes(forPollId pollId: UUID) async throws -> [PollVote] {
let predicate = NSPredicate(format: "%K == %@", CKPollVote.pollIdKey, pollId.uuidString)
let query = CKQuery(recordType: CKRecordType.pollVote, predicate: predicate)
do {
let (results, _) = try await publicDatabase.records(matching: query)
return results.compactMap { result in
guard case .success(let record) = result.1 else { return nil }
return CKPollVote(record: record).toVote()
}
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
func fetchMyVote(forPollId pollId: UUID) async throws -> PollVote? {
let userId = try await getCurrentUserRecordID()
let predicate = NSPredicate(
format: "%K == %@ AND %K == %@",
CKPollVote.pollIdKey, pollId.uuidString,
CKPollVote.voterIdKey, userId
)
let query = CKQuery(recordType: CKRecordType.pollVote, predicate: predicate)
do {
let (results, _) = try await publicDatabase.records(matching: query)
guard let result = results.first,
case .success(let record) = result.1
else {
return nil
}
return CKPollVote(record: record).toVote()
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
}
private func deleteVotes(forPollId pollId: UUID) async throws {
let votes = try await fetchVotes(forPollId: pollId)
let recordIDs = votes.map { CKRecord.ID(recordName: $0.id.uuidString) }
if !recordIDs.isEmpty {
let result = try await publicDatabase.modifyRecords(saving: [], deleting: recordIDs)
// Ignore individual delete errors - votes may already be deleted
_ = result
}
}
// MARK: - Subscriptions
func subscribeToVoteUpdates(forPollId pollId: UUID) async throws {
let predicate = NSPredicate(format: "%K == %@", CKPollVote.pollIdKey, pollId.uuidString)
let subscription = CKQuerySubscription(
recordType: CKRecordType.pollVote,
predicate: predicate,
subscriptionID: "poll-votes-\(pollId.uuidString)",
options: [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]
)
let notification = CKSubscription.NotificationInfo()
notification.shouldSendContentAvailable = true
subscription.notificationInfo = notification
do {
try await publicDatabase.save(subscription)
pollSubscriptionID = subscription.subscriptionID
} catch let error as CKError {
// Subscription already exists is OK
if error.code != .serverRejectedRequest {
throw mapCloudKitError(error)
}
} catch {
throw PollError.unknown(error)
}
}
func unsubscribeFromVoteUpdates() async throws {
guard let subscriptionID = pollSubscriptionID else { return }
do {
try await publicDatabase.deleteSubscription(withID: subscriptionID)
pollSubscriptionID = nil
} catch {
// Ignore errors - subscription may not exist
}
}
// MARK: - Results
func fetchPollResults(forPollId pollId: UUID) async throws -> PollResults {
async let pollTask = fetchPoll(byId: pollId)
async let votesTask = fetchVotes(forPollId: pollId)
let (poll, votes) = try await (pollTask, votesTask)
return PollResults(poll: poll, votes: votes)
}
// MARK: - Error Mapping
private func mapCloudKitError(_ error: CKError) -> PollError {
switch error.code {
case .notAuthenticated:
return .notSignedIn
case .networkUnavailable, .networkFailure:
return .networkUnavailable
case .unknownItem:
return .pollNotFound
default:
return .unknown(error)
}
}
}

View File

@@ -31,10 +31,31 @@ final class StoreManager {
private(set) var isLoading = false
private(set) var error: StoreError?
// MARK: - Debug Override (DEBUG builds only)
#if DEBUG
private static let debugProOverrideKey = "debugProOverride"
/// When true, isPro returns true regardless of actual subscription status.
/// Defaults to true in debug builds. Only compiled in DEBUG configuration.
var debugProOverride: Bool {
get {
// Default to true by checking if key exists; object(forKey:) returns nil if not set
UserDefaults.standard.object(forKey: Self.debugProOverrideKey) as? Bool ?? true
}
set {
UserDefaults.standard.set(newValue, forKey: Self.debugProOverrideKey)
}
}
#endif
// MARK: - Computed Properties
var isPro: Bool {
!purchasedProductIDs.intersection(Self.proProductIDs).isEmpty
#if DEBUG
if debugProOverride { return true }
#endif
return !purchasedProductIDs.intersection(Self.proProductIDs).isEmpty
}
var monthlyProduct: Product? {