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

@@ -0,0 +1,133 @@
//
// PollCreationView.swift
// SportsTime
//
// View for creating a new trip poll
//
import SwiftUI
struct PollCreationView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@State private var viewModel = PollCreationViewModel()
let trips: [Trip]
var onPollCreated: ((TripPoll) -> Void)?
var body: some View {
NavigationStack {
Form {
Section {
TextField("Poll Title", text: $viewModel.title)
.textInputAutocapitalization(.words)
} header: {
Text("Title")
} footer: {
Text("Give your poll a name, like \"Summer Road Trip Options\"")
}
Section {
ForEach(trips) { trip in
TripSelectionRow(
trip: trip,
isSelected: viewModel.selectedTripIds.contains(trip.id)
) {
viewModel.toggleTrip(trip.id)
}
}
} header: {
Text("Select Trips (\(viewModel.selectedTripIds.count) selected)")
} footer: {
if let message = viewModel.validationMessage {
Text(message)
.foregroundStyle(.secondary)
}
}
}
.navigationTitle("Create Poll")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
dismiss()
}
}
ToolbarItem(placement: .confirmationAction) {
Button("Create") {
Task {
await viewModel.createPoll(trips: trips)
}
}
.disabled(!viewModel.canCreate || viewModel.isLoading)
}
}
.overlay {
if viewModel.isLoading {
ProgressView()
.scaleEffect(1.2)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.ultraThinMaterial)
}
}
.alert("Error", isPresented: .constant(viewModel.error != nil)) {
Button("OK") {
viewModel.error = nil
}
} message: {
if let error = viewModel.error {
Text(error.localizedDescription)
}
}
.onChange(of: viewModel.createdPoll) { _, newPoll in
if let poll = newPoll {
onPollCreated?(poll)
dismiss()
}
}
}
}
}
// MARK: - Trip Selection Row
private struct TripSelectionRow: View {
let trip: Trip
let isSelected: Bool
let onTap: () -> Void
var body: some View {
Button(action: onTap) {
HStack {
VStack(alignment: .leading, spacing: 4) {
Text(trip.name)
.font(.headline)
.foregroundStyle(.primary)
Text(tripSummary)
.font(.subheadline)
.foregroundStyle(.secondary)
}
Spacer()
Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
.font(.title2)
.foregroundStyle(isSelected ? Theme.warmOrange : .secondary)
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
private var tripSummary: String {
let stopCount = trip.stops.count
let gameCount = trip.stops.flatMap { $0.games }.count
return "\(stopCount) stops, \(gameCount) games"
}
}
#Preview {
PollCreationView(trips: [])
}

View File

@@ -0,0 +1,318 @@
//
// PollDetailView.swift
// SportsTime
//
// View for displaying poll details and results
//
import SwiftUI
struct PollDetailView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@State private var viewModel = PollDetailViewModel()
@State private var showShareSheet = false
@State private var showDeleteConfirmation = false
@State private var showVotingSheet = false
@State private var isOwner = false
let pollId: UUID?
let shareCode: String?
init(pollId: UUID) {
self.pollId = pollId
self.shareCode = nil
}
init(shareCode: String) {
self.pollId = nil
self.shareCode = shareCode
}
var body: some View {
Group {
if viewModel.isLoading && viewModel.poll == nil {
ProgressView("Loading poll...")
} else if let poll = viewModel.poll {
pollContent(poll)
} else if let error = viewModel.error {
ContentUnavailableView(
"Poll Not Found",
systemImage: "exclamationmark.triangle",
description: Text(error.localizedDescription)
)
}
}
.navigationTitle(viewModel.poll?.title ?? "Poll")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
if viewModel.poll != nil {
ToolbarItem(placement: .primaryAction) {
Menu {
Button {
showShareSheet = true
} label: {
Label("Share Poll", systemImage: "square.and.arrow.up")
}
if isOwner {
Divider()
Button(role: .destructive) {
showDeleteConfirmation = true
} label: {
Label("Delete Poll", systemImage: "trash")
}
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
}
.refreshable {
await viewModel.refresh()
}
.task {
await loadPoll()
isOwner = await viewModel.isOwner
}
.task(id: viewModel.poll?.id) {
if viewModel.poll != nil {
isOwner = await viewModel.isOwner
}
}
.onDisappear {
Task {
await viewModel.cleanup()
}
}
.sheet(isPresented: $showShareSheet) {
if let url = viewModel.shareURL {
ShareSheet(items: [url])
}
}
.sheet(isPresented: $showVotingSheet) {
if let poll = viewModel.poll {
PollVotingView(poll: poll, existingVote: viewModel.myVote) {
Task {
await viewModel.refresh()
}
}
}
}
.confirmationDialog("Delete Poll", isPresented: $showDeleteConfirmation, titleVisibility: .visible) {
Button("Delete", role: .destructive) {
Task {
if await viewModel.deletePoll() {
dismiss()
}
}
}
Button("Cancel", role: .cancel) {}
} message: {
Text("This will permanently delete the poll and all votes. This action cannot be undone.")
}
}
@ViewBuilder
private func pollContent(_ poll: TripPoll) -> some View {
ScrollView {
VStack(spacing: 20) {
// Share Code Card
shareCodeCard(poll)
// Voting Status
votingStatusCard
// Results
if let results = viewModel.results {
resultsSection(results)
}
// Trip Previews
tripPreviewsSection(poll)
}
.padding()
}
}
@ViewBuilder
private func shareCodeCard(_ poll: TripPoll) -> some View {
VStack(spacing: 8) {
Text("Share Code")
.font(.caption)
.foregroundStyle(.secondary)
Text(poll.shareCode)
.font(.system(size: 32, weight: .bold, design: .monospaced))
.foregroundStyle(Theme.warmOrange)
Text("sportstime://poll/\(poll.shareCode)")
.font(.caption2)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding()
.background(Theme.cardBackground(colorScheme))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
@ViewBuilder
private var votingStatusCard: some View {
HStack {
VStack(alignment: .leading, spacing: 4) {
Text(viewModel.hasVoted ? "You voted" : "You haven't voted yet")
.font(.headline)
Text("\(viewModel.votes.count) total votes")
.font(.subheadline)
.foregroundStyle(.secondary)
}
Spacer()
Button(viewModel.hasVoted ? "Change Vote" : "Vote Now") {
showVotingSheet = true
}
.buttonStyle(.borderedProminent)
.tint(Theme.warmOrange)
}
.padding()
.background(Theme.cardBackground(colorScheme))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
@ViewBuilder
private func resultsSection(_ results: PollResults) -> some View {
VStack(alignment: .leading, spacing: 12) {
Text("Results")
.font(.headline)
ForEach(results.tripScores, id: \.tripIndex) { item in
let trip = results.poll.tripSnapshots[item.tripIndex]
ResultRow(
rank: results.tripScores.firstIndex { $0.tripIndex == item.tripIndex }! + 1,
tripName: trip.name,
score: item.score,
percentage: results.scorePercentage(for: item.tripIndex)
)
}
}
.padding()
.background(Theme.cardBackground(colorScheme))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
@ViewBuilder
private func tripPreviewsSection(_ poll: TripPoll) -> some View {
VStack(alignment: .leading, spacing: 12) {
Text("Trip Options")
.font(.headline)
ForEach(Array(poll.tripSnapshots.enumerated()), id: \.element.id) { index, trip in
TripPreviewCard(trip: trip, index: index + 1)
}
}
}
private func loadPoll() async {
if let pollId {
await viewModel.loadPoll(byId: pollId)
} else if let shareCode {
await viewModel.loadPoll(byShareCode: shareCode)
}
}
}
// MARK: - Result Row
private struct ResultRow: View {
let rank: Int
let tripName: String
let score: Int
let percentage: Double
var body: some View {
HStack(spacing: 12) {
Text("#\(rank)")
.font(.headline)
.foregroundStyle(rank == 1 ? Theme.warmOrange : .secondary)
.frame(width: 30)
VStack(alignment: .leading, spacing: 4) {
Text(tripName)
.font(.subheadline)
GeometryReader { geometry in
ZStack(alignment: .leading) {
Rectangle()
.fill(Color.secondary.opacity(0.2))
.frame(height: 8)
.clipShape(RoundedRectangle(cornerRadius: 4))
Rectangle()
.fill(rank == 1 ? Theme.warmOrange : Color.secondary)
.frame(width: geometry.size.width * percentage, height: 8)
.clipShape(RoundedRectangle(cornerRadius: 4))
}
}
.frame(height: 8)
}
Text("\(score)")
.font(.caption)
.foregroundStyle(.secondary)
.frame(width: 40, alignment: .trailing)
}
}
}
// MARK: - Trip Preview Card
private struct TripPreviewCard: View {
@Environment(\.colorScheme) private var colorScheme
let trip: Trip
let index: Int
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("Option \(index)")
.font(.caption)
.fontWeight(.semibold)
.foregroundStyle(.white)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Theme.warmOrange)
.clipShape(Capsule())
Text(trip.name)
.font(.headline)
}
HStack {
Label("\(trip.stops.count) stops", systemImage: "mappin.and.ellipse")
Spacer()
Label("\(trip.stops.flatMap { $0.games }.count) games", systemImage: "sportscourt")
}
.font(.caption)
.foregroundStyle(.secondary)
// Show cities
Text(trip.stops.map { $0.city }.joined(separator: ""))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
.padding()
.background(Theme.cardBackground(colorScheme))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
#Preview {
NavigationStack {
PollDetailView(shareCode: "ABC123")
}
}

View File

@@ -0,0 +1,178 @@
//
// PollVotingView.swift
// SportsTime
//
// View for ranking trips in a poll
//
import SwiftUI
struct PollVotingView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@State private var viewModel = PollVotingViewModel()
let poll: TripPoll
let existingVote: PollVote?
var onVoteSubmitted: (() -> Void)?
var body: some View {
NavigationStack {
VStack(spacing: 0) {
// Instructions
instructionsHeader
// Reorderable list
List {
ForEach(Array(viewModel.rankings.enumerated()), id: \.element) { index, tripIndex in
RankingRow(
rank: index + 1,
trip: poll.tripSnapshots[tripIndex]
)
}
.onMove { source, destination in
viewModel.moveTrip(from: source, to: destination)
}
}
.listStyle(.plain)
.environment(\.editMode, .constant(.active))
// Submit button
submitButton
}
.navigationTitle("Rank Trips")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
dismiss()
}
}
}
.onAppear {
viewModel.initializeRankings(
tripCount: poll.tripSnapshots.count,
existingVote: existingVote
)
}
.alert("Error", isPresented: .constant(viewModel.error != nil)) {
Button("OK") {
viewModel.error = nil
}
} message: {
if let error = viewModel.error {
Text(error.localizedDescription)
}
}
.onChange(of: viewModel.didSubmit) { _, didSubmit in
if didSubmit {
onVoteSubmitted?()
dismiss()
}
}
}
}
@ViewBuilder
private var instructionsHeader: some View {
VStack(spacing: 8) {
Image(systemName: "arrow.up.arrow.down")
.font(.title2)
.foregroundStyle(Theme.warmOrange)
Text("Drag to rank your preferences")
.font(.headline)
Text("Your top choice should be at the top")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.padding()
.frame(maxWidth: .infinity)
.background(Theme.cardBackground(colorScheme))
}
@ViewBuilder
private var submitButton: some View {
Button {
Task {
if let existingVote {
await viewModel.updateVote(existingVote: existingVote)
} else {
await viewModel.submitVote(pollId: poll.id)
}
}
} label: {
HStack {
if viewModel.isLoading {
ProgressView()
.tint(.white)
} else {
Text(existingVote != nil ? "Update Vote" : "Submit Vote")
}
}
.frame(maxWidth: .infinity)
.padding()
.background(Theme.warmOrange)
.foregroundStyle(.white)
.font(.headline)
}
.disabled(viewModel.isLoading || !viewModel.canSubmit)
}
}
// MARK: - Ranking Row
private struct RankingRow: View {
let rank: Int
let trip: Trip
var body: some View {
HStack(spacing: 12) {
// Rank badge
Text("\(rank)")
.font(.headline)
.foregroundStyle(.white)
.frame(width: 28, height: 28)
.background(rankColor)
.clipShape(Circle())
VStack(alignment: .leading, spacing: 2) {
Text(trip.name)
.font(.headline)
Text(tripSummary)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
}
.padding(.vertical, 4)
}
private var rankColor: Color {
switch rank {
case 1: return Theme.warmOrange
case 2: return .blue
case 3: return .green
default: return .secondary
}
}
private var tripSummary: String {
let cities = trip.stops.map { $0.city }.joined(separator: "")
return cities
}
}
#Preview {
PollVotingView(
poll: TripPoll(
title: "Test Poll",
ownerId: "test",
tripSnapshots: []
),
existingVote: nil
)
}

View File

@@ -0,0 +1,152 @@
//
// PollsListView.swift
// SportsTime
//
// View for listing user's polls
//
import SwiftUI
struct PollsListView: View {
@Environment(\.colorScheme) private var colorScheme
@State private var polls: [TripPoll] = []
@State private var isLoading = false
@State private var error: PollError?
@State private var showJoinPoll = false
@State private var joinCode = ""
var body: some View {
Group {
if isLoading && polls.isEmpty {
ProgressView("Loading polls...")
} else if polls.isEmpty {
emptyState
} else {
pollsList
}
}
.navigationTitle("Group Polls")
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button {
showJoinPoll = true
} label: {
Image(systemName: "link.badge.plus")
}
}
}
.refreshable {
await loadPolls()
}
.task {
await loadPolls()
}
.alert("Join Poll", isPresented: $showJoinPoll) {
TextField("Enter code", text: $joinCode)
.textInputAutocapitalization(.characters)
Button("Join") {
// Navigation will be handled by deep link
if !joinCode.isEmpty {
// TODO: Navigate to poll detail
}
}
Button("Cancel", role: .cancel) {
joinCode = ""
}
} message: {
Text("Enter the 6-character poll code")
}
.alert("Error", isPresented: .constant(error != nil)) {
Button("OK") {
error = nil
}
} message: {
if let error {
Text(error.localizedDescription)
}
}
}
@ViewBuilder
private var emptyState: some View {
ContentUnavailableView {
Label("No Polls", systemImage: "chart.bar.doc.horizontal")
} description: {
Text("Create a poll from your saved trips to let friends vote on which trip to take.")
}
}
@ViewBuilder
private var pollsList: some View {
List {
ForEach(polls) { poll in
NavigationLink(value: poll) {
PollRowView(poll: poll)
}
}
}
.listStyle(.plain)
.navigationDestination(for: TripPoll.self) { poll in
PollDetailView(pollId: poll.id)
}
}
private func loadPolls() async {
isLoading = true
error = nil
do {
polls = try await PollService.shared.fetchMyPolls()
} catch let pollError as PollError {
error = pollError
} catch {
self.error = .unknown(error)
}
isLoading = false
}
}
// MARK: - Poll Row View
private struct PollRowView: View {
@Environment(\.colorScheme) private var colorScheme
let poll: TripPoll
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(poll.title)
.font(.headline)
Spacer()
Text(poll.shareCode)
.font(.caption)
.fontWeight(.semibold)
.foregroundStyle(Theme.warmOrange)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Theme.warmOrange.opacity(0.15))
.clipShape(Capsule())
}
HStack {
Label("\(poll.tripSnapshots.count) trips", systemImage: "map")
Spacer()
Text(poll.createdAt, style: .date)
}
.font(.caption)
.foregroundStyle(.secondary)
}
.padding(.vertical, 4)
}
}
#Preview {
NavigationStack {
PollsListView()
}
}