-
Notifications
You must be signed in to change notification settings - Fork 1
Add annual location time forecasts #187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kyleve
wants to merge
22
commits into
main
Choose a base branch
from
codex/location-time-forecasts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
609559c
Add annual location time forecasts
kyleve 41c5e4c
Make planned stay expiry conditional
kyleve a70174b
Add forecast panel preview
kyleve f0bad2b
Add planned stay editor preview
kyleve d841da5
Make location forecasts conversational
kyleve e5b7183
Show elapsed forecast time once
kyleve 42a03f4
Make location forecasts optional and collapsible
kyleve 9dd1e8d
Merge main into location time forecasts
kyleve 53a1371
Refine location forecast card chrome
kyleve 74a5951
Soften location forecast disclosure
kyleve fd8f064
Merge remote-tracking branch 'origin/main' into codex/location-time-f…
kyleve 5952bf3
Distinguish planned days in the calendar
kyleve 96f2f14
Align planned stay hatches across calendar cells
kyleve 4f322b2
Restore chronological calendar order
kyleve 16f233b
Return concurrent planned stay from expiry
kyleve 26a6e20
Keep planned stay revisions monotonic
kyleve 30a67f1
Show cross-year planned stays in calendar
kyleve 25ab871
Keep planned stay previews Gregorian
kyleve 358de6a
Refresh Gregorian planned stay snapshots
kyleve 42409e5
Place estimate after current calendar month
kyleve 14bdd50
Add planned stay editor snapshots
kyleve bbd986f
Give snapshots solid adaptive backgrounds
kyleve File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
Where/WhereCore/Sources/Forecasting/LocationForecast.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import Foundation | ||
| import RegionKit | ||
|
|
||
| /// A region's independently calculated current-year residency estimate. | ||
| /// | ||
| /// This result deliberately contains only the estimate and its inputs. A future | ||
| /// residency goal (for example, “55% of the year”) can compare against it | ||
| /// without becoming another forecasting policy or changing planned-stay math. | ||
| public struct LocationForecast: Hashable, Sendable { | ||
| public let region: Region | ||
| public let year: Int | ||
| public let yearToDateDays: Int | ||
| public let elapsedDays: Int | ||
| public let plannedDays: Int | ||
| public let projectedRemainingDays: Double | ||
| public let estimatedTotalDays: Int | ||
|
|
||
| public var estimatedFractionOfYear: Double { | ||
| let daysInYear = CalendarDay.yearRange(year).lowerBound | ||
| .days(through: CalendarDay.lastDay(ofYear: year)).count | ||
| guard daysInYear > 0 else { return 0 } | ||
| return Double(estimatedTotalDays) / Double(daysInYear) | ||
| } | ||
|
|
||
| /// Estimate a current year's total once three complete calendar months have | ||
| /// elapsed. Returns `nil` before April 1 and for any non-current report. | ||
| public static func estimate( | ||
| region: Region, | ||
| report: YearReport, | ||
| asOf date: Date, | ||
| calendar: Calendar, | ||
| plannedStay: PlannedStay?, | ||
| ) -> LocationForecast? { | ||
| let today = CalendarDay(from: date, in: calendar) | ||
| guard report.year == today.year else { return nil } | ||
| guard today >= CalendarDay(year: report.year, month: 4, day: 1) else { return nil } | ||
|
|
||
| let firstDay = CalendarDay(year: report.year, month: 1, day: 1) | ||
| let lastDay = CalendarDay.lastDay(ofYear: report.year) | ||
| let elapsedDays = firstDay.days(through: today).count | ||
| let yearLength = firstDay.days(through: lastDay).count | ||
| guard elapsedDays > 0, yearLength > 0 else { return nil } | ||
|
|
||
| let yearToDateDays = report.totals[region, default: 0] | ||
| let baselineRate = Double(yearToDateDays) / Double(elapsedDays) | ||
| let tomorrow = today.adding(days: 1) | ||
|
|
||
| let matchingStay = plannedStay.flatMap { stay in | ||
| stay.region == region && stay.through >= today ? stay : nil | ||
| } | ||
| let plannedEnd = matchingStay.map { min($0.through, lastDay) } | ||
| let plannedDays = plannedEnd.map { tomorrow.days(through: $0).count } ?? 0 | ||
| let projectionStart = plannedEnd?.adding(days: 1) ?? tomorrow | ||
| let remainingDays = projectionStart.days(through: lastDay).count | ||
| let projectedRemainingDays = baselineRate * Double(remainingDays) | ||
| let estimated = Double(yearToDateDays + plannedDays) + projectedRemainingDays | ||
|
|
||
| return LocationForecast( | ||
| region: region, | ||
| year: report.year, | ||
| yearToDateDays: yearToDateDays, | ||
| elapsedDays: elapsedDays, | ||
| plannedDays: plannedDays, | ||
| projectedRemainingDays: projectedRemainingDays, | ||
| estimatedTotalDays: min(yearLength, max(0, Int(estimated.rounded()))), | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import Foundation | ||
| import RegionKit | ||
|
|
||
| /// User intent that the current stay in `region` continues through an inclusive | ||
| /// calendar day. The day is timezone-independent so travel cannot move the | ||
| /// asserted departure onto a neighboring date. | ||
| public struct PlannedStay: Hashable, Sendable, Codable { | ||
| public let region: Region | ||
| public let through: CalendarDay | ||
|
|
||
| public init(region: Region, through: CalendarDay) { | ||
| self.region = region | ||
| self.through = through | ||
| } | ||
| } |
77 changes: 77 additions & 0 deletions
77
Where/WhereCore/Sources/Forecasting/PlannedStayCoordinator.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import Foundation | ||
| import RegionKit | ||
|
|
||
| /// Reads and writes the single CloudKit-synced planned-stay register. | ||
| public struct PlannedStayCoordinator: Sendable { | ||
| private let store: any WhereStore | ||
| private let calendar: Calendar | ||
| private let now: @Sendable () -> Date | ||
|
|
||
| init(store: any WhereStore, calendar: Calendar, now: @escaping @Sendable () -> Date) { | ||
| self.store = store | ||
| self.calendar = calendar | ||
| self.now = now | ||
| } | ||
|
|
||
| /// The active stay as of the injected clock. An expired value is replaced | ||
| /// with a tombstone before returning so every device converges on “cleared.” | ||
| public func active() async throws -> PlannedStay? { | ||
| guard let record = try await latestRecord() else { return nil } | ||
| guard let stay = record.value else { return nil } | ||
| let today = CalendarDay(from: now(), in: calendar) | ||
| guard stay.through < today else { return stay } | ||
| return try await expireIfLatest(record, asOf: today) | ||
| } | ||
|
|
||
| /// Replace any prior intent with a stay through the inclusive day. | ||
| public func set(region: Region, through: CalendarDay) async throws { | ||
| try await write(value: PlannedStay(region: region, through: through)) | ||
| } | ||
|
|
||
| /// Clear the active stay with a synced tombstone. | ||
| public func clear() async throws { | ||
| try await write(value: nil) | ||
| } | ||
|
|
||
| private func latestRecord() async throws -> PlannedStayRecord? { | ||
| try await store.plannedStayRecords().max { lhs, rhs in | ||
| PlannedStayRecord.newer(rhs, than: lhs) | ||
| } | ||
| } | ||
|
|
||
| /// Clear `expiredRecord` only if it is still the winning revision. The | ||
| /// transactional re-read prevents a stale `active()` read from erasing a | ||
| /// newer stay saved while that read was suspended, and returns that newer | ||
| /// stay so the caller cannot replace it with stale `nil` state. | ||
| func expireIfLatest( | ||
| _ expiredRecord: PlannedStayRecord, | ||
| asOf today: CalendarDay, | ||
| ) async throws -> PlannedStay? { | ||
| try await store.perform { | ||
| guard let latest = try await latestRecord() else { return nil } | ||
| guard latest == expiredRecord else { | ||
| guard let stay = latest.value, stay.through >= today else { return nil } | ||
| return stay | ||
| } | ||
| guard let stay = expiredRecord.value, stay.through < today else { return nil } | ||
| let tombstone = PlannedStayRecord( | ||
| id: UUID(), | ||
| value: nil, | ||
| updatedAt: max(now(), expiredRecord.updatedAt.addingTimeInterval(0.001)), | ||
| ) | ||
| try await store.replacePlannedStayRecord(with: tombstone) | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| private func write(value: PlannedStay?) async throws { | ||
| try await store.perform { | ||
| let latest = try await latestRecord() | ||
| let timestamp = latest.map { | ||
| max(now(), $0.updatedAt.addingTimeInterval(0.001)) | ||
| } ?? now() | ||
| let record = PlannedStayRecord(id: UUID(), value: value, updatedAt: timestamp) | ||
| try await store.replacePlannedStayRecord(with: record) | ||
| } | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
Where/WhereCore/Sources/Forecasting/PlannedStayRecord.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import Foundation | ||
|
|
||
| /// One revision of the single synced planned-stay register. A `nil` value is a | ||
| /// tombstone, retained so a delayed CloudKit import cannot resurrect an older | ||
| /// active stay after it was cleared or expired. | ||
| public struct PlannedStayRecord: Hashable, Sendable, Codable, Identifiable { | ||
| public let id: UUID | ||
| public let value: PlannedStay? | ||
| public let updatedAt: Date | ||
|
|
||
| public init(id: UUID, value: PlannedStay?, updatedAt: Date) { | ||
| self.id = id | ||
| self.value = value | ||
| self.updatedAt = updatedAt | ||
| } | ||
|
|
||
| /// Deterministic last-writer ordering for duplicate rows produced by | ||
| /// eventually-consistent CloudKit writes. | ||
| public static func newer(_ lhs: PlannedStayRecord, than rhs: PlannedStayRecord) -> Bool { | ||
| if lhs.updatedAt != rhs.updatedAt { return lhs.updatedAt > rhs.updatedAt } | ||
| return lhs.id.uuidString > rhs.id.uuidString | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review focus: this is the load-bearing forecast policy. Planned days begin tomorrow, include the selected through-date, and baseline projection resumes the following day. The tests cover the April threshold, matching and non-matching stays, and cross-year stays.