Compare commits

..
Author SHA1 Message Date
FuelBoard Contributor ff8a1e18d0 Redesign the station listing and move the Best Value controls
Two columns split by a 1pt hairline: identity on the left at a fixed 52%
share so rows line up when scrolling, price and savings on the right,
leading-aligned on one axis with the price dominant. The favourites star
sits under the station logo, freeing the width the pounds-and-pence price
needs to render in full rather than scaled or truncated.

Badges stay tinted rather than filled — BEST VALUE green, CHEAPEST blue,
none for nearest — and the verdict capsule is one shared view across the
listing, the detail sheet and the compact summary, so wording and colour
cannot drift between them.

Best Value's minimum saving moves from Alerts to Settings, Fuel Savings,
beside the fill size and MPG that produce the saving; the Alerts tab reads
it back instead of offering it twice. Its options are now 50p steps to £5
(was 50p/£1/£2/£5), so £2.50 and £3 are reachable, with a test pinning the
step, the ceiling and the store's string round-trip.

The verdict capsule scales to 0.7 before truncating. Measured on a 393pt
screen its copy is handed ~69pt while "Closest station" needs ~90pt, so the
old 0.8 floor could not reach it and rows showed "Closest stati..." instead.

Verified: Debug build clean, swift test 249/249.
2026-10-16 13:38:11 +01:00
FuelBoard Contributor e960ef85c6 Make station price age informational only
The relay's price_updated is the maximum price_last_updated across the grades it maps, so it cannot vouch for the selected grade: stop using it to score, gate or warn about Best Value.

- FuelPriceFreshness is now station-level and display-only: one age per station, fresh/outdated/unknown/invalid, "May be outdated" past 30 days, with future-tolerance and non-finite guards.
- Best Value restores the closest-station-selling-the-selected-fuel baseline and its savings ranking; eligibility gating, eligible-first sorting and the unavailable banner are gone.
- Price age appears in the More info sheet only - no listing-row warnings, no extra banners.
- Copy reverted from "closest eligible station" to "closest station"; stale price-confidence strings removed, "May be outdated" added.
- Dormant per-grade timestamp plumbing removed, and regression tests added for every fuel type, missing/invalid/future stamps and the bundled offline dump.
2026-10-16 09:48:01 +01:00
FuelBoard Contributor 5900a81473 Station detail: price above its age, and the verdict caption on its own line
- More info lists the fuel price first, with "Price updated" beneath it:
  the price is what the row is about, the age qualifies it.
- The detail sheet stacks "vs closest eligible station" under the verdict
  capsule, matching the listing rows, so the caption no longer shares a
  line with the verdict it describes.
2026-10-15 22:48:07 +01:00
FuelBoard Contributor ed3a5137cd Best Value rows: capsule on its own line, comparison caption beneath
The verdict capsule shared a line with "vs closest eligible station"; the
caption's layoutPriority squeezed the capsule until it truncated
("Approx. £2.75 better off after tra…"), and in this sort mode the verdict
is the point of the row.

- The capsule now owns the line and the caption sits under it.
- The capsule text also shrinks rather than truncating at large Dynamic
  Type sizes, since nothing competes with it for width.
- The detail sheet keeps its side-by-side layout: it has the room, and the
  verdict there is the sheet's headline.
2026-10-15 22:25:53 +01:00
FuelBoard Contributor 5f3051aed7 Best Value: one price age instead of a source breakdown
Dated pricing had crowded More info and the station rows, and most of the
extra copy described a distinction the data cannot make: every station
carries a single station-wide timestamp, so "grade-specific vs
station-wide" never varied in practice.

- More info shows one row, "Price updated 28h ago" (or "Not provided"),
  replacing the separate station-report and fuel-update-time rows and the
  blanket "price freshness is not confirmed" label.
- Rows and the detail sheet stay quiet when a saving is shown; only an
  ineligible comparison explains itself. Provisional savings already read
  as estimates from the capsule, so the fuel-named warning lines are gone.
- Freshness/eligibility logic is unchanged: it still gates the baseline and
  still supports grade-specific timestamps for when the relay emits them.
- Tests updated; localisation keys for the removed copy dropped.
2026-10-15 22:00:48 +01:00
FuelBoard Contributor 5c0458dbf6 Drop deprecated MapKit and ActivityKit calls, and a dead capture
- RoadDistanceService builds route endpoints with MKMapItem(location:address:)
  instead of the MKPlacemark path deprecated in iOS 26.
- LiveActivityManager updates through ActivityContent, replacing the
  ActivityKit update(using:) call deprecated in iOS 16.2.
- The location-update hook no longer captures an unused state object; the
  closure body already runs on self, so behaviour is unchanged.
2026-10-15 21:37:41 +01:00
FuelBoard Contributor 9e77ee2947 Best Value: explain price age per surface instead of one blanket warning
- Station detail now separates the station's own report age from the
  selected fuel's update time, so a recent station-wide report no longer
  reads as an old price.
- Warning copy names the fuel and says which side is weak: the station's
  price is not individually dated, or the baseline's is. The misleading
  "unverified or older than 7 days" line is gone.
- Wording stays "Closest" throughout; new copy uses Unleaded / Premium /
  Diesel rather than the internal grade codes.
- Localisation: new and updated keys for the added copy.
2026-10-15 21:37:35 +01:00
FuelBoard Contributor 7c2eeb2604 Best Value: baseline on the closest eligible price and gate on freshness
- Add FuelPriceFreshness: selected-fuel-aware eligibility plus a shared
  comparison confidence, so a saving is presented as verified only when
  both the candidate and the baseline pass the gate for the fuel on screen.
- Rank against the closest station with an eligible selected-fuel price
  instead of the physically closest station, so a single stale neighbour
  can no longer invalidate every comparison in the list. Ordinary Closest
  sorting still includes every priced station.
- Keep ineligible prices visible, fall back to pump-price order, and label
  Best Value unavailable when no comparison qualifies.
- Widget: same baseline and confidence path as the app.
- Tests: stale-closest baseline, alert baseline, eligibility policy,
  boundary and missing-timestamp regressions.
2026-10-15 21:37:24 +01:00
FuelBoard Contributor 39a97f4905 Standardise onboarding header sizes 2026-10-15 17:23:25 +01:00
FuelBoard Contributor 3819b8a6ab Add Best Value small widget and standardise Closest wording 2026-10-15 17:14:02 +01:00
FuelBoard Contributor a5688cbac2 Clarify fuel savings comparison labels 2026-10-15 11:38:24 +01:00
FuelBoard Contributor 558f956d8d Update FuelBoard onboarding copy, title formatting, key sheet card wrapping, and best-value button placement 2026-10-14 16:22:31 +01:00
FuelBoard Contributor f04a0fe0f5 Key sheet: gate the How Best Value row on the feature, like the More info row
The More info row went inside the Best Value card's `if let fuelSavings`, but the
Key sheet row was left ungated, so it stayed visible with Best Value switched off.
It is now gated on `fuelSavingsSettings.isConfigured` — exactly the condition
`savingsForStation` uses, i.e. the same gate as the card — so the two rows appear
and disappear together.

Verified on the simulator by toggling Best Value in Settings and scrolling the Key
sheet to its end (four drags, sheet still up and its footer in view each time):
- OFF: the row is absent at every scroll position, and the More info sheet shows
  neither the card nor the row;
- ON: the row is present, and the More info card and its row are both back.
210 tests pass; Release builds.
2026-10-14 15:19:20 +01:00
FuelBoard Contributor f35f605b58 Onboarding welcome: the app icon stands on its own, with no circle behind it
The first onboarding screen showed the app icon inside AnimatedOnboardingIcon's
soft circle — a 10% tinted disc with an 18% ring around it. The wrapper now takes
`showsHalo`, defaulting to true so the other five pages and BestValueIntroView keep
theirs unchanged; the welcome page passes false.

Verified with before/after installs on the simulator:
- the icon's artwork is pixel-identical and unmoved (centre 603,661, 95 pt);
- the halo is gone — the tile's non-background footprint falls from the 118 pt
  ring to exactly the 96 pt tile, and the ring pixels at r=59 pt lose their tint;
- page 1 differs only by the status-bar clock, so the other pages are untouched.

The copy below the icon tightens by ~11 pt: the page block is centred between two
spacers and the icon's container no longer contributes 22 pt of height. The page
dots and the Continue button do not move. The icon keeps its soft accent shadow.
2026-10-14 15:02:29 +01:00
FuelBoard Contributor 7da277547b More info sheet: the copy confirmation reads "Postcode copied"
The capsule label was just "Copied", which reads oddly above a row whose hint is
"Copies the postcode". It is now "Postcode copied".

Still centred over the address row (centre x 603 of a 1206 px screen) and still a
pure overlay: the bands above and below the capsule are pixel-identical while it
is up (no reflow), and the row stays tappable straight through it.

The "Copied" localisation key goes with its only use; "Postcode copied" replaces it.
2026-10-14 14:52:07 +01:00
FuelBoard Contributor 93df94ddc9 How Best Value works: its own sheet, opened from the Key sheet and More info sheet
The explanation used to be a section inside the Key sheet. It is a standalone
HowBestValueSheet now, opened from a tappable row with a chevron: at the bottom of
the Key sheet, and at the bottom of the More info sheet below the Best Value card.

Gating: the More info row sits INSIDE the same `if let fuelSavings` as the card it
follows, so it disappears with the feature. Verified with Best Value toggled off in
Settings: the More info sheet then shows neither the card nor the row. The Key
sheet row is deliberately ungated — that sheet is the legend and is reachable
whatever the feature is doing.

Copy is unchanged: the same Localizable.strings strings are reused, and the old
section header became the sheet's title. A DEBUG-only `-showBestValueInfo` hook
opens the sheet without a tap.
2026-10-14 14:37:18 +01:00
FuelBoard Contributor 78b43ce6d7 Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 13:57:21 +01:00
FuelBoard Contributor 13967c3782 Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 13:45:05 +01:00
FuelBoard Contributor 4718e9b76a Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 13:16:20 +01:00
FuelBoard Contributor 6dfe732199 Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 12:48:33 +01:00
FuelBoard Contributor f0c13a79d6 Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 12:25:17 +01:00
FuelBoard Contributor 6b41e8ac51 Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 12:07:54 +01:00
FuelBoard Contributor e58dbb7833 Merge branch 'feature/more-info-map-and-postcode-copy' into integration/more-info-and-best-value 2026-10-14 11:52:42 +01:00
FuelBoard Contributor 7ee1f06ce6 Merge branch 'feature/best-value-candidate-fill' into integration/more-info-and-best-value 2026-10-14 11:34:33 +01:00
FuelBoard Contributor 6ea675499e Best Value detail sheet: keep the verdict capsule left-aligned
The capsule was right-aligned on its own line; the user asked for it back at
the left margin, leaving the Total row as it is.
2026-10-14 11:31:59 +01:00
FuelBoard Contributor 3c424ab397 Best Value: candidate-priced fills, key copy, detail total 2026-10-14 10:43:12 +01:00
33 changed files with 2049 additions and 446 deletions
+8 -8
View File
@@ -533,7 +533,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = Config/WatchApp.entitlements; CODE_SIGN_ENTITLEMENTS = Config/WatchApp.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -599,7 +599,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = Config/WatchApp.entitlements; CODE_SIGN_ENTITLEMENTS = Config/WatchApp.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -663,7 +663,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -728,7 +728,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES; ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -826,7 +826,7 @@
CODE_SIGN_ENTITLEMENTS = Config/App.entitlements; CODE_SIGN_ENTITLEMENTS = Config/App.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO; GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/App-Info.plist"; INFOPLIST_FILE = "Config/App-Info.plist";
@@ -851,7 +851,7 @@
CODE_SIGN_ENTITLEMENTS = Config/App.entitlements; CODE_SIGN_ENTITLEMENTS = Config/App.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO; GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/App-Info.plist"; INFOPLIST_FILE = "Config/App-Info.plist";
@@ -875,7 +875,7 @@
APPLICATION_EXTENSION_API_ONLY = YES; APPLICATION_EXTENSION_API_ONLY = YES;
CODE_SIGN_ENTITLEMENTS = Config/Widget.entitlements; CODE_SIGN_ENTITLEMENTS = Config/Widget.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO; GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/Widget-Info.plist"; INFOPLIST_FILE = "Config/Widget-Info.plist";
@@ -900,7 +900,7 @@
APPLICATION_EXTENSION_API_ONLY = YES; APPLICATION_EXTENSION_API_ONLY = YES;
CODE_SIGN_ENTITLEMENTS = Config/Widget.entitlements; CODE_SIGN_ENTITLEMENTS = Config/Widget.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26; CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3; DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO; GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/Widget-Info.plist"; INFOPLIST_FILE = "Config/Widget-Info.plist";
+9 -9
View File
@@ -13,7 +13,10 @@ struct AlertsView: View {
@Binding var radius: Double // stored in km (monitor + storage) @Binding var radius: Double // stored in km (monitor + storage)
@Binding var fuel: FuelType // the fuel alerts monitor for @Binding var fuel: FuelType // the fuel alerts monitor for
@Binding var alertMode: AlertMode @Binding var alertMode: AlertMode
@Binding var bestValueThresholdGBP: Double /// Read-only here: the threshold is edited in Settings → Fuel Savings, where
/// the fill size and MPG that decide the saving live. Read back so the
/// alert's own rule is visible without leaving the tab.
let bestValueThresholdGBP: Double
let bestValueConfigured: Bool let bestValueConfigured: Bool
@Binding var favouriteDropEnabled: Bool @Binding var favouriteDropEnabled: Bool
@Binding var favouriteDropFuel: FuelType @Binding var favouriteDropFuel: FuelType
@@ -178,17 +181,14 @@ struct AlertsView: View {
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
if alertMode == .bestValue { if alertMode == .bestValue {
Picker(String(localized: "Minimum saving", comment: "Best Value alert threshold picker title"), selection: $bestValueThresholdGBP) { // The threshold is edited in Settings → Fuel Savings: it
ForEach(FuelStore.bestValueAlertThresholdOptionsGBP, id: \.self) { value in // labels station rows BEST VALUE as well as gating this
Text(FuelSavingsFormat.money(value)).tag(value) // alert, so it lives with the fill size and MPG that
} // produce the saving. Read back here, not offered twice.
} Text(String(format: String(localized: "Minimum saving %@ — change in Settings, Fuel Savings.", comment: "Best Value alert threshold read-back"), FuelSavingsFormat.money(bestValueThresholdGBP)))
if !bestValueConfigured {
Text(String(localized: "Set up Best Value first so FuelBoard can account for your fill size, MPG and travel cost.", comment: "Best Value alert setup hint"))
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} }
}
if enabled && monitoredCount == 0 { if enabled && monitoredCount == 0 {
Text(String(localized: "No stations monitored yet — open the Stations tab to load prices first.", comment: "No monitored stations hint")) Text(String(localized: "No stations monitored yet — open the Stations tab to load prices first.", comment: "No monitored stations hint"))
.font(.caption) .font(.caption)
+294 -95
View File
@@ -29,7 +29,7 @@ struct ContentView: View {
@State private var sortMode: SortMode = ContentView.qaSortModeOverride(default: FuelStore.loadSortMode()) @State private var sortMode: SortMode = ContentView.qaSortModeOverride(default: FuelStore.loadSortMode())
@State private var stationLimit: Int = ContentView.qaStationRadiusOverride(default: FuelStore.loadStationLimit()) @State private var stationLimit: Int = ContentView.qaStationRadiusOverride(default: FuelStore.loadStationLimit())
@State private var distanceUnit: DistanceUnit = FuelStore.loadDistanceUnit() @State private var distanceUnit: DistanceUnit = FuelStore.loadDistanceUnit()
@State private var priceDisplayStyle: PriceDisplayStyle = FuelStore.loadPriceDisplayStyle() @State private var priceDisplayStyle: PriceDisplayStyle = ContentView.qaPriceStyleOverride(default: FuelStore.loadPriceDisplayStyle())
@State private var stationTapAction: StationTapAction = FuelStore.loadStationTapAction() @State private var stationTapAction: StationTapAction = FuelStore.loadStationTapAction()
@State private var fuelSavingsSettings: FuelSavingsSettings = FuelStore.loadFuelSavingsSettings() @State private var fuelSavingsSettings: FuelSavingsSettings = FuelStore.loadFuelSavingsSettings()
@State private var sessionFuelSavingsAmount: FuelSavingsFillAmount = FuelStore.loadFuelSavingsSettings().preferredAmount @State private var sessionFuelSavingsAmount: FuelSavingsFillAmount = FuelStore.loadFuelSavingsSettings().preferredAmount
@@ -114,6 +114,21 @@ struct ContentView: View {
return fallback return fallback
} }
/// QA hook: `-priceStyle poundsPence` renders prices in the wide pounds &
/// pence form for ONE launch. Same reason as `-sortMode`: simctl has no tap
/// command, so the wide price has to be measured against the row's column
/// widths without walking Settings → Units for every check. Never persisted.
private static func qaPriceStyleOverride(default fallback: PriceDisplayStyle) -> PriceDisplayStyle {
#if DEBUG
let args = ProcessInfo.processInfo.arguments
if let i = args.firstIndex(of: "-priceStyle"), i + 1 < args.count,
let style = PriceDisplayStyle(rawValue: args[i + 1]) {
return style
}
#endif
return fallback
}
private static func qaSortModeOverride(default fallback: SortMode) -> SortMode { private static func qaSortModeOverride(default fallback: SortMode) -> SortMode {
#if DEBUG #if DEBUG
let args = ProcessInfo.processInfo.arguments let args = ProcessInfo.processInfo.arguments
@@ -161,7 +176,7 @@ struct ContentView: View {
} }
private func installLocationUpdateHook() { private func installLocationUpdateHook() {
locationManager.onLocationUpdate = { [weak monitor] in locationManager.onLocationUpdate = {
self.updateAlertMonitor() self.updateAlertMonitor()
// The Live Activity follows the same wake-ups — this hook // The Live Activity follows the same wake-ups — this hook
// fires on every fix incl. background significant-change // fires on every fix incl. background significant-change
@@ -401,28 +416,27 @@ struct ContentView: View {
/// (computing a journey for each) and `savingsLookup` immediately scanned them /// (computing a journey for each) and `savingsLookup` immediately scanned them
/// all AGAIN to fill the per-station map. Both now share one result. /// all AGAIN to fill the per-station map. Both now share one result.
/// ///
/// The baseline is chosen with EXACTLY the loop and guards of /// The baseline is chosen with the same journey guards as
/// `FuelSavingsEstimator.baselineStation`, so the row labelled "Closest /// `FuelSavingsEstimator.baselineStation` when configured; with the feature
/// station" cannot move — and it is still selected when the feature is /// off, the ordinary Closest station still names that row.
/// unconfigured (it names that row), while the maps are only built when the
/// labels will actually be shown.
private func savingsScaffold() -> (baseline: FuelStation?, journeys: [String: FuelSavingsJourney]) { private func savingsScaffold() -> (baseline: FuelStation?, journeys: [String: FuelSavingsJourney]) {
guard let location else { return (nil, [:]) } guard let location else { return (nil, [:]) }
let configured = fuelSavingsSettings.isConfigured guard fuelSavingsSettings.isConfigured else {
let baseline = FuelSavingsEstimator.baselineStation(stations, fuel: selectedFuel) {
savingsJourneyMiles(for: $0, location: location)
}
return (baseline, [:])
}
var journeys: [String: FuelSavingsJourney] = [:] var journeys: [String: FuelSavingsJourney] = [:]
var bestStation: FuelStation?
var bestMiles = Double.infinity
for station in stations where station.prices[selectedFuel] != nil { for station in stations where station.prices[selectedFuel] != nil {
guard let journey = savingsJourneyMiles(for: station, location: location) else { continue } if let journey = savingsJourneyMiles(for: station, location: location) {
if configured { journeys[station.id] = journey } journeys[station.id] = journey
let miles = journey.miles
guard miles.isFinite, miles >= 0 else { continue }
if miles < bestMiles {
bestMiles = miles
bestStation = station
} }
} }
return (bestStation, configured ? journeys : [:]) let baseline = FuelSavingsEstimator.baselineStation(stations, fuel: selectedFuel) {
journeys[$0.id]
}
return (baseline, journeys)
} }
/// Row/detail savings lookup with the comparison baseline and the per-station /// Row/detail savings lookup with the comparison baseline and the per-station
@@ -566,10 +580,34 @@ struct ContentView: View {
func source(_ basis: FuelSavingsDistanceBasis) -> String { func source(_ basis: FuelSavingsDistanceBasis) -> String {
basis == .roadRoute ? "road route" : "straight-line estimate" basis == .roadRoute ? "road route" : "straight-line estimate"
} }
let price = station.prices[selectedFuel].map { String(format: "%.1fp/L", $0) } ?? "—" func amount(_ value: FuelSavingsFillAmount) -> String {
let baselinePrice = baseline?.prices[selectedFuel].map { String(format: "%.1fp/L", $0) } ?? "—" switch value.unit {
case .pounds: return String(format: "£%.2f", value.value)
case .litres: return String(format: "%.2f L", value.value)
}
}
func rawMoney(_ value: Double?) -> String {
value.map { String(format: "£%.6f", $0) } ?? "—"
}
let candidatePriceValue = station.prices[selectedFuel]
let baselinePriceValue = baseline?.prices[selectedFuel]
let price = candidatePriceValue.map { String(format: "%.1fp/L", $0) } ?? "—"
let baselinePrice = baselinePriceValue.map { String(format: "%.1fp/L", $0) } ?? "—"
let priceDifference = candidatePriceValue.flatMap { candidate in
baselinePriceValue.map { String(format: "%+.1fp/L", $0 - candidate) }
} ?? "—"
let litresBasis = sessionFuelSavingsAmount.unit == .pounds ? "candidate price" : "fixed litres"
let rows: [(String, String)] = [ let rows: [(String, String)] = [
("Station", "\(station.name) (\(station.id))"), ("Station", "\(station.name) (\(station.id))"),
("Settings default fill-up", amount(fuelSavingsSettings.preferredAmount)),
("Effective/session fill-up", amount(sessionFuelSavingsAmount)),
("Fill-up unit", sessionFuelSavingsAmount.unit.displayName),
("MPG", String(format: "%.1f UK MPG", fuelSavingsSettings.mpg)),
("Candidate price", price),
("Baseline price", baselinePrice),
("Price difference", priceDifference),
("Candidate litres", result.map { String(format: "%.6f L · %@", $0.fillLitres, litresBasis) } ?? "—"),
("Gross saving raw", rawMoney(result?.grossSavingGBP)),
("Displayed distance", "\(distanceUnit.format(stationDistance.displayDistanceKM)) · \(source(stationDistance.displaySource))"), ("Displayed distance", "\(distanceUnit.format(stationDistance.displayDistanceKM)) · \(source(stationDistance.displaySource))"),
("Outward road", meters(stationDistance.outwardMeters)), ("Outward road", meters(stationDistance.outwardMeters)),
("Return road", stationDistance.hasMeasuredReturn ? meters(stationDistance.returnMeters) : "inferred or unavailable"), ("Return road", stationDistance.hasMeasuredReturn ? meters(stationDistance.returnMeters) : "inferred or unavailable"),
@@ -581,12 +619,11 @@ struct ContentView: View {
("Station journey", miles(journey?.miles)), ("Station journey", miles(journey?.miles)),
("Baseline journey", miles(baselineJourney?.miles)), ("Baseline journey", miles(baselineJourney?.miles)),
("Additional journey", miles(result?.extraDistanceMiles)), ("Additional journey", miles(result?.extraDistanceMiles)),
("Additional fuel used", result.map { String(format: "%.6f L", $0.extraFuelLitres) } ?? "—"),
("Confidence", result?.journeyConfidence.rawValue ?? "estimated"), ("Confidence", result?.journeyConfidence.rawValue ?? "estimated"),
("Fuel price", price), ("Travel cost raw", rawMoney(result?.extraDrivingCostGBP)),
("Baseline price", baselinePrice), ("Net saving raw", rawMoney(result?.netSavingGBP)),
("Gross saving", result.map { FuelSavingsFormat.money($0.grossSavingGBP) } ?? "—"), ("Displayed net saving", result?.headline() ?? "—")
("Travel cost", result.map { FuelSavingsFormat.money($0.extraDrivingCostGBP) } ?? "—"),
("Net saving", result.map { FuelSavingsFormat.money($0.netSavingGBP) } ?? "—")
] ]
return FuelSavingsJourneyDiagnostics(rows: rows) return FuelSavingsJourneyDiagnostics(rows: rows)
#else #else
@@ -1096,6 +1133,11 @@ struct ContentView: View {
} }
} }
.onChange(of: fuelSavingsSettings) { old, new in .onChange(of: fuelSavingsSettings) { old, new in
// An explicit Settings default edit supersedes the temporary slider
// override. Changes to MPG/enabled alone leave the session fill intact.
if old.preferredAmount != new.preferredAmount {
sessionFuelSavingsAmount = new.preferredAmount
}
// Fuel Savings changed in Settings while the app was running: the // Fuel Savings changed in Settings while the app was running: the
// effective sort follows automatically (no stored sort is touched). // effective sort follows automatically (no stored sort is touched).
#if DEBUG #if DEBUG
@@ -1104,6 +1146,13 @@ struct ContentView: View {
ensureBestValueAlertModeIsAvailable() ensureBestValueAlertModeIsAvailable()
updateAlertMonitor() updateAlertMonitor()
} }
.onChange(of: sessionFuelSavingsAmount) { _, _ in
// This remains a session-only override: do not write it to FuelStore.
// Any active Best Value alert/Live Activity must nevertheless use
// the same effective amount as rows, details, favourites and sorting.
updateAlertMonitor()
updateLiveActivity()
}
.onChange(of: scenePhase) { _, newPhase in .onChange(of: scenePhase) { _, newPhase in
if newPhase == .active { if newPhase == .active {
// Never start location tracking while onboarding is on screen — // Never start location tracking while onboarding is on screen —
@@ -1493,7 +1542,6 @@ struct ContentView: View {
fuelSavingsSettings: fuelSavingsSettings, fuelSavingsSettings: fuelSavingsSettings,
fuelSavingsAmount: $sessionFuelSavingsAmount, fuelSavingsAmount: $sessionFuelSavingsAmount,
savingsForStation: savingsLookup(baseline: baselineStation, journeys: scaffold.journeys), savingsForStation: savingsLookup(baseline: baselineStation, journeys: scaffold.journeys),
savingsBaselineStationName: baselineStation?.name,
journeyDiagnosticsForStation: { station in journeyDiagnostics(for: station, baseline: baselineStation) }, journeyDiagnosticsForStation: { station in journeyDiagnostics(for: station, baseline: baselineStation) },
onToggleFavourite: toggleFavourite, onToggleFavourite: toggleFavourite,
onRefresh: { await refresh(force: true) } onRefresh: { await refresh(force: true) }
@@ -1515,7 +1563,6 @@ struct ContentView: View {
fuelSavingsSettings: fuelSavingsSettings, fuelSavingsSettings: fuelSavingsSettings,
fuelSavingsAmount: $sessionFuelSavingsAmount, fuelSavingsAmount: $sessionFuelSavingsAmount,
savingsForStation: savingsLookup(baseline: baselineStation, journeys: scaffold.journeys), savingsForStation: savingsLookup(baseline: baselineStation, journeys: scaffold.journeys),
savingsBaselineStationName: baselineStation?.name,
journeyDiagnosticsForStation: { station in journeyDiagnostics(for: station, baseline: baselineStation) }, journeyDiagnosticsForStation: { station in journeyDiagnostics(for: station, baseline: baselineStation) },
onToggleFavourite: toggleFavourite, onToggleFavourite: toggleFavourite,
onReorder: reorderFavourites, onReorder: reorderFavourites,
@@ -1532,7 +1579,7 @@ struct ContentView: View {
radius: $alertsRadius, radius: $alertsRadius,
fuel: $alertsFuel, fuel: $alertsFuel,
alertMode: $alertsMode, alertMode: $alertsMode,
bestValueThresholdGBP: $alertsBestValueThresholdGBP, bestValueThresholdGBP: alertsBestValueThresholdGBP,
bestValueConfigured: fuelSavingsSettings.isConfigured, bestValueConfigured: fuelSavingsSettings.isConfigured,
favouriteDropEnabled: $favouriteDropAlertsEnabled, favouriteDropEnabled: $favouriteDropAlertsEnabled,
favouriteDropFuel: $favouriteDropAlertsFuel, favouriteDropFuel: $favouriteDropAlertsFuel,
@@ -1560,6 +1607,7 @@ struct ContentView: View {
priceDisplayStyle: $priceDisplayStyle, priceDisplayStyle: $priceDisplayStyle,
stationTapAction: $stationTapAction, stationTapAction: $stationTapAction,
fuelSavingsSettings: $fuelSavingsSettings, fuelSavingsSettings: $fuelSavingsSettings,
bestValueThresholdGBP: $alertsBestValueThresholdGBP,
dataRefreshMode: $dataRefreshMode, dataRefreshMode: $dataRefreshMode,
alertsFuel: alertsFuel, alertsFuel: alertsFuel,
alertsRadiusKM: alertsRadius, alertsRadiusKM: alertsRadius,
@@ -1743,20 +1791,47 @@ struct StationRow: View {
let distanceUnit: DistanceUnit let distanceUnit: DistanceUnit
let priceDisplayStyle: PriceDisplayStyle let priceDisplayStyle: PriceDisplayStyle
let baselinePrice: Double? let baselinePrice: Double?
/// This row is the cheapest price in range — the caller's existing
/// `topStationID` test. Feeds the CHEAPEST badge.
let isTopResult: Bool let isTopResult: Bool
let isFavourite: Bool let isFavourite: Bool
/// Label for the cheapest-pump-price badge ("TOP" in price/distance order,
/// "CHEAPEST" when the list is ranked by net saving).
var topBadgeText: String = "TOP"
var tapAction: StationTapAction = .openMap var tapAction: StationTapAction = .openMap
var fuelSavings: FuelSavingsAvailability? var fuelSavings: FuelSavingsAvailability?
/// The session fill-up figure (the one the adjustment control edits). The /// The user's Best Value alert threshold — the app's existing gate for
/// compact banner does not print it today, but a row that carried a hard /// calling a saving worth the drive, so a row labels itself BEST VALUE by
/// zero would print "for £0" the moment it did — pass the real figure. /// exactly the rule the alerts already use. Read per row (the alert path
var fuelSavingsAmount: FuelSavingsFillAmount = FuelSavingsSettings.defaultPreferredAmount /// reads it per evaluation too); pass explicitly to inject a value.
var bestValueThresholdGBP: Double = FuelStore.loadAlertsBestValueThresholdGBP()
var onToggleFavourite: () -> Void = {} var onToggleFavourite: () -> Void = {}
var onShowDetails: (FuelStation) -> Void = { _ in } var onShowDetails: (FuelStation) -> Void = { _ in }
/// The price's point size, scaled with Dynamic Type: the price is built from
/// an explicit size (its "p"/"/L" suffixes are sized relative to it inside
/// `priceTextAttributed`), so it needs a metric rather than a font style.
/// 22pt keeps the price the row's loudest element after the station name.
@ScaledMetric(relativeTo: .title2) private var priceSize: CGFloat = 22
/// The identity column's share of the ROW, for every row and both price
/// styles. The mockup's divider sits at ~53% of its row; this is that ratio,
/// held per row rather than derived from the row's text — the point is that
/// the hairline, the price axis and the star cannot move as the list scrolls.
/// The price column takes the remainder, and its savings capsule scales down
/// instead of widening the column and dragging the hairline with it.
///
/// One value for both price styles: the star used to sit at the end of the
/// price line and hold ~28pt of the price column, so the wide form `£1.58⁷/L`
/// — ~20pt wider than the bare `158.7` at the same point size — did not fit on
/// a 393pt screen. With the star now under the station logo the price column
/// has that width back, so the identity column no longer has to give width up
/// in pounds & pence, and names keep the same room in both styles.
private static let leftSectionShare: CGFloat = 0.52
/// The comparison label sits beside the capsule only where the row is wide
/// enough for both (regular width). On an iPhone the mockup's canvas is
/// wider than the whole screen, so the label drops under the capsule rather
/// than starving the station name.
@Environment(\.horizontalSizeClass) private var sizeClass
private var ragColor: Color { private var ragColor: Color {
guard let price = station.prices[fuel], let baselinePrice else { return .gray } guard let price = station.prices[fuel], let baselinePrice else { return .gray }
switch RAGRating.rating(price: price, cheapest: baselinePrice) { switch RAGRating.rating(price: price, cheapest: baselinePrice) {
@@ -1782,6 +1857,26 @@ struct StationRow: View {
return abs(price - baselinePrice) <= 0.05 return abs(price - baselinePrice) <= 0.05
} }
/// The row's single recommendation badge, if any. BEST VALUE (worth the
/// drive by the alert threshold) outranks CHEAPEST; NEAREST never gets one,
/// being context rather than a recommendation.
private var recommendationBadge: StationRecommendationBadge? {
StationRecommendationBadge.badge(
netSavingGBP: fuelSavings?.result?.netSavingGBP,
isCheapest: isTopResult,
bestValueThresholdGBP: bestValueThresholdGBP
)
}
/// VoiceOver: the price, then the delta the redesign no longer prints — the
/// listing shows a savings capsule in its place, so the comparison against
/// the cheapest price in range would otherwise be visible only as a colour.
private func priceSpokenLabel(_ price: Double) -> String {
guard let deltaText else { return FuelStore.priceTextSpoken(price) }
let comparison = String(localized: "vs cheapest", comment: "Price delta comparison caption")
return "\(FuelStore.priceTextSpoken(price)), \(isCheapestPrice ? deltaText : "\(deltaText) \(comparison)")"
}
private func handleTap() { private func handleTap() {
switch tapAction { switch tapAction {
case .openMap: case .openMap:
@@ -1798,9 +1893,31 @@ struct StationRow: View {
} }
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 6) { // Two sections, one hairline: station identity on the left, price and
HStack(spacing: 12) { // savings on the right. No wrapper VStack and no full-width verdict
// LEFT — round brand logo (or generic fuel pump fallback) // banner under the row — the savings capsule carries the verdict inside
// the right-hand column, and the extra travel behind it is explained in
// the detail sheet instead of being repeated on every row.
HStack(alignment: .center, spacing: 12) {
// LEFT SECTION — station identity: brand logo, then name, address and
// distance. Given a FIXED SHARE of the row (~52%, the mockup's ratio)
// rather than sizing to its content: sized to content, this column
// grew and shrank with each row's badge and savings copy, which moved
// the hairline 23pt between adjacent rows (x767 on a BEST VALUE row,
// x699 on a "costs more" row) — so the divider and the price axis
// both jumped sideways as the list scrolled. One share for every row
// puts them on a single vertical line down the whole list.
HStack(alignment: .top, spacing: 12) {
// The logo, with the favourite star directly beneath it. Moving
// the star out of the price line is what gives the price column
// its width back: sat at the end of that line it held ~28pt of
// the column, which is exactly the space the wide pounds &
// pence price needs for its own digits on a 393pt screen.
// 10pt between logo and star: at 4pt the star's glyph sat almost
// against the logo's bottom edge and read as part of it rather
// than as the control it is.
VStack(spacing: 10) {
// Round brand logo (or generic fuel pump fallback)
Group { Group {
if let asset = station.brandImageName { if let asset = station.brandImageName {
Image(asset) Image(asset)
@@ -1819,13 +1936,21 @@ struct StationRow: View {
.overlay(Circle().stroke(Color.primary.opacity(0.10), lineWidth: 1)) .overlay(Circle().stroke(Color.primary.opacity(0.10), lineWidth: 1))
.shadow(color: .black.opacity(0.08), radius: 2, y: 1) .shadow(color: .black.opacity(0.08), radius: 2, y: 1)
// MIDDLE — name, full address, distance favouriteButton
}
// Name, full address, distance
VStack(alignment: .leading, spacing: 2) { VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 6) { // The name WRAPS instead of truncating: the row is tall
// enough now, and a name cut to "Z A Service Stat…" cannot
// be told apart from the station next door. Baseline
// alignment keeps the notice symbols on the name's FIRST
// line instead of floating beside a two-line name.
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(station.name) Text(station.name)
.font(.headline) .font(.headline)
.lineLimit(1) .multilineTextAlignment(.leading)
.truncationMode(.tail) .fixedSize(horizontal: false, vertical: true)
ForEach(StationNotice.notices(for: station)) { notice in ForEach(StationNotice.notices(for: station)) { notice in
Image(systemName: notice.symbolName) Image(systemName: notice.symbolName)
.font(.caption2.weight(.semibold)) .font(.caption2.weight(.semibold))
@@ -1833,70 +1958,107 @@ struct StationRow: View {
.accessibilityLabel(notice.title) .accessibilityLabel(notice.title)
} }
} }
// Wraps for the same reason as the name — addresses here run
// to 70 characters at the 95th percentile.
Text(StationAddressLine.display(address: station.address, Text(StationAddressLine.display(address: station.address,
postcode: station.postcode, postcode: station.postcode,
name: station.name)) name: station.name))
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
.lineLimit(1) .multilineTextAlignment(.leading)
.truncationMode(.tail) .fixedSize(horizontal: false, vertical: true)
if let location { if let location {
let distance = FuelStore.stationDistanceDisplay( let distance = FuelStore.stationDistanceDisplay(
station: station, userLat: location.lat, userLng: location.lng station: station, userLat: location.lat, userLng: location.lng
) )
Text(distance.labelWithReturn(unit: distanceUnit)) // ONE-WAY distance: the listing shows how far the station
// is. The return leg stays in the savings explanation, where
// the extra travel it drives is actually costed.
HStack(spacing: 3) {
Image(systemName: "location.fill")
.font(.caption2)
.accessibilityHidden(true)
Text(distance.label(unit: distanceUnit))
.font(.caption2) .font(.caption2)
.foregroundStyle(.secondary)
.monospacedDigit() .monospacedDigit()
.accessibilityLabel(distance.spokenLabelWithReturn(unit: distanceUnit)) }
.foregroundStyle(.secondary)
.accessibilityElement(children: .ignore)
.accessibilityLabel(distance.spokenLabel(unit: distanceUnit))
} }
} }
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
// RIGHT — price in £ (no p) + difference vs cheapest
VStack(alignment: .trailing, spacing: 2) {
if isTopResult {
// The badge always marks the CHEAPEST PUMP PRICE (never
// "best saving"), so in Best Value order — where the
// top row is the best net saving — it may sit lower down
// the list, and says so. It sits ABOVE the price it
// annotates rather than beside the name, so it reads as
// part of the price and the name keeps its width.
Text(topBadgeText)
.font(.caption2.bold())
.padding(.horizontal, 5)
.padding(.vertical, 1)
.background(Capsule().fill(.blue.opacity(0.15)))
.foregroundStyle(.blue)
.lineLimit(1)
.fixedSize()
} }
.frame(maxWidth: .infinity, alignment: .leading)
.containerRelativeFrame(.horizontal, alignment: .leading) { length, _ in
length * Self.leftSectionShare
}
// 1pt hairline between the two sections. Inset top and bottom so it
// spans the row's content without touching the row edges, and
// decorative: the columns are told apart by their content, and two
// hairs per row would just be noise to VoiceOver.
//
// `secondary`, not `separator`: over a dark row fill the system
// separator measures 7/255 brighter than the fill — measurably
// invisible — while the mockup's rule sits ~112 above it. Secondary
// lands on the mockup's own value in both appearances.
Rectangle()
.fill(Color.secondary)
.frame(width: 1)
.frame(maxHeight: .infinity)
.padding(.vertical, 6)
.accessibilityHidden(true)
// RIGHT SECTION — price and savings, every element leading-aligned on
// ONE axis. The 12pt row spacing plus this column's leading padding
// puts that axis ~22pt right of the hairline. (The mockup centres the
// price against the badge so its status dot hangs into the gutter; the
// redesign was explicitly asked not to do that.)
VStack(alignment: .leading, spacing: 12) {
if let badge = recommendationBadge {
badgeCapsule(badge)
}
// Price line: the status dot and the price, leading-aligned on
// the column's one axis. The star no longer ends this line — it
// sits under the station logo — so this whole column width now
// belongs to the price, which is what lets the wide pounds &
// pence form (£1.58⁷/L) render at full size rather than being
// scaled down or truncated.
if let price = station.prices[fuel] { if let price = station.prices[fuel] {
HStack(spacing: 5) { HStack(spacing: 5) {
Circle() Circle()
.fill(ragColor) .fill(ragColor)
.frame(width: 8, height: 8) .frame(width: 8, height: 8)
FuelStore.priceTextAttributed(price, style: priceDisplayStyle, size: 20, weight: .bold) FuelStore.priceTextAttributed(price, style: priceDisplayStyle,
} size: priceSize, weight: .bold)
if let deltaText {
Text(deltaText)
.font(.caption2.bold().monospaced())
.foregroundStyle(ragColor)
if !isCheapestPrice {
// "+8.0p" on its own never said what it measured
// against; the delta is against the cheapest price
// in range in EVERY sort mode.
Text("vs cheapest")
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1) .lineLimit(1)
.minimumScaleFactor(0.8) .minimumScaleFactor(0.8)
} }
// The visible "+1.8p vs cheapest" line is gone with the
// redesign, so the comparison rides on the price's label.
.accessibilityElement(children: .ignore)
.accessibilityLabel(priceSpokenLabel(price))
}
if let result = fuelSavings?.result {
savingsCapsule(result)
} }
} }
.frame(maxWidth: .infinity, alignment: .leading)
// The spec's ~20-24pt of air between the divider and the price
// column: the row's own 12pt spacing plus this 10pt.
.padding(.leading, 10)
}
.contentShape(Rectangle())
.onTapGesture(perform: handleTap)
.onLongPressGesture(perform: showDetails)
} }
// FAR RIGHT — favourite star /// The favourite toggle, sitting under the station logo. Kept as its own view
/// so it stays a separate VoiceOver element — the price beside it is a single
/// grouped label — and keeps its own tap target inside the row's tap and
/// long-press gestures.
private var favouriteButton: some View {
Button { Button {
onToggleFavourite() onToggleFavourite()
} label: { } label: {
@@ -1905,25 +2067,62 @@ struct StationRow: View {
} }
.buttonStyle(.borderless) .buttonStyle(.borderless)
} }
if fuelSavings != nil {
// Full-width verdict banner under the row. Inline in the middle /// The savings capsule plus the comparison it is measured against. The
// column it truncated ("Approx. £2.75 better off after tra…") /// capsule itself is the shared verdict view, so a row, the detail sheet and
// because the /// the compact summary cannot drift apart. The comparison label sits beside
// price block squeezes that column — and the verdict is the /// the capsule only where there is width for both.
// point of this sort mode, so it gets its own line. @ViewBuilder
FuelSavingsSummaryView( private func savingsCapsule(_ result: FuelSavingsResult) -> some View {
availability: fuelSavings, let comparison = Text(FuelSavingsFormat.comparisonLabel(status: result.status))
amount: fuelSavingsAmount, .font(.caption2)
baselineStationName: nil, .foregroundStyle(.secondary)
compact: true, .lineLimit(1)
distanceUnit: distanceUnit // Same narrow column as the capsule above it, so the same floor:
) // scaled copy, not a trimmed "vs closest st…".
.minimumScaleFactor(0.7)
if sizeClass == .regular {
HStack(spacing: 8) {
FuelSavingsCapsule(result: result)
comparison
}
} else {
VStack(alignment: .leading, spacing: 2) {
FuelSavingsCapsule(result: result)
comparison
} }
} }
.contentShape(Rectangle())
.onTapGesture(perform: handleTap)
.onLongPressGesture(perform: showDetails)
} }
/// One recommendation badge, above the price it annotates. Tinted rather
/// than the mockup's solid fill, like every other badge and capsule in the
/// app: coloured text keeps its contrast in both appearances, at every
/// Dynamic Type size, without introducing a colour outside the palette.
private func badgeCapsule(_ badge: StationRecommendationBadge) -> some View {
Text(badge.title)
.font(.caption2.bold())
.foregroundStyle(badge.tint)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(Capsule().fill(badge.tint.opacity(0.15)))
.lineLimit(1)
.fixedSize()
}
}
/// Badge copy and colour for `StationRecommendationBadge` — view concerns, so
/// they stay out of the shared model the tests cover.
private extension StationRecommendationBadge {
var title: String {
switch self {
case .bestValue:
return String(localized: "BEST VALUE", comment: "Station badge: saving clears the Best Value threshold")
case .cheapest:
return String(localized: "CHEAPEST", comment: "Station badge: cheapest price in range")
}
}
var tint: Color { self == .bestValue ? .green : .blue }
} }
// MARK: - Location manager // MARK: - Location manager
+5 -13
View File
@@ -21,10 +21,9 @@ struct FavouritesView: View {
/// still never touches the Settings default. /// still never touches the Settings default.
let fuelSavingsSettings: FuelSavingsSettings let fuelSavingsSettings: FuelSavingsSettings
@Binding var fuelSavingsAmount: FuelSavingsFillAmount @Binding var fuelSavingsAmount: FuelSavingsFillAmount
/// Estimated saving for a favourite, against the nearest eligible station — /// Estimated saving for a favourite, against the closest station by
/// the same baseline and definition the Stations list uses. /// journey distance — the same baseline and definition the Stations list uses.
var savingsForStation: (FuelStation) -> FuelSavingsAvailability? = { _ in nil } var savingsForStation: (FuelStation) -> FuelSavingsAvailability? = { _ in nil }
var savingsBaselineStationName: String?
var journeyDiagnosticsForStation: (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil } var journeyDiagnosticsForStation: (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil }
var onToggleFavourite: (FuelStation, FuelType) -> Void = { _, _ in } var onToggleFavourite: (FuelStation, FuelType) -> Void = { _, _ in }
/// Persists a reordered favourites array (after drag-and-drop). /// Persists a reordered favourites array (after drag-and-drop).
@@ -84,7 +83,6 @@ struct FavouritesView: View {
fuelSavingsSettings: FuelSavingsSettings = .defaults, fuelSavingsSettings: FuelSavingsSettings = .defaults,
fuelSavingsAmount: Binding<FuelSavingsFillAmount>, fuelSavingsAmount: Binding<FuelSavingsFillAmount>,
savingsForStation: @escaping (FuelStation) -> FuelSavingsAvailability? = { _ in nil }, savingsForStation: @escaping (FuelStation) -> FuelSavingsAvailability? = { _ in nil },
savingsBaselineStationName: String? = nil,
journeyDiagnosticsForStation: @escaping (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil }, journeyDiagnosticsForStation: @escaping (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil },
onToggleFavourite: @escaping (FuelStation, FuelType) -> Void = { _, _ in }, onToggleFavourite: @escaping (FuelStation, FuelType) -> Void = { _, _ in },
onReorder: @escaping ([FavouriteEntry]) -> Void = { _ in }, onReorder: @escaping ([FavouriteEntry]) -> Void = { _ in },
@@ -99,7 +97,6 @@ struct FavouritesView: View {
self.fuelSavingsSettings = fuelSavingsSettings self.fuelSavingsSettings = fuelSavingsSettings
_fuelSavingsAmount = fuelSavingsAmount _fuelSavingsAmount = fuelSavingsAmount
self.savingsForStation = savingsForStation self.savingsForStation = savingsForStation
self.savingsBaselineStationName = savingsBaselineStationName
self.journeyDiagnosticsForStation = journeyDiagnosticsForStation self.journeyDiagnosticsForStation = journeyDiagnosticsForStation
self.onToggleFavourite = onToggleFavourite self.onToggleFavourite = onToggleFavourite
self.onReorder = onReorder self.onReorder = onReorder
@@ -147,12 +144,9 @@ struct FavouritesView: View {
if fuelSavingsSettings.isConfigured { if fuelSavingsSettings.isConfigured {
Section { Section {
FuelSavingsAdjustmentView( FuelSavingsAdjustmentView(amount: $fuelSavingsAmount)
amount: $fuelSavingsAmount,
referencePricePencePerLitre: cheapestPrice
)
} footer: { } footer: {
Text(String(localized: "Savings below are estimated against the nearest station with a price for this fuel — the same baseline as the Stations list.", comment: "Favourites fuel-savings explanation")) Text(String(localized: "Savings below are estimated against the closest station by journey distance — the same baseline as the Stations list.", comment: "Favourites fuel-savings explanation"))
} }
} }
@@ -167,10 +161,8 @@ struct FavouritesView: View {
baselinePrice: cheapestPrice, baselinePrice: cheapestPrice,
isTopResult: station.id == cheapest?.id, isTopResult: station.id == cheapest?.id,
isFavourite: activeFuelFavouriteIDs.contains(station.id), isFavourite: activeFuelFavouriteIDs.contains(station.id),
topBadgeText: "CHEAPEST",
tapAction: stationTapAction, tapAction: stationTapAction,
fuelSavings: savingsForStation(station), fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount,
onToggleFavourite: { onToggleFavourite(station, activeFuel) }, onToggleFavourite: { onToggleFavourite(station, activeFuel) },
onShowDetails: { detailStation = $0 } onShowDetails: { detailStation = $0 }
) )
@@ -219,9 +211,9 @@ struct FavouritesView: View {
station: station, station: station,
location: location, location: location,
distanceUnit: distanceUnit, distanceUnit: distanceUnit,
selectedFuel: activeFuel,
fuelSavings: savingsForStation(station), fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount, fuelSavingsAmount: fuelSavingsAmount,
savingsBaselineStationName: savingsBaselineStationName,
journeyDiagnostics: journeyDiagnosticsForStation(station), journeyDiagnostics: journeyDiagnosticsForStation(station),
// Every station listed here IS a favourite for the tab's // Every station listed here IS a favourite for the tab's
// fuel, so the star starts filled; tapping it unstars. // fuel, so the star starts filled; tapping it unstars.
+130 -28
View File
@@ -2,7 +2,8 @@ import SwiftUI
struct FuelSavingsAdjustmentView: View { struct FuelSavingsAdjustmentView: View {
@Binding var amount: FuelSavingsFillAmount @Binding var amount: FuelSavingsFillAmount
let referencePricePencePerLitre: Double?
@State private var unitChangeNotice: String?
private var range: ClosedRange<Double> { private var range: ClosedRange<Double> {
FuelSavingsCalculator.fillAmountSliderRange(for: amount.unit) FuelSavingsCalculator.fillAmountSliderRange(for: amount.unit)
@@ -44,6 +45,14 @@ struct FuelSavingsAdjustmentView: View {
Text("Changes the estimate for this session only — your Settings default stays unchanged.") Text("Changes the estimate for this session only — your Settings default stays unchanged.")
.font(.caption2) .font(.caption2)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
Text("£ compares the litres your budget buys at each station; Litres compares one fixed quantity.")
.font(.caption2)
.foregroundStyle(.secondary)
if let unitChangeNotice {
Text(unitChangeNotice)
.font(.caption2)
.foregroundStyle(.orange)
}
} }
} }
@@ -52,12 +61,10 @@ struct FuelSavingsAdjustmentView: View {
get: { amount.unit }, get: { amount.unit },
set: { newUnit in set: { newUnit in
guard newUnit != amount.unit else { return } guard newUnit != amount.unit else { return }
if let referencePricePencePerLitre, // No one litre figure equals a budget at every candidate price.
let converted = try? FuelSavingsCalculator.convert(amount: amount, to: newUnit, referencePricePencePerLitre: referencePricePencePerLitre) { // A unit change starts a new, explicitly labelled comparison.
amount = converted amount = FuelSavingsCalculator.newComparisonAmount(afterSwitching: amount, to: newUnit)
} else { unitChangeNotice = "New comparison basis — adjust the \(newUnit.displayName) amount to your intended fill-up."
amount = FuelSavingsFillAmount(value: newUnit == .pounds ? 40 : 30, unit: newUnit)
}
} }
) )
} }
@@ -73,11 +80,16 @@ struct FuelSavingsAdjustmentView: View {
struct FuelSavingsSummaryView: View { struct FuelSavingsSummaryView: View {
let availability: FuelSavingsAvailability? let availability: FuelSavingsAvailability?
let amount: FuelSavingsFillAmount let amount: FuelSavingsFillAmount
let baselineStationName: String? var baselineStationName: String? = nil
var compact: Bool = false var compact: Bool = false
/// Sizes the "extra return travel" caption in the user's own unit (the /// Sizes the "extra return travel" caption in the user's own unit (the
/// stored figure is miles) — used by both the row banner and the detail sheet. /// stored figure is miles) — used by both the row banner and the detail sheet.
var distanceUnit: DistanceUnit = .miles var distanceUnit: DistanceUnit = .miles
var showInfoAction: (() -> Void)? = nil
private func comparisonLabel(for result: FuelSavingsResult) -> String {
FuelSavingsFormat.comparisonLabel(status: result.status)
}
var body: some View { var body: some View {
switch availability { switch availability {
@@ -92,8 +104,19 @@ struct FuelSavingsSummaryView: View {
// break even, blue baseline. lineLimit + minimumScaleFactor keep // break even, blue baseline. lineLimit + minimumScaleFactor keep
// it to one line, so rows stay even. // it to one line, so rows stay even.
VStack(alignment: .leading, spacing: 2) { VStack(alignment: .leading, spacing: 2) {
// The capsule gets the WHOLE line and the comparison caption
// sits beneath it. Side by side, the caption's layoutPriority
// squeezed the verdict until it truncated ("Approx. £2.75
// better off after tra…"), and in this sort mode the verdict
// is the point of the row.
capsule(for: result, compact: true) capsule(for: result, compact: true)
.accessibilityLabel(accessibilityHeadline(for: result)) .accessibilityLabel(accessibilityHeadline(for: result))
Text(comparisonLabel(for: result))
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1)
.minimumScaleFactor(0.85)
.accessibilityLabel("Comparison: \(comparisonLabel(for: result))")
if let extraTravel = FuelSavingsFormat.extraTravelLabel( if let extraTravel = FuelSavingsFormat.extraTravelLabel(
extraDistanceMiles: result.extraDistanceMiles, extraDistanceMiles: result.extraDistanceMiles,
unit: distanceUnit, unit: distanceUnit,
@@ -117,8 +140,27 @@ struct FuelSavingsSummaryView: View {
// room for. The old shape led with a status word + headline that // room for. The old shape led with a status word + headline that
// matched neither the listing nor each other. // matched neither the listing nor each other.
VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) {
// Same shape as the listing rows: the capsule takes the line
// and the comparison caption sits directly beneath it, so the
// verdict never competes for width with its own caption.
VStack(alignment: .leading, spacing: 4) {
capsule(for: result, compact: false) capsule(for: result, compact: false)
.accessibilityLabel(accessibilityHeadline(for: result)) .accessibilityLabel(accessibilityHeadline(for: result))
Text(comparisonLabel(for: result))
.font(.subheadline)
.foregroundStyle(.secondary)
.lineLimit(1)
.minimumScaleFactor(0.85)
.accessibilityLabel("Comparison: \(comparisonLabel(for: result))")
}
LabeledContent("Your fill-up", value: amountText)
LabeledContent("Fuel you'll receive", value: String(format: "%.2f litres", result.fillLitres))
.monospacedDigit()
if amount.unit == .pounds {
Text("You pay the selected budget here. The saving compares the same litres at your closest station; litres differ between stations, and this is not a refund.")
.font(.caption2)
.foregroundStyle(.secondary)
}
if let extraTravel = FuelSavingsFormat.extraTravelLabel( if let extraTravel = FuelSavingsFormat.extraTravelLabel(
extraDistanceMiles: result.extraDistanceMiles, extraDistanceMiles: result.extraDistanceMiles,
unit: distanceUnit, unit: distanceUnit,
@@ -130,13 +172,30 @@ struct FuelSavingsSummaryView: View {
.accessibilityLabel(spokenExtraTravel(for: result, fallback: extraTravel)) .accessibilityLabel(spokenExtraTravel(for: result, fallback: extraTravel))
} }
if result.status == .baseline { if result.status == .baseline {
Text("Your closest station with a price for this fuel — every other saving is measured against it.") Text("Your closest station by journey distance is the baseline — every other saving is measured against it.")
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} else { } else {
Text("Compared with \(baselineStationName ?? "your nearest station") for \(amountText).").font(.caption).foregroundStyle(.secondary) Text(baselineStationName.map { "Compared with \($0)." } ?? "Compared with your closest station.")
LabeledContent("Fuel-price saving", value: FuelSavingsFormat.money(result.grossSavingGBP)) .font(.caption)
.foregroundStyle(.secondary)
LabeledContent(
result.grossSavingGBP >= 0 ? "Fuel-price saving" : "Fuel-price difference",
value: result.grossSavingGBP >= 0
? FuelSavingsFormat.money(result.grossSavingGBP)
: "Costs \(FuelSavingsFormat.money(abs(result.grossSavingGBP))) more"
)
LabeledContent("Extra driving cost", value: FuelSavingsFormat.money(result.extraDrivingCostGBP)) LabeledContent("Extra driving cost", value: FuelSavingsFormat.money(result.extraDrivingCostGBP))
Divider()
LabeledContent {
Text(result.headline())
.fontWeight(.semibold)
.foregroundStyle(capsuleColor(for: result.status))
.monospacedDigit()
} label: {
Text("Total")
.fontWeight(.semibold)
}
if result.journeyConfidence.isEstimated { if result.journeyConfidence.isEstimated {
Text("Estimated from straight-line or incomplete route data — refined once both routes are measured.") Text("Estimated from straight-line or incomplete route data — refined once both routes are measured.")
.font(.caption2) .font(.caption2)
@@ -146,6 +205,22 @@ struct FuelSavingsSummaryView: View {
.font(.caption2) .font(.caption2)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} }
if let showInfoAction {
Rectangle()
.fill(Color(.separator))
.frame(height: 0.5)
.padding(.vertical, 4)
Button(action: showInfoAction) {
HStack(spacing: 8) {
Text("How Best Value works")
Spacer(minLength: 8)
Image(systemName: "chevron.forward")
.font(.footnote.weight(.semibold))
.foregroundStyle(.tertiary)
}
}
.buttonStyle(.plain)
}
} }
} }
case .unavailable(let reason): case .unavailable(let reason):
@@ -176,39 +251,66 @@ struct FuelSavingsSummaryView: View {
} }
/// VoiceOver form of the verdict. `spokenHeadline()` spells "Approx." out for /// VoiceOver form of the verdict. `spokenHeadline()` spells "Approx." out for
/// estimated comparisons and leaves the plain words ("Break even", "Closest /// and leaves the plain words ("Break even", "Closest station") alone —
/// station") alone — one source, so visible and spoken copy cannot drift. /// one source, so visible and spoken copy cannot drift.
private func accessibilityHeadline(for result: FuelSavingsResult) -> String { private func accessibilityHeadline(for result: FuelSavingsResult) -> String {
result.spokenHeadline() result.spokenHeadline()
} }
/// The colour-coded verdict capsule — ONE implementation for the listing rows /// The colour-coded verdict capsule lives in `FuelSavingsCapsule` — ONE
/// and the detail sheet, so the verdict reads identically in both; the sheet /// implementation for the listing rows, the detail sheet and this compact
/// just gets the larger font and padding. /// summary, so the verdict reads identically everywhere; the sheet just
/// /// gets the larger font and padding.
/// An HStack with an explicit spacing, NOT a Label: given the width to spare,
/// a Label lays its icon and title out across the row and leaves a visible
/// gap between them (22pt in the listing row), which read as the text having
/// drifted away from its symbol. The icon is decorative here — the verdict
/// is in the text — so VoiceOver reads the capsule as one phrase.
private func capsule(for result: FuelSavingsResult, compact: Bool) -> some View { private func capsule(for result: FuelSavingsResult, compact: Bool) -> some View {
FuelSavingsCapsule(result: result, compact: compact)
}
/// Verdict colour lives in `FuelSavingsCapsule.color(for:)`.
private func capsuleColor(for status: FuelSavingsStatus) -> Color {
FuelSavingsCapsule.color(for: status)
}
private func symbol(for status: FuelSavingsStatus) -> String {
FuelSavingsCapsule.symbol(for: status)
}
}
/// The colour-coded verdict capsule shared by the station listing rows, the
/// detail sheet and the compact summary.
///
/// An HStack with an explicit spacing, NOT a Label: given the width to spare,
/// a Label lays its icon and title out across the row and leaves a visible gap
/// between them (22pt in the listing row), which read as the text having
/// drifted away from its symbol. The icon is decorative here — the verdict is
/// in the text — so VoiceOver reads the capsule as one phrase.
struct FuelSavingsCapsule: View {
let result: FuelSavingsResult
var compact: Bool = true
var body: some View {
HStack(spacing: compact ? 3 : 5) { HStack(spacing: compact ? 3 : 5) {
Image(systemName: symbol(for: result.status)) Image(systemName: Self.symbol(for: result.status))
.accessibilityHidden(true) .accessibilityHidden(true)
Text(result.capsuleHeadline()) Text(result.capsuleHeadline())
.lineLimit(1) .lineLimit(1)
.minimumScaleFactor(0.8) // Measured on a 393pt screen: the capsule is handed ~101pt, of
// which the icon, its spacing and the 8pt padding either side
// take 32pt, leaving ~69pt for the text. "Closest station" needs
// ~90pt at full size, so a 0.8 floor — 72pt — could not reach it
// and the row showed "Closest stati…" instead. 0.7 leaves ~63pt,
// which clears it at ~10pt type: scaled, never truncated.
.minimumScaleFactor(0.7)
} }
.font(compact ? .caption.weight(.semibold) : .headline) .font(compact ? .caption.weight(.semibold) : .headline)
.foregroundStyle(capsuleColor(for: result.status)) .foregroundStyle(Self.color(for: result.status))
.padding(.horizontal, compact ? 8 : 12) .padding(.horizontal, compact ? 8 : 12)
.padding(.vertical, compact ? 4 : 7) .padding(.vertical, compact ? 4 : 7)
.background(Capsule().fill(capsuleColor(for: result.status).opacity(0.15))) .background(Capsule().fill(Self.color(for: result.status).opacity(0.15)))
} }
/// Verdict colour: green save, red worse off, grey break even, blue /// Verdict colour: green save, red worse off, grey break even, blue
/// baseline — the same green/amber/red family the price dot already uses. /// baseline — the same green/amber/red family the price dot already uses.
private func capsuleColor(for status: FuelSavingsStatus) -> Color { static func color(for status: FuelSavingsStatus) -> Color {
switch status { switch status {
case .worthTheDrive: return .green case .worthTheDrive: return .green
case .notWorthTheDrive: return .red case .notWorthTheDrive: return .red
@@ -217,7 +319,7 @@ struct FuelSavingsSummaryView: View {
} }
} }
private func symbol(for status: FuelSavingsStatus) -> String { static func symbol(for status: FuelSavingsStatus) -> String {
switch status { switch status {
case .worthTheDrive: return "checkmark.circle.fill" case .worthTheDrive: return "checkmark.circle.fill"
case .breakEven: return "equal.circle.fill" case .breakEven: return "equal.circle.fill"
+71
View File
@@ -0,0 +1,71 @@
import SwiftUI
/// The "How Best Value works" explanation as its own sheet.
///
/// It used to sit inline in the Key sheet as a `Section`; it is one shared view
/// now so the Key sheet and the More info sheet can both open it, and the copy is
/// unchanged (the same `Localizable.strings` keys are reused — the old section
/// header string is the sheet's title).
struct HowBestValueSheet: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationStack {
List {
Section {
VStack(alignment: .leading, spacing: 10) {
Text("Best Value compares each station with the closest station by journey distance. It works out what you could save at the pump, then takes off the fuel used for the extra return journey.")
Text("Your fill-up amount and MPG are used to show whether you could save overall.")
Text("With a £ budget you spend that amount at each station; the litres differ by station. Savings compare those litres with the same quantity at your closest station, then deduct extra journey fuel. You do not receive cash back.")
Text("With Litres, every station is compared for the fixed quantity you selected.")
Text("Results are marked “Approx.” until road distances are available.")
.foregroundStyle(.secondary)
}
.font(.subheadline)
.padding(.vertical, 4)
}
}
.navigationTitle("How Best Value works")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { dismiss() }
}
}
}
.presentationDetents([.fraction(0.42)])
.presentationBackground(Color(UIColor.systemGroupedBackground))
}
}
/// The row that opens `HowBestValueSheet`. A tappable row with a chevron, like
/// the other rows in both sheets. `.buttonStyle(.plain)` keeps it from becoming a
/// row-wide tap target that could swallow a neighbouring control (see the
/// two-buttons-in-one-row rule).
struct HowBestValueRow: View {
let action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 8) {
Text("How Best Value works")
Spacer(minLength: 8)
Image(systemName: "chevron.forward")
.font(.footnote.weight(.semibold))
.foregroundStyle(.tertiary)
}
}
.buttonStyle(.plain)
}
}
#if DEBUG
/// QA hook support: `-showBestValueInfo` opens this sheet without a tap, so it can
/// be screenshotted (simctl has no tap command) — the same pattern as
/// `-showKeySheet` / `-showDetail`.
enum BestValueInfoQA {
static var isRequested: Bool {
ProcessInfo.processInfo.arguments.contains("-showBestValueInfo")
}
}
#endif
+1 -1
View File
@@ -79,7 +79,7 @@ enum LiveActivityManager {
currentStartDate = nil currentStartDate = nil
start(attributes: attributes, state: state) start(attributes: attributes, state: state)
} else { } else {
Task { await current.update(using: state) } Task { await current.update(ActivityContent(state: state, staleDate: nil)) }
} }
} else { } else {
start(attributes: attributes, state: state) start(attributes: attributes, state: state)
+25 -14
View File
@@ -98,7 +98,7 @@ struct OnboardingView: View {
private var welcomePage: some View { private var welcomePage: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
Spacer() Spacer()
AnimatedOnboardingIcon(tint: .accentColor) { AnimatedOnboardingIcon(tint: .accentColor, showsHalo: false) {
// The app icon itself, with the standard iOS rounded-corner // The app icon itself, with the standard iOS rounded-corner
// treatment (~22% of the size), so onboarding matches the // treatment (~22% of the size), so onboarding matches the
// Home Screen. // Home Screen.
@@ -108,9 +108,9 @@ struct OnboardingView: View {
.frame(width: 96, height: 96) .frame(width: 96, height: 96)
.clipShape(RoundedRectangle(cornerRadius: 21, style: .continuous)) .clipShape(RoundedRectangle(cornerRadius: 21, style: .continuous))
} }
.padding(.bottom, 28) .padding(.bottom, 16)
Text(String(localized: "Welcome to FuelBoard", comment: "Onboarding welcome title")) Text(String(localized: "Welcome to\nFuelBoard", comment: "Onboarding welcome title"))
.font(.largeTitle.bold()) .font(.largeTitle.bold())
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
@@ -121,12 +121,13 @@ struct OnboardingView: View {
.padding(.horizontal, 32) .padding(.horizontal, 32)
.padding(.top, 12) .padding(.top, 12)
featureRow(icon: "globe.europe.africa.fill", text: String(localized: "UK-wide prices — 8,000+ stations, updated twice a day", comment: "Onboarding feature row")) featureRow(icon: "map.fill", title: String(localized: "Compare fuel prices near you", comment: "Onboarding feature row title"), subtitle: String(localized: "Over 8,000 stations across Great Britain, with prices updated daily.", comment: "Onboarding feature row subtitle"))
featureRow(icon: "scope", text: String(localized: "Cheapest within your chosen radius, or closest station first", comment: "Onboarding feature row"))
featureRow(icon: "star.fill", text: String(localized: "Favourites with instant price comparison", comment: "Onboarding feature row")) featureRow(icon: "chart.line.uptrend.xyaxis", title: String(localized: "See how much you could save", comment: "Onboarding feature row title"), subtitle: String(localized: "Compare fill-up costs and potential savings at different stations.", comment: "Onboarding feature row subtitle"))
featureRow(icon: "chart.bar.fill", text: String(localized: "Green/amber/red rating vs the best nearby price", comment: "Onboarding feature row"))
featureRow(icon: "square.grid.2x2.fill", text: String(localized: "Home-screen widget showing the cheapest nearby", comment: "Onboarding feature row")) featureRow(icon: "car.fill", title: String(localized: "Know if it's worth the drive", comment: "Onboarding feature row title"), subtitle: String(localized: "Factor in your journey and fuel costs to find the best value.", comment: "Onboarding feature row subtitle"))
featureRow(icon: "bell.fill", text: String(localized: "Alerts when you approach the cheapest station", comment: "Onboarding feature row"))
featureRow(icon: "star.fill", title: String(localized: "Keep your favourites close", comment: "Onboarding feature row title"), subtitle: String(localized: "Save stations and quickly compare their latest prices.", comment: "Onboarding feature row subtitle"))
Spacer() Spacer()
} }
@@ -155,7 +156,7 @@ struct OnboardingView: View {
permissionStatusLabel( permissionStatusLabel(
granted: prompter.locationGranted, granted: prompter.locationGranted,
denied: prompter.locationDenied, denied: prompter.locationDenied,
deniedText: String(localized: "Location was denied. You can still browse all stations, but \"nearest\" sorting needs it.", comment: "Onboarding location denied text") deniedText: String(localized: "Location was denied. You can still browse all stations, but \"closest\" sorting needs it.", comment: "Onboarding location denied text")
) )
.padding(.top, 24) .padding(.top, 24)
@@ -298,18 +299,23 @@ struct OnboardingView: View {
OnboardingPrimaryButton(title: title, action: action) OnboardingPrimaryButton(title: title, action: action)
} }
private func featureRow(icon: String, text: String) -> some View { private func featureRow(icon: String, title: String, subtitle: String) -> some View {
HStack(spacing: 12) { HStack(alignment: .top, spacing: 12) {
Image(systemName: icon) Image(systemName: icon)
.font(.system(size: 20, weight: .semibold)) .font(.system(size: 20, weight: .semibold))
.foregroundStyle(Color.accentColor) .foregroundStyle(Color.accentColor)
.frame(width: 32) .frame(width: 32)
Text(text) VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.subheadline.bold())
Text(subtitle)
.font(.subheadline) .font(.subheadline)
.foregroundStyle(.secondary)
}
Spacer(minLength: 0) Spacer(minLength: 0)
} }
.padding(.horizontal, 36) .padding(.horizontal, 36)
.padding(.vertical, 10) .padding(.vertical, 8)
} }
private func permissionStatusLabel(granted: Bool, denied: Bool, deniedText: String) -> some View { private func permissionStatusLabel(granted: Bool, denied: Bool, deniedText: String) -> some View {
@@ -393,6 +399,9 @@ struct AnimatedOnboardingIcon<Content: View>: View {
let tint: Color let tint: Color
var motion: Motion = .gentle var motion: Motion = .gentle
/// The soft circle behind the glyph. The welcome page turns it off: it shows
/// the app icon itself and reads better with no container around it.
var showsHalo: Bool = true
@ViewBuilder var content: Content @ViewBuilder var content: Content
@State private var settled = false @State private var settled = false
@@ -402,6 +411,7 @@ struct AnimatedOnboardingIcon<Content: View>: View {
var body: some View { var body: some View {
ZStack { ZStack {
if showsHalo {
Circle() Circle()
.fill(tint.opacity(0.10)) .fill(tint.opacity(0.10))
.frame(width: 108, height: 108) .frame(width: 108, height: 108)
@@ -412,6 +422,7 @@ struct AnimatedOnboardingIcon<Content: View>: View {
.frame(width: 118, height: 118) .frame(width: 118, height: 118)
.scaleEffect(settled ? 1.03 : 0.97) .scaleEffect(settled ? 1.03 : 0.97)
.opacity(settled ? 1.0 : 0.55) .opacity(settled ? 1.0 : 0.55)
}
content content
.scaleEffect(iconScale) .scaleEffect(iconScale)
+2 -2
View File
@@ -618,7 +618,7 @@ final class ProximityMonitor: NSObject, ObservableObject, @preconcurrency CLLoca
let content = UNMutableNotificationContent() let content = UNMutableNotificationContent()
content.sound = .default content.sound = .default
content.title = "Best Value \(fuel.displayName) nearby: \(brand)" content.title = "Best Value \(fuel.displayName) nearby: \(brand)"
content.body = "\(station.name) could leave you \(result.headline()). Tap for directions." content.body = "\(station.name): \(result.headline()). Tap for directions."
addAlertRequest(content: content, station: station) addAlertRequest(content: content, station: station)
logAlert(.fired, "Best Value alert scheduled — \(brand) · \(result.headline())") logAlert(.fired, "Best Value alert scheduled — \(brand) · \(result.headline())")
lastAlert = "Best Value · \(brand) · \(result.headline())" lastAlert = "Best Value · \(brand) · \(result.headline())"
@@ -923,7 +923,7 @@ final class ProximityMonitor: NSObject, ObservableObject, @preconcurrency CLLoca
content.sound = .default content.sound = .default
let brand = candidate.station.brand.isEmpty ? candidate.station.name : candidate.station.brand let brand = candidate.station.brand.isEmpty ? candidate.station.name : candidate.station.brand
content.title = "Best Value \(fuel.displayName) nearby: \(brand)" content.title = "Best Value \(fuel.displayName) nearby: \(brand)"
content.body = "\(candidate.station.name) could leave you \(candidate.result.headline()). Tap for directions." content.body = "\(candidate.station.name): \(candidate.result.headline()). Tap for directions."
let baseResult = "Best Value · \(brand) · \(candidate.result.headline()) · radius \(unit.format(radiusKM))" let baseResult = "Best Value · \(brand) · \(candidate.result.headline()) · radius \(unit.format(radiusKM))"
lastTestResult = baseResult lastTestResult = baseResult
logAlert(.fired, "Best Value test alert scheduled — \(brand) · \(candidate.result.headline())") logAlert(.fired, "Best Value test alert scheduled — \(brand) · \(candidate.result.headline())")
+9 -2
View File
@@ -13,6 +13,7 @@
// every row at once; the mode must also be ON for any pass to run at all. // every row at once; the mode must also be ON for any pass to run at all.
import Foundation import Foundation
import CoreLocation
import MapKit import MapKit
import UIKit import UIKit
import WidgetKit import WidgetKit
@@ -407,8 +408,14 @@ enum RoadDistanceService {
/// Driving distance (metres) between two coordinates via Apple Maps routing. /// Driving distance (metres) between two coordinates via Apple Maps routing.
private static func roadMeters(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) async -> Double? { private static func roadMeters(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) async -> Double? {
let request = MKDirections.Request() let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: from)) request.source = MKMapItem(
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: to)) location: CLLocation(latitude: from.latitude, longitude: from.longitude),
address: nil
)
request.destination = MKMapItem(
location: CLLocation(latitude: to.latitude, longitude: to.longitude),
address: nil
)
request.transportType = .automobile request.transportType = .automobile
request.requestsAlternateRoutes = false request.requestsAlternateRoutes = false
do { do {
+31 -5
View File
@@ -20,6 +20,12 @@ struct SettingsView: View {
@Binding var priceDisplayStyle: PriceDisplayStyle @Binding var priceDisplayStyle: PriceDisplayStyle
@Binding var stationTapAction: StationTapAction @Binding var stationTapAction: StationTapAction
@Binding var fuelSavingsSettings: FuelSavingsSettings @Binding var fuelSavingsSettings: FuelSavingsSettings
/// The Best Value gate — the net saving that makes a station worth the trip.
/// Edited here, with the fill size and MPG that PRODUCE that saving, rather
/// than in the Alerts tab: the same figure also decides which station rows
/// carry the BEST VALUE badge, so it is a fuel-savings setting first and an
/// alert setting second. Stored under the alerts key either way.
@Binding var bestValueThresholdGBP: Double
@Binding var dataRefreshMode: DataRefreshMode @Binding var dataRefreshMode: DataRefreshMode
/// The fuel + radius currently configured for alerts (mirrors the Alerts /// The fuel + radius currently configured for alerts (mirrors the Alerts
/// tab) so the test notification matches what real alerts will say. /// tab) so the test notification matches what real alerts will say.
@@ -79,6 +85,7 @@ struct SettingsView: View {
/// Return key, so the keyboard's Done button clears this to dismiss AND /// Return key, so the keyboard's Done button clears this to dismiss AND
/// commit the typed value. Both Fuel Savings controls are sliders now, so /// commit the typed value. Both Fuel Savings controls are sliders now, so
/// nothing sets it — it stays for any numeric field this screen takes again. /// nothing sets it — it stays for any numeric field this screen takes again.
@State private var settingsUnitChangeNotice: String?
@FocusState private var focusedSavingsField: SavingsField? @FocusState private var focusedSavingsField: SavingsField?
private enum SavingsField: Hashable { private enum SavingsField: Hashable {
@@ -148,6 +155,25 @@ struct SettingsView: View {
step: FuelSavingsCalculator.fillAmountSliderStep(for: fuelSavingsSettings.preferredAmount.unit)) step: FuelSavingsCalculator.fillAmountSliderStep(for: fuelSavingsSettings.preferredAmount.unit))
.accessibilityLabel("Typical fill-up") .accessibilityLabel("Typical fill-up")
.accessibilityValue(fillUpText) .accessibilityValue(fillUpText)
Picker("Minimum saving", selection: $bestValueThresholdGBP) {
ForEach(FuelStore.bestValueAlertThresholdOptionsGBP, id: \.self) { value in
Text(FuelSavingsFormat.money(value)).tag(value)
}
}
// Persisted by ContentView's single
// `.onChange(of: alertsBestValueThresholdGBP)`, which
// also refreshes the alert monitor — so this picker
// needs no handler of its own. The store snaps to the
// nearest option, so the picker and the stored value
// cannot disagree.
Text("A saving worth driving for: the net saving left after the extra travel cost. Stations above it are labelled BEST VALUE in the station list, and Best Value alerts use the same figure.")
.font(.caption)
.foregroundStyle(.secondary)
if let settingsUnitChangeNotice {
Text(settingsUnitChangeNotice)
.font(.caption2)
.foregroundStyle(.orange)
}
if !fuelSavingsSettings.isConfigured && fuelSavingsSettings.enabled { if !fuelSavingsSettings.isConfigured && fuelSavingsSettings.enabled {
Text("Set a realistic UK MPG and fill-up amount before Best Value appears in sorting.") Text("Set a realistic UK MPG and fill-up amount before Best Value appears in sorting.")
.font(.caption) .font(.caption)
@@ -285,7 +311,7 @@ struct SettingsView: View {
} header: { } header: {
Text("Debug") Text("Debug")
} footer: { } footer: {
Text("The first button applies the real criteria — cheapest \(alertsFuel.displayName.lowercased()) station within \(distanceUnit.format(alertsRadiusKM)) of you — and sends the actual station's name, price and coordinates. The second fires with no criteria at all (nearest seller), still carrying a real station, just to verify a notification appears and tapping it opens directions. Cheapest in range mirrors the app list (selected fuel + distance); the in-range count mirrors the alert radius.") Text("The first button applies the real criteria — cheapest \(alertsFuel.displayName.lowercased()) station within \(distanceUnit.format(alertsRadiusKM)) of you — and sends the actual station's name, price and coordinates. The second fires with no criteria at all (closest seller), still carrying a real station, just to verify a notification appears and tapping it opens directions. Cheapest in range mirrors the app list (selected fuel + distance); the in-range count mirrors the alert radius.")
} }
.onAppear { onRefreshDebugStatus() } .onAppear { onRefreshDebugStatus() }
@@ -709,10 +735,10 @@ struct SettingsView: View {
Binding( Binding(
get: { fuelSavingsSettings.preferredAmount.unit }, get: { fuelSavingsSettings.preferredAmount.unit },
set: { newUnit in set: { newUnit in
fuelSavingsSettings.preferredAmount.unit = newUnit guard newUnit != fuelSavingsSettings.preferredAmount.unit else { return }
if !fuelSavingsSettings.preferredAmount.isValid { fuelSavingsSettings.preferredAmount = FuelSavingsCalculator.newComparisonAmount(
fuelSavingsSettings.preferredAmount.value = newUnit == .pounds ? 40 : 30 afterSwitching: fuelSavingsSettings.preferredAmount, to: newUnit)
} settingsUnitChangeNotice = "New comparison basis — adjust the \(newUnit.displayName) amount to your intended fill-up."
persistFuelSavingsSettings() persistFuelSavingsSettings()
} }
) )
+29 -6
View File
@@ -17,6 +17,8 @@ struct StationDetailView: View {
let station: FuelStation let station: FuelStation
let location: Coordinate? let location: Coordinate?
let distanceUnit: DistanceUnit let distanceUnit: DistanceUnit
/// Fuel whose price is being shown by the surrounding station list.
var selectedFuel: FuelType = FuelStore.loadSelectedFuel()
var fuelSavings: FuelSavingsAvailability? = nil var fuelSavings: FuelSavingsAvailability? = nil
var fuelSavingsAmount: FuelSavingsFillAmount = FuelSavingsSettings.defaultPreferredAmount var fuelSavingsAmount: FuelSavingsFillAmount = FuelSavingsSettings.defaultPreferredAmount
var savingsBaselineStationName: String? = nil var savingsBaselineStationName: String? = nil
@@ -29,10 +31,13 @@ struct StationDetailView: View {
var onToggleFavourite: (() -> Void)? = nil var onToggleFavourite: (() -> Void)? = nil
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
@State private var showingReportIssueConfirmation = false @State private var showingReportIssueConfirmation = false
/// Transient "Copied" confirmation on the Address row. Cleared by a task so /// Transient "Postcode copied" confirmation on the Address row. Cleared by a task so
/// the caption fades out on its own. /// the caption fades out on its own.
@State private var showingCopied = false @State private var showingCopied = false
@State private var copyResetTask: Task<Void, Never>? @State private var copyResetTask: Task<Void, Never>?
/// The "How Best Value works" sheet, opened from the row at the bottom of the
/// Best Value card (the Key sheet opens the same shared view).
@State private var showBestValueInfo = false
private let reportIssueURL = URL(string: "https://www.gov.uk/guidance/report-an-error-in-fuel-prices-or-forecourt-details")! private let reportIssueURL = URL(string: "https://www.gov.uk/guidance/report-an-error-in-fuel-prices-or-forecourt-details")!
@@ -54,6 +59,18 @@ struct StationDetailView: View {
station.postcode.trimmingCharacters(in: .whitespacesAndNewlines) station.postcode.trimmingCharacters(in: .whitespacesAndNewlines)
} }
private var priceFreshness: FuelPriceFreshness.Assessment {
FuelPriceFreshness.assessment(for: station)
}
/// The selected grade's current price, when present. Kept separate from
/// the price-age row so an old price remains visible rather than being
/// silently hidden.
private var selectedFuelPriceText: String {
guard let price = station.prices[selectedFuel] else { return "—" }
return FuelStore.priceText(price, style: .stationSign)
}
/// Opens Apple Maps driving directions — the same destination (and the same /// Opens Apple Maps driving directions — the same destination (and the same
/// URL) the Directions button below uses, so the map and the button can /// URL) the Directions button below uses, so the map and the button can
/// never point at two different places. /// never point at two different places.
@@ -134,7 +151,7 @@ struct StationDetailView: View {
// The whole row is a copy control: it puts JUST the postcode // The whole row is a copy control: it puts JUST the postcode
// on the clipboard so it can be pasted into another // on the clipboard so it can be pasted into another
// navigation app. The copy glyph sits ON the address line, // navigation app. The copy glyph sits ON the address line,
// and the "Copied" confirmation is a capsule that floats OVER // and the "Postcode copied" confirmation is a capsule that floats OVER
// THIS ROW — it confirms the address, so it must not hover // THIS ROW — it confirms the address, so it must not hover
// over the map. It is an overlay, so nothing moves while it is // over the map. It is an overlay, so nothing moves while it is
// up, and `allowsHitTesting(false)` keeps the row tappable // up, and `allowsHitTesting(false)` keeps the row tappable
@@ -169,7 +186,7 @@ struct StationDetailView: View {
if showingCopied { if showingCopied {
HStack(spacing: 4) { HStack(spacing: 4) {
Image(systemName: "checkmark") Image(systemName: "checkmark")
Text("Copied") Text("Postcode copied")
} }
.font(.footnote.weight(.semibold)) .font(.footnote.weight(.semibold))
.foregroundStyle(.green) .foregroundStyle(.green)
@@ -194,6 +211,9 @@ struct StationDetailView: View {
LabeledContent("Distance", value: distance.labelWithReturn(unit: distanceUnit)) LabeledContent("Distance", value: distance.labelWithReturn(unit: distanceUnit))
.monospacedDigit() .monospacedDigit()
} }
LabeledContent("\(selectedFuel.displayName) price", value: selectedFuelPriceText)
.monospacedDigit()
StationPriceAgeView(assessment: priceFreshness)
ForEach(StationNotice.notices(for: station)) { notice in ForEach(StationNotice.notices(for: station)) { notice in
Label(notice.title, systemImage: notice.symbolName) Label(notice.title, systemImage: notice.symbolName)
.font(.subheadline.weight(.semibold)) .font(.subheadline.weight(.semibold))
@@ -235,7 +255,8 @@ struct StationDetailView: View {
availability: fuelSavings, availability: fuelSavings,
amount: fuelSavingsAmount, amount: fuelSavingsAmount,
baselineStationName: savingsBaselineStationName, baselineStationName: savingsBaselineStationName,
distanceUnit: distanceUnit distanceUnit: distanceUnit,
showInfoAction: { showBestValueInfo = true }
) )
} header: { } header: {
Text("Best Value") Text("Best Value")
@@ -265,6 +286,8 @@ struct StationDetailView: View {
} message: { } message: {
Text("Are you sure you want to report an error in fuel prices or forecourt details? This will open in your chosen browser.") Text("Are you sure you want to report an error in fuel prices or forecourt details? This will open in your chosen browser.")
} }
// Nested sheet: the More info sheet stays put behind the explanation.
.sheet(isPresented: $showBestValueInfo) { HowBestValueSheet() }
.toolbar { .toolbar {
ToolbarItem(placement: .cancellationAction) { ToolbarItem(placement: .cancellationAction) {
Button("Done") { dismiss() } Button("Done") { dismiss() }
@@ -284,12 +307,12 @@ struct StationDetailView: View {
) )
} }
} }
// The "Copied" fade-out task must not outlive the sheet. // The "Postcode copied" fade-out task must not outlive the sheet.
.onDisappear { copyResetTask?.cancel() } .onDisappear { copyResetTask?.cancel() }
#if DEBUG #if DEBUG
// QA hook: `-qaCopyPostcode` runs the REAL copy on open, so the // QA hook: `-qaCopyPostcode` runs the REAL copy on open, so the
// clipboard value (read back with `xcrun simctl pbpaste`) and the // clipboard value (read back with `xcrun simctl pbpaste`) and the
// "Copied" confirmation can be verified without a tap — simctl // "Postcode copied" confirmation can be verified without a tap — simctl
// cannot drive taps into the Simulator. // cannot drive taps into the Simulator.
.task { .task {
guard ProcessInfo.processInfo.arguments.contains("-qaCopyPostcode") else { return } guard ProcessInfo.processInfo.arguments.contains("-qaCopyPostcode") else { return }
+31
View File
@@ -0,0 +1,31 @@
import SwiftUI
/// The More info sheet's price-age row.
///
/// Station-level by design: the relay publishes a single `price_updated` per
/// station (the newest grade it maps), so the copy says "Price updated" and
/// never claims the selected grade itself was updated.
///
/// Past `FuelPriceFreshness.outdatedAge` a discreet note flags the information
/// as possibly out of date. It is informational only — it gates nothing, and
/// the station's own price row above it is unaffected.
///
/// Its own view rather than inlined into `StationDetailView`: that body sits at
/// the compiler's type-checking limit, so one extra statement there fails the
/// build. One statement here, one there.
struct StationPriceAgeView: View {
let assessment: FuelPriceFreshness.Assessment
var body: some View {
VStack(alignment: .leading, spacing: 2) {
LabeledContent("Price updated", value: assessment.updateAgeLabel)
.monospacedDigit()
if let notice = assessment.outdatedNotice {
Text(notice)
.font(.caption2)
.foregroundStyle(.secondary)
.accessibilityLabel(notice)
}
}
}
}
+77 -39
View File
@@ -19,7 +19,6 @@ struct StationsView: View {
let fuelSavingsSettings: FuelSavingsSettings let fuelSavingsSettings: FuelSavingsSettings
@Binding var fuelSavingsAmount: FuelSavingsFillAmount @Binding var fuelSavingsAmount: FuelSavingsFillAmount
var savingsForStation: (FuelStation) -> FuelSavingsAvailability? = { _ in nil } var savingsForStation: (FuelStation) -> FuelSavingsAvailability? = { _ in nil }
var savingsBaselineStationName: String?
var journeyDiagnosticsForStation: (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil } var journeyDiagnosticsForStation: (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil }
var onToggleFavourite: (FuelStation, FuelType) -> Void = { _, _ in } var onToggleFavourite: (FuelStation, FuelType) -> Void = { _, _ in }
var onRefresh: () async -> Void = {} var onRefresh: () async -> Void = {}
@@ -35,6 +34,11 @@ struct StationsView: View {
/// info button in the header — keeps the list focused on stations. /// info button in the header — keeps the list focused on stations.
@State private var showKey = false @State private var showKey = false
/// The "How Best Value works" sheet. The explanation used to be a section in
/// the Key sheet; it is its own sheet now, opened from a row at the bottom of
/// the Key sheet and from the More info sheet.
@State private var showBestValueInfo = false
/// Station picked for the More-info sheet (tap action = showDetails). /// Station picked for the More-info sheet (tap action = showDetails).
@State private var detailStation: FuelStation? @State private var detailStation: FuelStation?
@@ -63,7 +67,7 @@ struct StationsView: View {
} }
if location != nil { if location != nil {
if sortMode == .closest { if sortMode == .closest {
return "\(mode) \(fuel) stations — nearest first, best value within \(miles) \(unit) · \(ratio) stations updated" return "\(mode) \(fuel) stations — closest first, lowest price within \(miles) \(unit) · \(ratio) stations updated"
} }
return "\(mode) \(fuel) within \(miles) \(unit) — \(ratio) stations updated · \(tapHint)" return "\(mode) \(fuel) within \(miles) \(unit) — \(ratio) stations updated · \(tapHint)"
} }
@@ -89,7 +93,7 @@ struct StationsView: View {
} }
.pickerStyle(.segmented) .pickerStyle(.segmented)
// In Closest mode the whole country is the pool — the // In Closest mode the whole country is the pool — the
// radius is meaningless ("nearest" must never return an // radius is meaningless ("closest" must never return an
// empty state), so the picker is disabled but its value is // empty state), so the picker is disabled but its value is
// kept for when the user switches back to Cheapest. // kept for when the user switches back to Cheapest.
.disabled(sortMode == .closest) .disabled(sortMode == .closest)
@@ -116,10 +120,7 @@ struct StationsView: View {
// stale stored sort mode must not keep the control on screen // stale stored sort mode must not keep the control on screen
// for a switched-off feature. // for a switched-off feature.
if sortMode == .worthTheDrive && fuelSavingsSettings.isConfigured { if sortMode == .worthTheDrive && fuelSavingsSettings.isConfigured {
FuelSavingsAdjustmentView( FuelSavingsAdjustmentView(amount: $fuelSavingsAmount)
amount: $fuelSavingsAmount,
referencePricePencePerLitre: baselinePrice
)
} }
if isLoading && stations.isEmpty { if isLoading && stations.isEmpty {
@@ -144,22 +145,7 @@ struct StationsView: View {
.padding(.vertical, 4) .padding(.vertical, 4)
} else { } else {
ForEach(Array(stations.prefix(visibleCount)), id: \.id) { station in ForEach(Array(stations.prefix(visibleCount)), id: \.id) { station in
StationRow( stationRow(station)
station: station,
fuel: selectedFuel,
location: location,
distanceUnit: distanceUnit,
priceDisplayStyle: priceDisplayStyle,
baselinePrice: baselinePrice,
isTopResult: station.id == topStationID,
isFavourite: favouriteIDs.contains(station.id),
topBadgeText: sortMode == .worthTheDrive ? "CHEAPEST" : "TOP",
tapAction: stationTapAction,
fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount,
onToggleFavourite: { onToggleFavourite(station, selectedFuel) },
onShowDetails: { detailStation = $0 }
)
} }
if visibleCount < stations.count { if visibleCount < stations.count {
@@ -218,6 +204,18 @@ struct StationsView: View {
if ProcessInfo.processInfo.arguments.contains("-showKeySheet") { if ProcessInfo.processInfo.arguments.contains("-showKeySheet") {
showKey = true showKey = true
} }
// QA hook: `-showBestValueInfo` opens the Key sheet and then the
// explanation on top of it, so the copy can be screenshotted
// without a tap. It has to chain: the explanation's `.sheet` lives
// inside the Key sheet's content, so it cannot present while the
// Key sheet is shut.
if BestValueInfoQA.isRequested {
showKey = true
Task { @MainActor in
try? await Task.sleep(nanoseconds: 1_200_000_000)
showBestValueInfo = true
}
}
#endif #endif
} }
.task(id: stations.count) { .task(id: stations.count) {
@@ -243,21 +241,44 @@ struct StationsView: View {
} }
} }
.sheet(isPresented: $showKey) { .sheet(isPresented: $showKey) {
keySheet
}
.sheet(item: $detailStation) { station in
detailSheet(for: station)
}
}
}
private func detailSheet(for station: FuelStation) -> some View {
StationDetailView(
station: station,
location: location,
distanceUnit: distanceUnit,
selectedFuel: selectedFuel,
fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount,
journeyDiagnostics: journeyDiagnosticsForStation(station),
isFavourite: favouriteIDs.contains(station.id),
onToggleFavourite: { onToggleFavourite(station, selectedFuel) }
)
}
private var keySheet: some View {
NavigationStack { NavigationStack {
List { List {
Section { Section {
VStack(spacing: 10) { VStack(spacing: 10) {
keyCard( keyCard(
icon: "checkmark.circle.fill", color: .green, icon: "checkmark.circle.fill", color: .green,
title: "Best value", blurb: "Within 1.5p of the cheapest", title: "Good price", blurb: "Within 1.5p of the cheapest",
threshold: "≤1.5p") threshold: "0–1.5p")
keyCard( keyCard(
icon: "equal.circle.fill", color: .orange, icon: "equal.circle.fill", color: .orange,
title: "Okay", blurb: "Within 4p of the cheapest", title: "Okay", blurb: "More than 1.5p, up to 4p above the cheapest",
threshold: "≤4p") threshold: ">1.5–4p")
keyCard( keyCard(
icon: "exclamationmark.circle.fill", color: .red, icon: "exclamationmark.circle.fill", color: .red,
title: "Pricey", blurb: "More than 4p over the cheapest", title: "Pricey", blurb: "More than 4p above the cheapest",
threshold: ">4p") threshold: ">4p")
Rectangle() Rectangle()
.fill(Color(.separator)) .fill(Color(.separator))
@@ -289,15 +310,27 @@ struct StationsView: View {
.padding(.horizontal, 14) .padding(.horizontal, 14)
.padding(.vertical, 12) .padding(.vertical, 12)
.keyCardFill(color: .yellow) .keyCardFill(color: .yellow)
Text("Colours match each station's rating on the list") Text("Price differences are shown in pence per litre (p/litre). Colours match each station's rating on the list.")
.font(.footnote) .font(.footnote)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity, alignment: .center)
.multilineTextAlignment(.center)
.padding(.top, 4) .padding(.top, 4)
} }
.listRowBackground(Color.clear) .listRowBackground(Color.clear)
.listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16)) .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
} }
// The explanation is its own sheet now, opened from this
// row. Gated exactly like the More info row and the Best
// Value card itself: `isConfigured` is the same condition
// `savingsForStation` uses, so the row appears and
// disappears with the feature.
if fuelSavingsSettings.isConfigured {
Section {
HowBestValueRow { showBestValueInfo = true }
}
}
} }
.navigationTitle("Key") .navigationTitle("Key")
.navigationBarTitleDisplayMode(.inline) .navigationBarTitleDisplayMode(.inline)
@@ -306,25 +339,29 @@ struct StationsView: View {
Button("Done") { showKey = false } Button("Done") { showKey = false }
} }
} }
// Nested sheet: the Key sheet stays behind the explanation.
.sheet(isPresented: $showBestValueInfo) { HowBestValueSheet() }
} }
.presentationDetents([.fraction(0.6)]) .presentationDetents([.fraction(0.6)])
.presentationBackground(Color(UIColor.systemGroupedBackground)) .presentationBackground(Color(UIColor.systemGroupedBackground))
} }
.sheet(item: $detailStation) { station in
StationDetailView( private func stationRow(_ station: FuelStation) -> some View {
StationRow(
station: station, station: station,
fuel: selectedFuel,
location: location, location: location,
distanceUnit: distanceUnit, distanceUnit: distanceUnit,
fuelSavings: savingsForStation(station), priceDisplayStyle: priceDisplayStyle,
fuelSavingsAmount: fuelSavingsAmount, baselinePrice: baselinePrice,
savingsBaselineStationName: savingsBaselineStationName, isTopResult: station.id == topStationID,
journeyDiagnostics: journeyDiagnosticsForStation(station),
isFavourite: favouriteIDs.contains(station.id), isFavourite: favouriteIDs.contains(station.id),
onToggleFavourite: { onToggleFavourite(station, selectedFuel) } tapAction: stationTapAction,
fuelSavings: savingsForStation(station),
onToggleFavourite: { onToggleFavourite(station, selectedFuel) },
onShowDetails: { detailStation = $0 }
) )
} }
}
}
private var availableSortModes: [SortMode] { private var availableSortModes: [SortMode] {
var modes: [SortMode] = [.closest, .cheapest] var modes: [SortMode] = [.closest, .cheapest]
@@ -347,6 +384,7 @@ struct StationsView: View {
Text(LocalizedStringKey(blurb)) Text(LocalizedStringKey(blurb))
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
} }
Spacer(minLength: 8) Spacer(minLength: 8)
HStack(spacing: 6) { HStack(spacing: 6) {
+3 -2
View File
@@ -76,7 +76,7 @@ struct WidgetMockScreen: View {
let location = FuelStore.loadLocation().map { Coordinate(lat: $0.lat, lng: $0.lng) } let location = FuelStore.loadLocation().map { Coordinate(lat: $0.lat, lng: $0.lng) }
// 5 miles — the widget config's default Distance. WidgetDistance itself // 5 miles — the widget config's default Distance. WidgetDistance itself
// lives in the widget target, so the preview mirrors its default here. // lives in the widget target, so the preview mirrors its default here.
let radiusKM = 5 * 1.60934 let radiusKM = 5 * FuelSavingsCalculator.kilometresPerMile
let all = FuelStore.loadStations() let all = FuelStore.loadStations()
let selling = all.filter { station in let selling = all.filter { station in
guard station.prices[fuel] != nil else { return false } guard station.prices[fuel] != nil else { return false }
@@ -94,7 +94,8 @@ struct WidgetMockScreen: View {
isFavourites: false, isFavourites: false,
location: location, location: location,
locationSource: location != nil ? "live" : "none", locationSource: location != nil ? "live" : "none",
unit: FuelStore.loadDistanceUnit() unit: FuelStore.loadDistanceUnit(),
bestValueResult: nil
) )
} }
} }
+31 -9
View File
@@ -10,9 +10,11 @@
"Settings" = "Settings"; "Settings" = "Settings";
"FuelBoard" = "FuelBoard"; "FuelBoard" = "FuelBoard";
"TOP" = "TOP"; "TOP" = "TOP";
"BEST VALUE" = "BEST VALUE";
"CHEAPEST" = "CHEAPEST";
/* Stations tab */ /* Stations tab */
"Closest %@ stations — nearest first, best value within %lld %@ · %lld stations" = "Closest %@ stations — nearest first, best value within %lld %@ · %lld stations"; "Closest %@ stations — closest first, lowest price within %lld %@ · %lld stations" = "Closest %@ stations — closest first, lowest price within %lld %@ · %lld stations";
"Cheapest %@ within %lld %@ — %lld stations · tap a station for directions." = "Cheapest %@ within %lld %@ — %lld stations · tap a station for directions."; "Cheapest %@ within %lld %@ — %lld stations · tap a station for directions." = "Cheapest %@ within %lld %@ — %lld stations · tap a station for directions.";
"%@ %@ — tap a station for directions." = "%@ %@ — tap a station for directions."; "%@ %@ — tap a station for directions." = "%@ %@ — tap a station for directions.";
"Fuel type" = "Fuel type"; "Fuel type" = "Fuel type";
@@ -23,18 +25,25 @@
"Show %lld more (%lld remaining)" = "Show %lld more (%lld remaining)"; "Show %lld more (%lld remaining)" = "Show %lld more (%lld remaining)";
"All %lld stations shown" = "All %lld stations shown"; "All %lld stations shown" = "All %lld stations shown";
"Key" = "Key"; "Key" = "Key";
"Best value" = "Best value"; "Good price" = "Good price";
"Within 1.5p of the cheapest" = "Within 1.5p of the cheapest"; "Within 1.5p of the cheapest" = "Within 1.5p of the cheapest";
"Okay" = "Okay"; "Okay" = "Okay";
"Within 4p of the cheapest" = "Within 4p of the cheapest"; "More than 1.5p, up to 4p above the cheapest" = "More than 1.5p, up to 4p above the cheapest";
"Pricey" = "Pricey"; "Pricey" = "Pricey";
"More than 4p over the cheapest" = "More than 4p over the cheapest"; "More than 4p above the cheapest" = "More than 4p above the cheapest";
"Top result for the current sort" = "Top result for the current sort"; "Top result for the current sort" = "Top result for the current sort";
"Star a station to add it to Favourites" = "Star a station to add it to Favourites"; "Star a station to add it to Favourites" = "Star a station to add it to Favourites";
/* Star button in the More info sheet heading (accessibility labels) */ /* Star button in the More info sheet heading (accessibility labels) */
"Add to favourites" = "Add to favourites"; "Add to favourites" = "Add to favourites";
"Remove from favourites" = "Remove from favourites"; "Remove from favourites" = "Remove from favourites";
"Colours match each station's rating on the list" = "Colours match each station's rating on the list"; "Price differences are shown in pence per litre (p/litre). Colours match each station's rating on the list." = "Price differences are shown in pence per litre (p/litre). Colours match each station's rating on the list.";
"How Best Value works" = "How Best Value works";
"Best Value compares each station with the closest station by journey distance. It works out what you could save at the pump, then takes off the fuel used for the extra return journey." = "Best Value compares each station with the closest station by journey distance. It works out what you could save at the pump, then takes off the fuel used for the extra return journey.";
"With a £ budget you spend that amount at each station; the litres differ by station. Savings compare those litres with the same quantity at your closest station, then deduct extra journey fuel. You do not receive cash back." = "With a £ budget you spend that amount at each station; the litres differ by station. Savings compare those litres with the same quantity at your closest station, then deduct extra journey fuel. You do not receive cash back.";
"Your closest station by journey distance is the baseline — every other saving is measured against it." = "Your closest station by journey distance is the baseline — every other saving is measured against it.";
"Savings below are estimated against the closest station by journey distance — the same baseline as the Stations list." = "Savings below are estimated against the closest station by journey distance — the same baseline as the Stations list.";
"Your fill-up amount and MPG are used to show whether you could save overall." = "Your fill-up amount and MPG are used to show whether you could save overall.";
"Results are marked “Approx.” until road distances are available." = "Results are marked “Approx.” until road distances are available.";
/* Favourites tab */ /* Favourites tab */
"No favourites yet" = "No favourites yet"; "No favourites yet" = "No favourites yet";
@@ -66,9 +75,8 @@
"More info" = "More info"; "More info" = "More info";
"Name" = "Name"; "Name" = "Name";
"Address" = "Address"; "Address" = "Address";
"Distance" = "Distance";
"Copied" = "Copied";
"Copies the postcode" = "Copies the postcode"; "Copies the postcode" = "Copies the postcode";
"Postcode copied" = "Postcode copied";
"Address: %@" = "Address: %@"; "Address: %@" = "Address: %@";
"Directions to %@" = "Directions to %@"; "Directions to %@" = "Directions to %@";
"Opens Apple Maps with driving directions" = "Opens Apple Maps with driving directions"; "Opens Apple Maps with driving directions" = "Opens Apple Maps with driving directions";
@@ -77,7 +85,7 @@
"Test alert notification (real data)" = "Test alert notification (real data)"; "Test alert notification (real data)" = "Test alert notification (real data)";
"Send plain test notification" = "Send plain test notification"; "Send plain test notification" = "Send plain test notification";
"Debug" = "Debug"; "Debug" = "Debug";
"The first button applies the real criteria — cheapest %@ station within %@ of you — and sends the actual station's name, price and coordinates. The second fires with no criteria at all (nearest seller), still carrying a real station, just to verify a notification appears and tapping it opens directions. Cheapest in range mirrors the app list (selected fuel + distance); the in-range count mirrors the alert radius." = "The first button applies the real criteria — cheapest %@ station within %@ of you — and sends the actual station's name, price and coordinates. The second fires with no criteria at all (nearest seller), still carrying a real station, just to verify a notification appears and tapping it opens directions. Cheapest in range mirrors the app list (selected fuel + distance); the in-range count mirrors the alert radius."; "The first button applies the real criteria — cheapest %@ station within %@ of you — and sends the actual station's name, price and coordinates. The second fires with no criteria at all (closest seller), still carrying a real station, just to verify a notification appears and tapping it opens directions. Cheapest in range mirrors the app list (selected fuel + distance); the in-range count mirrors the alert radius." = "The first button applies the real criteria — cheapest %@ station within %@ of you — and sends the actual station's name, price and coordinates. The second fires with no criteria at all (closest seller), still carrying a real station, just to verify a notification appears and tapping it opens directions. Cheapest in range mirrors the app list (selected fuel + distance); the in-range count mirrors the alert radius.";
"Widget Diagnostics" = "Widget Diagnostics"; "Widget Diagnostics" = "Widget Diagnostics";
"Each beacon is written by the widget extension at the end of every timeline entry for that intent type (keychain, so it survives free-SideStore installs). A missing SMALL beacon after adding the small widget means its timeline never reaches the provider. Installed widgets come from WidgetCenter." = "Each beacon is written by the widget extension at the end of every timeline entry for that intent type (keychain, so it survives free-SideStore installs). A missing SMALL beacon after adding the small widget means its timeline never reaches the provider. Installed widgets come from WidgetCenter."; "Each beacon is written by the widget extension at the end of every timeline entry for that intent type (keychain, so it survives free-SideStore installs). A missing SMALL beacon after adding the small widget means its timeline never reaches the provider. Installed widgets come from WidgetCenter." = "Each beacon is written by the widget extension at the end of every timeline entry for that intent type (keychain, so it survives free-SideStore installs). A missing SMALL beacon after adding the small widget means its timeline never reaches the provider. Installed widgets come from WidgetCenter.";
"SMALL: %@" = "SMALL: %@"; "SMALL: %@" = "SMALL: %@";
@@ -135,7 +143,7 @@
"Connection shows the source of the current prices (CSV mirror or API). Data updated is the latest price change reported by the GOV.UK server itself. Prices use the UK Fuel Finder dataset (Open Government Licence) and refresh up to twice a day." = "Connection shows the source of the current prices (CSV mirror or API). Data updated is the latest price change reported by the GOV.UK server itself. Prices use the UK Fuel Finder dataset (Open Government Licence) and refresh up to twice a day."; "Connection shows the source of the current prices (CSV mirror or API). Data updated is the latest price change reported by the GOV.UK server itself. Prices use the UK Fuel Finder dataset (Open Government Licence) and refresh up to twice a day." = "Connection shows the source of the current prices (CSV mirror or API). Data updated is the latest price change reported by the GOV.UK server itself. Prices use the UK Fuel Finder dataset (Open Government Licence) and refresh up to twice a day.";
"Prices near you" = "Prices near you"; "Prices near you" = "Prices near you";
"FuelBoard uses your location to show prices around you and rank stations by distance. Your position never leaves the device." = "FuelBoard uses your location to show prices around you and rank stations by distance. Your position never leaves the device."; "FuelBoard uses your location to show prices around you and rank stations by distance. Your position never leaves the device." = "FuelBoard uses your location to show prices around you and rank stations by distance. Your position never leaves the device.";
"Location was denied. You can still browse all stations, but \"nearest\" sorting needs it." = "Location was denied. You can still browse all stations, but \"nearest\" sorting needs it."; "Location was denied. You can still browse all stations, but \"closest\" sorting needs it." = "Location was denied. You can still browse all stations, but \"closest\" sorting needs it.";
"Allowed" = "Allowed"; "Allowed" = "Allowed";
"The system prompt will appear next." = "The system prompt will appear next."; "The system prompt will appear next." = "The system prompt will appear next.";
"FuelBoard can notify you when you're approaching the cheapest station in your alert radius — even with the app closed. You can switch this off in the Alerts tab." = "FuelBoard can notify you when you're approaching the cheapest station in your alert radius — even with the app closed. You can switch this off in the Alerts tab."; "FuelBoard can notify you when you're approaching the cheapest station in your alert radius — even with the app closed. You can switch this off in the Alerts tab." = "FuelBoard can notify you when you're approaching the cheapest station in your alert radius — even with the app closed. You can switch this off in the Alerts tab.";
@@ -199,7 +207,9 @@
"Cheapest station" = "Cheapest station"; "Cheapest station" = "Cheapest station";
"Alert type" = "Alert type"; "Alert type" = "Alert type";
"Best Value" = "Best Value"; "Best Value" = "Best Value";
"Total" = "Total";
"Minimum saving" = "Minimum saving"; "Minimum saving" = "Minimum saving";
"Minimum saving %@ — change in Settings, Fuel Savings." = "Minimum saving %@ — change in Settings, Fuel Savings.";
"Set up Best Value first so FuelBoard can account for your fill size, MPG and travel cost." = "Set up Best Value first so FuelBoard can account for your fill size, MPG and travel cost."; "Set up Best Value first so FuelBoard can account for your fill size, MPG and travel cost." = "Set up Best Value first so FuelBoard can account for your fill size, MPG and travel cost.";
"Set up Best Value first so Best Value alerts can account for your fill size, MPG and travel cost." = "Set up Best Value first so Best Value alerts can account for your fill size, MPG and travel cost."; "Set up Best Value first so Best Value alerts can account for your fill size, MPG and travel cost." = "Set up Best Value first so Best Value alerts can account for your fill size, MPG and travel cost.";
"When you approach the Best Value station within the radius, FuelBoard sends a notification if it could leave you at least %@ better off after extra return travel. Nearby stations selling %@ are watched — favourites get priority — and each station alerts at most once per hour." = "When you approach the Best Value station within the radius, FuelBoard sends a notification if it could leave you at least %@ better off after extra return travel. Nearby stations selling %@ are watched — favourites get priority — and each station alerts at most once per hour."; "When you approach the Best Value station within the radius, FuelBoard sends a notification if it could leave you at least %@ better off after extra return travel. Nearby stations selling %@ are watched — favourites get priority — and each station alerts at most once per hour." = "When you approach the Best Value station within the radius, FuelBoard sends a notification if it could leave you at least %@ better off after extra return travel. Nearby stations selling %@ are watched — favourites get priority — and each station alerts at most once per hour.";
@@ -212,3 +222,15 @@
"A-roads and motorway exits. Wide early warning for longer trips — but in town it rarely fires, because you're usually already inside the circle." = "A-roads and motorway exits. Wide early warning for longer trips — but in town it rarely fires, because you're usually already inside the circle."; "A-roads and motorway exits. Wide early warning for longer trips — but in town it rarely fires, because you're usually already inside the circle." = "A-roads and motorway exits. Wide early warning for longer trips — but in town it rarely fires, because you're usually already inside the circle.";
"Long-distance journeys. Maximum reach: a ping when a cheap station is coming up from far out. In town this essentially never fires." = "Long-distance journeys. Maximum reach: a ping when a cheap station is coming up from far out. In town this essentially never fires."; "Long-distance journeys. Maximum reach: a ping when a cheap station is coming up from far out. In town this essentially never fires." = "Long-distance journeys. Maximum reach: a ping when a cheap station is coming up from far out. In town this essentially never fires.";
"%@ — %@" = "%@ — %@"; "%@ — %@" = "%@ — %@";
/* Best Value calculation and station price age */
"£ compares the litres your budget buys at each station; Litres compares one fixed quantity." = "£ compares the litres your budget buys at each station; Litres compares one fixed quantity.";
"You pay the selected budget here. The saving compares the same litres at your closest station; litres differ between stations, and this is not a refund." = "You pay the selected budget here. The saving compares the same litres at your closest station; litres differ between stations, and this is not a refund.";
"Best Value unavailable · location needed" = "Best Value unavailable · location needed";
"your order" = "your order";
"Price updated" = "Price updated";
"%@ ago" = "%@ ago";
"Not provided" = "Not provided";
"May be outdated" = "May be outdated";
"Fuel you'll receive" = "Fuel you'll receive";
"Compared with your closest station." = "Compared with your closest station.";
@@ -0,0 +1 @@
../../../Shared/FuelPriceFreshness.swift
@@ -211,10 +211,10 @@ final class DistanceTests: XCTestCase {
} }
func testMilesConversion() { func testMilesConversion() {
// 5 miles ≈ 8.05 km (app uses × 1.60934) // 5 miles ≈ 8.05 km using the shared exact conversion
XCTAssertEqual(5 * 1.60934, 8.0467, accuracy: 0.001) XCTAssertEqual(5 * FuelSavingsCalculator.kilometresPerMile, 8.04672, accuracy: 0.001)
// 262 km ≈ 162.8 miles (display uses × 0.621371) // 262 km ≈ 162.8 miles using the shared exact conversion
XCTAssertEqual(262 * 0.621371, 162.8, accuracy: 0.1) XCTAssertEqual(262 / FuelSavingsCalculator.kilometresPerMile, 162.8, accuracy: 0.1)
} }
} }
@@ -267,14 +267,14 @@ final class FuelTypeLabelTests: XCTestCase {
} }
func testDistanceUnitConversion() { func testDistanceUnitConversion() {
XCTAssertEqual(DistanceUnit.miles.toKM(1), 1.60934, accuracy: 0.00001) XCTAssertEqual(DistanceUnit.miles.toKM(1), 1.609344, accuracy: 0.00001)
XCTAssertEqual(DistanceUnit.kilometers.toKM(5), 5) XCTAssertEqual(DistanceUnit.kilometers.toKM(5), 5)
XCTAssertEqual(DistanceUnit.miles.fromKM(1.60934), 1, accuracy: 0.00001) XCTAssertEqual(DistanceUnit.miles.fromKM(1.609344), 1, accuracy: 0.00001)
XCTAssertEqual(DistanceUnit.kilometers.fromKM(2.5), 2.5) XCTAssertEqual(DistanceUnit.kilometers.fromKM(2.5), 2.5)
} }
func testDistanceUnitFormat() { func testDistanceUnitFormat() {
XCTAssertEqual(DistanceUnit.miles.format(1.60934), "1.0 mi") XCTAssertEqual(DistanceUnit.miles.format(1.609344), "1.0 mi")
XCTAssertEqual(DistanceUnit.kilometers.format(3.4), "3.4 km") XCTAssertEqual(DistanceUnit.kilometers.format(3.4), "3.4 km")
} }
} }
@@ -400,7 +400,7 @@ final class AlertRadiusFollowTests: XCTestCase {
FuelStore.saveDistanceUnit(.miles) FuelStore.saveDistanceUnit(.miles)
FuelStore.saveStationLimit(5) FuelStore.saveStationLimit(5)
let eff = FuelStore.effectiveAlertsRadiusKM(followsSearch: true, manualKM: 3) let eff = FuelStore.effectiveAlertsRadiusKM(followsSearch: true, manualKM: 3)
XCTAssertEqual(eff, 5 * 1.60934, accuracy: 0.001) XCTAssertEqual(eff, 5 * FuelSavingsCalculator.kilometresPerMile, accuracy: 0.001)
} }
} }
@@ -731,7 +731,7 @@ final class RoadDistanceCacheTests: XCTestCase {
sourceLat: sourceLat, sourceLng: sourceLng, sourceLat: sourceLat, sourceLng: sourceLng,
entries: ["far": .init(meters: 23_500, lat: 51.5074, lng: -0.1278, returnMeters: 23_500)]) entries: ["far": .init(meters: 23_500, lat: 51.5074, lng: -0.1278, returnMeters: 23_500)])
let tenMilesKM = 10 * 1.60934 let tenMilesKM = 10 * FuelSavingsCalculator.kilometresPerMile
XCTAssertLessThan(far.distanceKM(to: sourceLat, lng2: sourceLng), tenMilesKM, XCTAssertLessThan(far.distanceKM(to: sourceLat, lng2: sourceLng), tenMilesKM,
"fixture: the straight line must sit INSIDE the 10-mile radius") "fixture: the straight line must sit INSIDE the 10-mile radius")
XCTAssertGreaterThan(FuelStore.displayDistanceKM(station: far, userLat: sourceLat, userLng: sourceLng), XCTAssertGreaterThan(FuelStore.displayDistanceKM(station: far, userLat: sourceLat, userLng: sourceLng),
@@ -743,7 +743,7 @@ final class RoadDistanceCacheTests: XCTestCase {
userLat: sourceLat, userLng: sourceLng), userLat: sourceLat, userLng: sourceLng),
"a station whose row reads 14.6 mi must not appear in a 10-mile list") "a station whose row reads 14.6 mi must not appear in a 10-mile list")
// The same station is back once the radius actually covers its distance. // The same station is back once the radius actually covers its distance.
XCTAssertTrue(FuelStore.isWithinDisplayRadius(station: far, radiusKM: 15 * 1.60934, XCTAssertTrue(FuelStore.isWithinDisplayRadius(station: far, radiusKM: 15 * FuelSavingsCalculator.kilometresPerMile,
userLat: sourceLat, userLng: sourceLng)) userLat: sourceLat, userLng: sourceLng))
// …and an unknown station (no cached route) still tests its displayed // …and an unknown station (no cached route) still tests its displayed
// straight line, so nothing changes for the bulk of the list. // straight line, so nothing changes for the bulk of the list.
@@ -783,10 +783,10 @@ final class RoadDistanceCacheTests: XCTestCase {
XCTAssertFalse(confirmed.isApproximate, "a cached road distance is not an approximation") XCTAssertFalse(confirmed.isApproximate, "a cached road distance is not an approximation")
XCTAssertEqual(confirmed.km, 3.2, accuracy: 0.0001) XCTAssertEqual(confirmed.km, 3.2, accuracy: 0.0001)
XCTAssertEqual(confirmed.label(unit: .miles), "2.0 mi") XCTAssertEqual(confirmed.label(unit: .miles), "2.0 mi")
XCTAssertEqual(confirmed.labelWithReturn(unit: .miles), "2.0 mi (4.0 mi return)") XCTAssertEqual(confirmed.labelWithReturn(unit: .miles), "2.0 mi (4.2 mi return)")
XCTAssertEqual(confirmed.labelWithReturn(unit: .kilometers), "3.2 km (6.4 km return)") XCTAssertEqual(confirmed.labelWithReturn(unit: .kilometers), "3.2 km (6.8 km return)")
XCTAssertEqual(confirmed.spokenLabel(unit: .miles), "2.0 miles") XCTAssertEqual(confirmed.spokenLabel(unit: .miles), "2.0 miles")
XCTAssertEqual(confirmed.spokenLabelWithReturn(unit: .miles), "2.0 miles, 4.0 miles return") XCTAssertEqual(confirmed.spokenLabelWithReturn(unit: .miles), "2.0 miles, 4.2 miles return")
let approximate = FuelStore.stationDistanceDisplay(station: unrouted, userLat: 51.6, userLng: -0.1) let approximate = FuelStore.stationDistanceDisplay(station: unrouted, userLat: 51.6, userLng: -0.1)
XCTAssertTrue(approximate.isApproximate, "the straight-line fallback must be identified as one") XCTAssertTrue(approximate.isApproximate, "the straight-line fallback must be identified as one")
@@ -794,11 +794,40 @@ final class RoadDistanceCacheTests: XCTestCase {
XCTAssertEqual(approximate.label(unit: .miles), XCTAssertEqual(approximate.label(unit: .miles),
"Approx. " + DistanceUnit.miles.format(approximate.km)) "Approx. " + DistanceUnit.miles.format(approximate.km))
XCTAssertEqual(approximate.labelWithReturn(unit: .miles), XCTAssertEqual(approximate.labelWithReturn(unit: .miles),
"Approx. \(DistanceUnit.miles.format(approximate.km)) (\(DistanceUnit.miles.format(approximate.km * 2)) return)") "Approx. " + DistanceUnit.miles.format(approximate.km) + " (Approx. " + DistanceUnit.miles.format(approximate.km * 2) + " return)")
XCTAssertEqual(approximate.spokenLabel(unit: .kilometers), XCTAssertEqual(approximate.spokenLabel(unit: .kilometers),
"Approximately " + DistanceUnit.kilometers.spoken(approximate.km)) "Approximately " + DistanceUnit.kilometers.spoken(approximate.km))
XCTAssertEqual(approximate.spokenLabelWithReturn(unit: .kilometers), XCTAssertEqual(approximate.spokenLabelWithReturn(unit: .kilometers),
"Approximately \(DistanceUnit.kilometers.spoken(approximate.km)), \(DistanceUnit.kilometers.spoken(approximate.km * 2)) return") "Approximately \(DistanceUnit.kilometers.spoken(approximate.km)), Approximately \(DistanceUnit.kilometers.spoken(approximate.km * 2)) return")
}
func testDisplayedReturnUsesTheIndependentlyMeasuredReturnRoute() {
FuelStore.setAccurateDistancesEnabled(true)
let station = station("separate-legs", 51.5074, -0.1278)
FuelStore.saveRoadDistances(
sourceLat: 51.6,
sourceLng: -0.1,
entries: ["separate-legs": .init(
meters: 4_650,
lat: station.lat,
lng: station.lng,
returnMeters: 4_820
)],
complete: true
)
let display = FuelStore.stationDistanceDisplay(
station: station,
userLat: 51.6,
userLng: -0.1
)
XCTAssertEqual(display.km, 4.65, accuracy: 1e-12)
XCTAssertEqual(display.returnKM, 9.47, accuracy: 1e-12)
XCTAssertFalse(display.isApproximate)
XCTAssertFalse(display.returnIsApproximate)
XCTAssertEqual(display.labelWithReturn(unit: .miles), "2.9 mi (5.9 mi return)")
XCTAssertEqual(display.spokenLabelWithReturn(unit: .miles), "2.9 miles, 5.9 miles return")
} }
/// The marker tracks the cache on its own: same station, bare figure once its /// The marker tracks the cache on its own: same station, bare figure once its
@@ -961,7 +990,7 @@ final class RoadDistanceCacheTests: XCTestCase {
let display = FuelStore.stationDistanceDisplay(station: routed, userLat: 51.6, userLng: -0.1) let display = FuelStore.stationDistanceDisplay(station: routed, userLat: 51.6, userLng: -0.1)
XCTAssertTrue(display.isApproximate, "the browse layer must never serve routes with the mode off") XCTAssertTrue(display.isApproximate, "the browse layer must never serve routes with the mode off")
XCTAssertEqual(display.km, routed.distanceKM(to: 51.6, lng2: -0.1), accuracy: 0.0001) XCTAssertEqual(display.km, routed.distanceKM(to: 51.6, lng2: -0.1), accuracy: 0.0001)
XCTAssertTrue(FuelStore.isWithinDisplayRadius(station: routed, radiusKM: 10 * 1.60934, XCTAssertTrue(FuelStore.isWithinDisplayRadius(station: routed, radiusKM: 10 * FuelSavingsCalculator.kilometresPerMile,
userLat: 51.6, userLng: -0.1), userLat: 51.6, userLng: -0.1),
"with the mode off the radius is a straight-line radius, agreeing with the rows") "with the mode off the radius is a straight-line radius, agreeing with the rows")
@@ -1000,7 +1029,7 @@ final class RoadDistanceCacheTests: XCTestCase {
let display = FuelStore.stationDistanceDisplay(station: routed, userLat: 51.6, userLng: -0.1) let display = FuelStore.stationDistanceDisplay(station: routed, userLat: 51.6, userLng: -0.1)
XCTAssertFalse(display.isApproximate) XCTAssertFalse(display.isApproximate)
XCTAssertEqual(display.km, 23.5, accuracy: 0.0001) XCTAssertEqual(display.km, 23.5, accuracy: 0.0001)
XCTAssertFalse(FuelStore.isWithinDisplayRadius(station: routed, radiusKM: 10 * 1.60934, XCTAssertFalse(FuelStore.isWithinDisplayRadius(station: routed, radiusKM: 10 * FuelSavingsCalculator.kilometresPerMile,
userLat: 51.6, userLng: -0.1), userLat: 51.6, userLng: -0.1),
"in this mode a 10-mile radius is 10 miles of driving, matching the routed rows") "in this mode a 10-mile radius is 10 miles of driving, matching the routed rows")
} }
@@ -0,0 +1,179 @@
import XCTest
#if SWIFT_PACKAGE
@testable import FuelBoardShared
#endif
/// Station-level price age — one timestamp per station, reported in More info
/// and nowhere else.
///
/// The relay's `price_updated` is the newest `price_last_updated` across every
/// grade a station maps, so it is not evidence about the selected grade. These
/// tests pin what the app *reports*; `StationPriceAgePolicyTests` pins what the
/// app does about it (nothing).
final class FuelPriceFreshnessTests: XCTestCase {
private let now = Date(timeIntervalSince1970: 1_800_000_000)
private func at(_ offset: TimeInterval) -> TimeInterval {
now.addingTimeInterval(offset).timeIntervalSince1970
}
private func station(priceUpdated: TimeInterval?) -> FuelStation {
FuelStation(id: "freshness-station", name: "Freshness Station", brand: "Test",
address: "1 High Street", postcode: "BD1 1AA", lat: 53.79, lng: -1.75,
prices: [.e10: 169.9], priceUpdated: priceUpdated)
}
// MARK: - One figure per station, whatever fuel is on screen
func testOneAgeIsReportedForEveryFuelAStationSells() {
let sold = FuelStation(id: "multi", name: "Multi", brand: "", address: "", postcode: "",
lat: 53, lng: -1, prices: [.e5: 165.9, .e10: 169.9, .diesel: 129.9],
priceUpdated: at(-28 * 60 * 60))
for fuel in FuelType.allCases {
XCTAssertEqual(FuelPriceFreshness.assessment(for: sold, now: now).updateAgeLabel,
"28h ago",
"\(fuel.rawValue): every grade reads the same station timestamp")
}
}
func testStationTimestampIsDecodedAndNoPerGradeTimestampIsInvented() throws {
let json = """
{
"stations": [{
"id": "s1",
"name": "LISTER ARMS",
"brand": "Shell",
"address": "MANCHESTER ROAD, BRADFORD",
"postcode": "BD5 7JX",
"lat": 53.78,
"lng": -1.75,
"prices": {"E10": 169.9, "DIESEL": 129.9},
"price_updated": "2026-10-14T07:45:52Z",
"price_updated_by_grade": {
"E10": "2026-01-01T00:00:00Z",
"DIESEL": "2026-01-01T00:00:00Z"
}
}]
}
"""
let decoded = try XCTUnwrap(try FuelPriceProvider.decodeStations(from: Data(json.utf8)).first)
XCTAssertEqual(decoded.priceUpdated,
ISO8601DateFormatter.fuelBoardDate("2026-10-14T07:45:52Z")?.timeIntervalSince1970,
"the station-level field is what the app records")
// A per-grade map in the payload is ignored: the app has one age, and it
// is the station's.
let assessment = FuelPriceFreshness.assessment(for: decoded, now: now)
XCTAssertEqual(assessment.status, .outdated,
"the station field is used, not the 2026-01-01 grade entries")
}
// MARK: - Reading the age
func testFreshAgeReadsInMinutesThenHours() {
XCTAssertEqual(FuelPriceFreshness.assessment(priceUpdated: at(-59 * 60), now: now).updateAgeLabel,
"59m ago")
XCTAssertEqual(FuelPriceFreshness.assessment(priceUpdated: at(-60 * 60), now: now).updateAgeLabel,
"1h ago")
XCTAssertEqual(FuelPriceFreshness.assessment(priceUpdated: at(-47 * 60 * 60), now: now).updateAgeLabel,
"47h ago")
XCTAssertEqual(FuelPriceFreshness.assessment(priceUpdated: at(-48 * 60 * 60), now: now).updateAgeLabel,
"2d ago")
}
func testFreshInformationIsNeverFlagged() {
let assessment = FuelPriceFreshness.assessment(for: station(priceUpdated: at(-28 * 60 * 60)), now: now)
XCTAssertEqual(assessment.status, .fresh)
XCTAssertFalse(assessment.isOutdated)
XCTAssertNil(assessment.outdatedNotice)
XCTAssertEqual(assessment.age, 28 * 60 * 60)
}
// MARK: - The thirty-day display threshold
func testInformationExactlyThirtyDaysOldIsNotYetFlagged() {
let assessment = FuelPriceFreshness.assessment(priceUpdated: at(-FuelPriceFreshness.outdatedAge), now: now)
XCTAssertEqual(assessment.status, .fresh)
XCTAssertNil(assessment.outdatedNotice)
}
func testInformationJustPastThirtyDaysIsFlaggedButStillReportsItsAge() {
let assessment = FuelPriceFreshness.assessment(priceUpdated: at(-FuelPriceFreshness.outdatedAge - 1), now: now)
XCTAssertEqual(assessment.status, .outdated)
XCTAssertTrue(assessment.isOutdated)
XCTAssertEqual(assessment.outdatedNotice, "May be outdated")
XCTAssertEqual(assessment.updateAgeLabel, "30d ago")
}
func testLongOldInformationIsFlaggedWithItsDayCount() {
// The oldest figure the mirror carries for a real station is ~250 days.
let assessment = FuelPriceFreshness.assessment(priceUpdated: at(-250 * 86_400), now: now)
XCTAssertEqual(assessment.status, .outdated)
XCTAssertEqual(assessment.updateAgeLabel, "250d ago")
XCTAssertEqual(assessment.outdatedNotice, "May be outdated")
}
// MARK: - Missing, malformed, future and absurd timestamps
func testMissingTimestampReadsNotProvidedAndIsNeverFlagged() {
let assessment = FuelPriceFreshness.assessment(for: station(priceUpdated: nil), now: now)
XCTAssertEqual(assessment.status, .unknown)
XCTAssertNil(assessment.age)
XCTAssertEqual(assessment.updateAgeLabel, "Not provided")
XCTAssertFalse(assessment.isOutdated)
XCTAssertNil(assessment.outdatedNotice)
}
func testUnparseableSourceTextIsDroppedRatherThanGuessed() throws {
XCTAssertNil(FuelPriceTimestamp.parse("not-a-date"))
XCTAssertNil(FuelPriceTimestamp.parse(""))
XCTAssertNil(FuelPriceTimestamp.parse(" "))
let json = """
{"stations": [{"id": "bad", "name": "Bad", "brand": "", "address": "", "postcode": "",
"lat": 53, "lng": -1, "prices": {"E10": 169.9}, "price_updated": "2026-99-99T99:99:99Z"}]}
"""
let decoded = try XCTUnwrap(try FuelPriceProvider.decodeStations(from: Data(json.utf8)).first)
XCTAssertNil(decoded.priceUpdated)
XCTAssertEqual(FuelPriceFreshness.assessment(for: decoded, now: now).updateAgeLabel, "Not provided")
}
func testSmallClockSkewReadsAsJustNowNotAsAFutureDate() {
let assessment = FuelPriceFreshness.assessment(priceUpdated: at(60), now: now)
XCTAssertEqual(assessment.status, .fresh)
XCTAssertEqual(assessment.age, 0)
XCTAssertEqual(assessment.updateAgeLabel, "0m ago")
}
func testTimestampBeyondTheSkewToleranceIsUnusableNotOptimistic() {
let assessment = FuelPriceFreshness.assessment(priceUpdated: at(86_400), now: now)
XCTAssertEqual(assessment.status, .invalid)
XCTAssertNil(assessment.age)
XCTAssertEqual(assessment.updateAgeLabel, "Not provided")
XCTAssertNil(assessment.outdatedNotice)
}
func testNonFiniteAndAbsurdEpochsAreUnusableAndCannotTrap() {
let values: [TimeInterval] = [.nan, .infinity, -.infinity,
.greatestFiniteMagnitude, -.greatestFiniteMagnitude]
for value in values {
let assessment = FuelPriceFreshness.assessment(priceUpdated: value, now: now)
XCTAssertEqual(assessment.status, .invalid, "\(value)")
XCTAssertNil(assessment.age, "\(value)")
XCTAssertEqual(assessment.updateAgeLabel, "Not provided", "\(value)")
XCTAssertFalse(assessment.isOutdated, "\(value)")
}
}
}
private extension ISO8601DateFormatter {
static func fuelBoardDate(_ string: String) -> Date? {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter.date(from: string) ?? {
formatter.formatOptions = [.withInternetDateTime]
return formatter.date(from: string)
}()
}
}
@@ -48,6 +48,42 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
// MARK: - 1. Unit conversion // MARK: - 1. Unit conversion
func testBudgetExamplesAcrossAllFuelTypes() throws {
for fuel in FuelType.allCases {
let base = FuelStation(id: "base", name: "Base", brand: "", address: "", postcode: "", lat: 53, lng: -1, prices: [fuel: 199.9], priceUpdated: nil)
let other = FuelStation(id: "other", name: "Other", brand: "", address: "", postcode: "", lat: 53, lng: -1, prices: [fuel: 129.9], priceUpdated: nil)
let settings = FuelSavingsSettings(enabled: true, mpg: 30, preferredAmount: .init(value: 40, unit: .pounds))
for budget in [20.0, 40, 60, 73, 100] {
let result = FuelSavingsEstimator.availability(station: other, fuel: fuel, baseline: base,
settings: settings, amount: .init(value: budget, unit: .pounds),
journey: .init(miles: 8.3, basis: .roadRoute),
baselineJourney: .init(miles: 0.9, basis: .roadRoute))?.result
let volume = budget / 1.299
XCTAssertEqual(result?.fillLitres ?? 0, volume, accuracy: 1e-9)
XCTAssertEqual(result?.grossSavingGBP ?? 0, volume * 0.7, accuracy: 1e-9)
XCTAssertEqual(result?.netSavingGBP ?? 0, volume * 0.7 - 7.4 / 30 * 4.54609 * 1.299, accuracy: 1e-9)
}
}
}
func testCandidateBudgetAndEqualQuantitySavingsForEveryFuel() throws {
for fuel in FuelType.allCases {
let candidate = FuelStation(id: "candidate-\(fuel.rawValue)", name: "Candidate", brand: "", address: "", postcode: "", lat: 53.7, lng: -1.8, prices: [fuel: 129.9], priceUpdated: nil)
let baseline = FuelStation(id: "baseline-\(fuel.rawValue)", name: "Nearest", brand: "", address: "", postcode: "", lat: 53.7, lng: -1.8, prices: [fuel: 199.9], priceUpdated: nil)
let configured = FuelSavingsSettings(enabled: true, mpg: 30, preferredAmount: .init(value: 60, unit: .pounds))
let money = FuelSavingsEstimator.availability(station: candidate, fuel: fuel, baseline: baseline, settings: configured,
amount: .init(value: 60, unit: .pounds), journey: .init(miles: 8.3, basis: .roadRoute),
baselineJourney: .init(miles: 0.9, basis: .roadRoute))?.result
let litres = FuelSavingsEstimator.availability(station: candidate, fuel: fuel, baseline: baseline, settings: configured,
amount: .init(value: 60 / 1.299, unit: .litres), journey: .init(miles: 8.3, basis: .roadRoute),
baselineJourney: .init(miles: 0.9, basis: .roadRoute))?.result
XCTAssertEqual(money?.fillLitres ?? 0, 60 / 1.299, accuracy: 1e-8, fuel.rawValue)
XCTAssertEqual(money?.grossSavingGBP ?? 0, litres?.grossSavingGBP ?? -1, accuracy: 1e-8, fuel.rawValue)
XCTAssertEqual(money?.netSavingGBP ?? 0, litres?.netSavingGBP ?? -1, accuracy: 1e-8, fuel.rawValue)
XCTAssertEqual(money?.netSavingGBP ?? 0, (money?.grossSavingGBP ?? 0) - (money?.extraDrivingCostGBP ?? 0), accuracy: 1e-8, fuel.rawValue)
}
}
func testImperialGallonIsUsedNotTheUSGallon() { func testImperialGallonIsUsedNotTheUSGallon() {
XCTAssertEqual(FuelSavingsCalculator.imperialGallonLitres, 4.54609) XCTAssertEqual(FuelSavingsCalculator.imperialGallonLitres, 4.54609)
XCTAssertNotEqual(FuelSavingsCalculator.imperialGallonLitres, 3.785411784, XCTAssertNotEqual(FuelSavingsCalculator.imperialGallonLitres, 3.785411784,
@@ -82,18 +118,84 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
XCTAssertEqual(FuelSavingsFormat.distance(1, unit: .miles), DistanceUnit.miles.format(1.609344)) XCTAssertEqual(FuelSavingsFormat.distance(1, unit: .miles), DistanceUnit.miles.format(1.609344))
} }
// MARK: - 2/4. The three stations from the brief // MARK: - 2. Candidate-priced fill-up
func testPoundsFillUsesCandidatePriceForLitresAndGrossSaving() throws {
let result = try FuelSavingsCalculator.calculate(
mpg: 30,
amount: FuelSavingsFillAmount(value: 60, unit: .pounds),
baselinePricePencePerLitre: 171.9,
candidatePricePencePerLitre: 169.9,
baselineJourneyMiles: 0.879,
candidateJourneyMiles: 8.306
)
XCTAssertEqual(result.fillLitres, 60 / 1.699, accuracy: 1e-9)
XCTAssertEqual(result.grossSavingGBP, (60 / 1.699) * 0.02, accuracy: 1e-9)
XCTAssertEqual(FuelSavingsFormat.money(result.grossSavingGBP), "£0.71")
XCTAssertEqual(result.extraFuelLitres, 1.1254603476666667, accuracy: 1e-9)
XCTAssertEqual(result.extraDrivingCostGBP, 1.9121571306856667, accuracy: 1e-9)
XCTAssertEqual(result.netSavingGBP, -1.2058593084372853, accuracy: 1e-9)
XCTAssertEqual(result.headline(), "Costs £1.21 more")
}
func testPoundsExamplesScaleFromThirtyToOneHundredPounds() throws {
for (budget, expectedLitres, expectedGross) in [
(30.0, 17.657445556209535, 0.3531489111241907),
(60.0, 35.31489111241907, 0.7062978222483814),
(100.0, 58.85815185403179, 1.1771630370806357)
] {
let result = try FuelSavingsCalculator.calculate(
mpg: 30,
amount: FuelSavingsFillAmount(value: budget, unit: .pounds),
baselinePricePencePerLitre: 171.9,
candidatePricePencePerLitre: 169.9,
baselineJourneyMiles: 0,
candidateJourneyMiles: 0
)
XCTAssertEqual(result.fillLitres, expectedLitres, accuracy: 1e-8)
XCTAssertEqual(result.grossSavingGBP, expectedGross, accuracy: 1e-8)
}
}
func testCandidatePriceControlsLitresWhileBaselinePriceOnlyChangesSaving() throws {
let amount = FuelSavingsFillAmount(value: 60, unit: .pounds)
let first = try FuelSavingsCalculator.calculate(
mpg: 30, amount: amount,
baselinePricePencePerLitre: 171.9,
candidatePricePencePerLitre: 169.9,
baselineJourneyMiles: 0, candidateJourneyMiles: 0
)
let differentBaseline = try FuelSavingsCalculator.calculate(
mpg: 30, amount: amount,
baselinePricePencePerLitre: 179.9,
candidatePricePencePerLitre: 169.9,
baselineJourneyMiles: 0, candidateJourneyMiles: 0
)
let differentCandidate = try FuelSavingsCalculator.calculate(
mpg: 30, amount: amount,
baselinePricePencePerLitre: 179.9,
candidatePricePencePerLitre: 159.9,
baselineJourneyMiles: 0, candidateJourneyMiles: 0
)
XCTAssertEqual(first.fillLitres, differentBaseline.fillLitres, accuracy: 1e-12)
XCTAssertNotEqual(first.grossSavingGBP, differentBaseline.grossSavingGBP)
XCTAssertNotEqual(differentBaseline.fillLitres, differentCandidate.fillLitres)
}
// MARK: - 3/5. The three stations from the brief
func testBriefCaseTescoBradfordIsMarginallyWorseOff() throws { func testBriefCaseTescoBradfordIsMarginallyWorseOff() throws {
let result = try briefResult(candidatePrice: 170.9, extraMiles: 2.0) let result = try briefResult(candidatePrice: 170.9, extraMiles: 2.0)
XCTAssertEqual(result.fillLitres, 34.904014, accuracy: 1e-6) XCTAssertEqual(result.fillLitres, 35.108250, accuracy: 1e-6)
XCTAssertEqual(result.grossSavingGBP, 0.349040, accuracy: 1e-6, "1p/litre cheaper on a 34.90 L fill") XCTAssertEqual(result.grossSavingGBP, 0.351083, accuracy: 1e-6, "£60 buys 35.11 L at the candidate price")
XCTAssertEqual(result.extraDistanceMiles, 2.0, accuracy: 1e-9) XCTAssertEqual(result.extraDistanceMiles, 2.0, accuracy: 1e-9)
XCTAssertEqual(result.extraDrivingCostGBP, 0.517951, accuracy: 1e-6) XCTAssertEqual(result.extraDrivingCostGBP, 0.517951, accuracy: 1e-6)
XCTAssertEqual(result.netSavingGBP, -0.168911, accuracy: 1e-6) XCTAssertEqual(result.netSavingGBP, -0.166869, accuracy: 1e-6)
XCTAssertEqual(result.status, .notWorthTheDrive) XCTAssertEqual(result.status, .notWorthTheDrive)
XCTAssertEqual(result.headline(), "£0.17 worse off after travel") XCTAssertEqual(result.headline(), "Costs £0.17 more")
} }
/// The brief recorded "£0.18 worse off" for this row against a displayed /// The brief recorded "£0.18 worse off" for this row against a displayed
@@ -104,9 +206,9 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
/// is entirely the rounding of the distance, not of the money. /// is entirely the rounding of the distance, not of the money.
func testTheReportedEighteenPenceIsRoundedExtraDistanceNotARoundingBug() throws { func testTheReportedEighteenPenceIsRoundedExtraDistanceNotARoundingBug() throws {
XCTAssertEqual(try briefResult(candidatePrice: 170.9, extraMiles: 2.00).headline(), XCTAssertEqual(try briefResult(candidatePrice: 170.9, extraMiles: 2.00).headline(),
"£0.17 worse off after travel") "Costs £0.17 more")
XCTAssertEqual(try briefResult(candidatePrice: 170.9, extraMiles: 2.05).headline(), XCTAssertEqual(try briefResult(candidatePrice: 170.9, extraMiles: 2.05).headline(),
"£0.18 worse off after travel") "Costs £0.18 more")
// 2.05 mi shows as "2.0 mi" at one decimal place — the same caption. // 2.05 mi shows as "2.0 mi" at one decimal place — the same caption.
XCTAssertEqual(FuelSavingsFormat.extraTravelLabel(extraDistanceMiles: 2.05, unit: .miles), XCTAssertEqual(FuelSavingsFormat.extraTravelLabel(extraDistanceMiles: 2.05, unit: .miles),
@@ -118,13 +220,13 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
func testBriefCaseMFGHareAndHoundsIsWorseOff() throws { func testBriefCaseMFGHareAndHoundsIsWorseOff() throws {
let result = try briefResult(candidatePrice: 172.9, extraMiles: 2.8) let result = try briefResult(candidatePrice: 172.9, extraMiles: 2.8)
XCTAssertEqual(result.fillLitres, 34.904014, accuracy: 1e-6) XCTAssertEqual(result.fillLitres, 34.702140, accuracy: 1e-6)
XCTAssertEqual(result.grossSavingGBP, -0.349040, accuracy: 1e-6, "1p/litre dearer costs 34.90 L × 1p") XCTAssertEqual(result.grossSavingGBP, -0.347021, accuracy: 1e-6, "£60 buys 34.70 L at the candidate price")
XCTAssertEqual(result.extraDistanceMiles, 2.8, accuracy: 1e-9) XCTAssertEqual(result.extraDistanceMiles, 2.8, accuracy: 1e-9)
XCTAssertEqual(result.extraDrivingCostGBP, 0.733618, accuracy: 1e-6) XCTAssertEqual(result.extraDrivingCostGBP, 0.733618, accuracy: 1e-6)
XCTAssertEqual(result.netSavingGBP, -1.082658, accuracy: 1e-6) XCTAssertEqual(result.netSavingGBP, -1.080639, accuracy: 1e-6)
XCTAssertEqual(result.status, .notWorthTheDrive) XCTAssertEqual(result.status, .notWorthTheDrive)
XCTAssertEqual(result.headline(), "£1.08 worse off after travel") XCTAssertEqual(result.headline(), "Costs £1.08 more")
} }
func testBriefCasePGGNapoleonSamePumpPriceIsTravelCostOnly() throws { func testBriefCasePGGNapoleonSamePumpPriceIsTravelCostOnly() throws {
@@ -135,7 +237,7 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
XCTAssertEqual(result.netSavingGBP, -0.729375, accuracy: 1e-6, XCTAssertEqual(result.netSavingGBP, -0.729375, accuracy: 1e-6,
"with no price difference the whole result is the extra driving") "with no price difference the whole result is the extra driving")
XCTAssertEqual(result.status, .notWorthTheDrive) XCTAssertEqual(result.status, .notWorthTheDrive)
XCTAssertEqual(result.headline(), "£0.73 worse off after travel") XCTAssertEqual(result.headline(), "Costs £0.73 more")
} }
// MARK: - 5/6. Classification, tolerance and rounding // MARK: - 5/6. Classification, tolerance and rounding
@@ -150,15 +252,15 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
} }
func testSmallSavingInsideTheToleranceIsBreakEvenNotPennies() throws { func testSmallSavingInsideTheToleranceIsBreakEvenNotPennies() throws {
// 171.9p vs 170.9p over a 1.23 mi delta: net +£0.0305. // 171.9p vs 170.9p over a 1.23 mi delta: the small saving remains within tolerance.
let result = try briefResult(candidatePrice: 170.9, extraMiles: 1.23) let result = try briefResult(candidatePrice: 170.9, extraMiles: 1.23)
XCTAssertEqual(result.netSavingGBP, 0.030500, accuracy: 1e-6) XCTAssertEqual(result.netSavingGBP, 0.03254252417853143, accuracy: 1e-9)
XCTAssertEqual(result.status, .breakEven, "±5p reads as break even rather than a meaningless £0.03") XCTAssertEqual(result.status, .breakEven, "±5p reads as break even rather than a meaningless £0.03")
XCTAssertEqual(result.headline(), "Break even") XCTAssertEqual(result.headline(), "Break even")
} }
func testBreakEvenToleranceDecidesTheClassificationAtTheBoundary() throws { func testBreakEvenToleranceDecidesTheClassificationAtTheBoundary() throws {
let net = -0.168911 let net = -0.166869
// A tolerance wider than the loss → break even; narrower → worse off. // A tolerance wider than the loss → break even; narrower → worse off.
let lenient = try FuelSavingsCalculator.calculate( let lenient = try FuelSavingsCalculator.calculate(
mpg: 30, mpg: 30,
@@ -187,7 +289,7 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
func testMoneyIsRoundedOnlyForDisplay() throws { func testMoneyIsRoundedOnlyForDisplay() throws {
// Full precision retained internally… // Full precision retained internally…
let result = try briefResult(candidatePrice: 172.9, extraMiles: 2.8) let result = try briefResult(candidatePrice: 172.9, extraMiles: 2.8)
XCTAssertEqual(result.netSavingGBP, -1.082658, accuracy: 1e-6) XCTAssertEqual(result.netSavingGBP, -1.080639, accuracy: 1e-6)
XCTAssertNotEqual(result.netSavingGBP, -1.08, "the stored value must not be pre-rounded") XCTAssertNotEqual(result.netSavingGBP, -1.08, "the stored value must not be pre-rounded")
// …and rounded to two places only when shown. // …and rounded to two places only when shown.
XCTAssertEqual(FuelSavingsFormat.money(1.082658), "£1.08") XCTAssertEqual(FuelSavingsFormat.money(1.082658), "£1.08")
@@ -197,6 +299,23 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
XCTAssertEqual(FuelSavingsFormat.money(0), "£0.00") XCTAssertEqual(FuelSavingsFormat.money(0), "£0.00")
} }
func testIndependentlyRoundedFinancialComponentsMayDifferFromRoundedTotalByOnePenny() {
let gross = 1.234
let drivingCost = 0.005
let net = gross - drivingCost
XCTAssertEqual(FuelSavingsFormat.money(gross), "£1.23")
XCTAssertEqual(FuelSavingsFormat.money(drivingCost), "£0.01")
XCTAssertEqual(FuelSavingsFormat.money(net), "£1.23")
let independentlyRoundedSubtraction = 1.23 - 0.01
XCTAssertEqual(independentlyRoundedSubtraction, 1.22, accuracy: 1e-12)
XCTAssertNotEqual(
FuelSavingsFormat.money(independentlyRoundedSubtraction),
FuelSavingsFormat.money(net),
"the raw total remains authoritative; independently rounded components need not add back exactly"
)
}
func testSortingUsesTheUnroundedNetSoRoundedTiesStillOrderCorrectly() { func testSortingUsesTheUnroundedNetSoRoundedTiesStillOrderCorrectly() {
// Two rows that both DISPLAY "£0.18 worse off" but differ in the raw // Two rows that both DISPLAY "£0.18 worse off" but differ in the raw
// figure: the sort must use the raw value, never the shown one. // figure: the sort must use the raw value, never the shown one.
@@ -237,12 +356,12 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
baselineJourneyMiles: 2.0, baselineJourneyMiles: 2.0,
candidateJourneyMiles: 7.0 candidateJourneyMiles: 7.0
) )
XCTAssertEqual(result.fillLitres, 27.416038, accuracy: 1e-6) XCTAssertEqual(result.fillLitres, 28.797696, accuracy: 1e-6)
XCTAssertEqual(result.grossSavingGBP, 1.919123, accuracy: 1e-6) XCTAssertEqual(result.grossSavingGBP, 2.015839, accuracy: 1e-6)
XCTAssertEqual(result.extraDrivingCostGBP, 0.701613, accuracy: 1e-6) XCTAssertEqual(result.extraDrivingCostGBP, 0.701613, accuracy: 1e-6)
XCTAssertEqual(result.netSavingGBP, 1.217509, accuracy: 1e-6) XCTAssertEqual(result.netSavingGBP, 1.314226, accuracy: 1e-6)
XCTAssertEqual(result.status, .worthTheDrive) XCTAssertEqual(result.status, .worthTheDrive)
XCTAssertEqual(result.headline(), "£1.22 better off after travel") XCTAssertEqual(result.headline(), "Save £1.31")
} }
func testNearerCandidateIsNeverChargedExtraTravel() throws { func testNearerCandidateIsNeverChargedExtraTravel() throws {
@@ -270,9 +389,9 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
baselineJourneyMiles: 0.8, baselineJourneyMiles: 0.8,
candidateJourneyMiles: 3.6 candidateJourneyMiles: 3.6
) )
XCTAssertEqual(sixty.grossSavingGBP, -0.349040, accuracy: 1e-6, "MPG must not touch the pump saving") XCTAssertEqual(sixty.grossSavingGBP, -0.347021, accuracy: 1e-6, "MPG must not touch the pump saving")
XCTAssertEqual(sixty.extraDrivingCostGBP, 0.366809, accuracy: 1e-6) XCTAssertEqual(sixty.extraDrivingCostGBP, 0.366809, accuracy: 1e-6)
XCTAssertEqual(sixty.netSavingGBP, -0.715849, accuracy: 1e-6) XCTAssertEqual(sixty.netSavingGBP, -0.713830, accuracy: 1e-6)
let fortyFive = try FuelSavingsCalculator.calculate( let fortyFive = try FuelSavingsCalculator.calculate(
mpg: 45, mpg: 45,
@@ -283,7 +402,7 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
candidateJourneyMiles: 3.6 candidateJourneyMiles: 3.6
) )
XCTAssertEqual(fortyFive.extraDrivingCostGBP, 0.489078, accuracy: 1e-6) XCTAssertEqual(fortyFive.extraDrivingCostGBP, 0.489078, accuracy: 1e-6)
XCTAssertEqual(fortyFive.netSavingGBP, -0.838119, accuracy: 1e-6) XCTAssertEqual(fortyFive.netSavingGBP, -0.836100, accuracy: 1e-6)
} }
func testDifferentFillBudgetsScaleOnlyThePumpSaving() throws { func testDifferentFillBudgetsScaleOnlyThePumpSaving() throws {
@@ -295,10 +414,10 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
baselineJourneyMiles: 0.8, baselineJourneyMiles: 0.8,
candidateJourneyMiles: 3.6 candidateJourneyMiles: 3.6
) )
XCTAssertEqual(forty.fillLitres, 23.269343, accuracy: 1e-6, "£40 buys 23.27 L at 171.9p") XCTAssertEqual(forty.fillLitres, 23.134760, accuracy: 1e-6, "£40 buys 23.13 L at the candidate price")
XCTAssertEqual(forty.grossSavingGBP, -0.232693, accuracy: 1e-6) XCTAssertEqual(forty.grossSavingGBP, -0.231348, accuracy: 1e-6)
XCTAssertEqual(forty.extraDrivingCostGBP, 0.733618, accuracy: 1e-6, "the journey cost is budget-independent") XCTAssertEqual(forty.extraDrivingCostGBP, 0.733618, accuracy: 1e-6, "the journey cost is budget-independent")
XCTAssertEqual(forty.netSavingGBP, -0.966311, accuracy: 1e-6) XCTAssertEqual(forty.netSavingGBP, -0.964965, accuracy: 1e-6)
let ninety = try FuelSavingsCalculator.calculate( let ninety = try FuelSavingsCalculator.calculate(
mpg: 30, mpg: 30,
@@ -308,9 +427,9 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
baselineJourneyMiles: 0.8, baselineJourneyMiles: 0.8,
candidateJourneyMiles: 3.6 candidateJourneyMiles: 3.6
) )
XCTAssertEqual(ninety.fillLitres, 52.356021, accuracy: 1e-6) XCTAssertEqual(ninety.fillLitres, 52.053210, accuracy: 1e-6)
XCTAssertEqual(ninety.grossSavingGBP, -0.523560, accuracy: 1e-6) XCTAssertEqual(ninety.grossSavingGBP, -0.520532, accuracy: 1e-6)
XCTAssertEqual(ninety.netSavingGBP, -1.257178, accuracy: 1e-6) XCTAssertEqual(ninety.netSavingGBP, -1.254150, accuracy: 1e-6)
} }
func testFillUpInLitresIsFixedRegardlessOfPrice() throws { func testFillUpInLitresIsFixedRegardlessOfPrice() throws {
@@ -370,7 +489,7 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
journey: journey(2.8), journey: journey(2.8),
baselineJourney: journey(0.8) baselineJourney: journey(0.8)
) )
XCTAssertEqual(both?.result?.netSavingGBP ?? 0, -0.168911, accuracy: 1e-6) XCTAssertEqual(both?.result?.netSavingGBP ?? 0, -0.166869, accuracy: 1e-6)
} }
func testMixedRouteBasisIsReportedAsAnEstimate() { func testMixedRouteBasisIsReportedAsAnEstimate() {
@@ -393,7 +512,7 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
XCTAssertEqual(mixed?.result?.distanceBasis, .straightLine, XCTAssertEqual(mixed?.result?.distanceBasis, .straightLine,
"one unmeasured leg makes the whole estimate an estimate") "one unmeasured leg makes the whole estimate an estimate")
XCTAssertEqual(mixed?.result?.journeyConfidence, .estimated) XCTAssertEqual(mixed?.result?.journeyConfidence, .estimated)
XCTAssertEqual(mixed?.result?.headline(compact: true), "Approx. £0.17 worse off after travel") XCTAssertEqual(mixed?.result?.headline(compact: true), "Approx. Costs £0.17 more")
} }
func testBaselineStationIsLabelledClosestStationNotBreakEven() { func testBaselineStationIsLabelledClosestStationNotBreakEven() {
@@ -41,6 +41,42 @@ final class FuelSavingsEstimateTests: XCTestCase {
FuelSavingsJourney(miles: miles, basis: .straightLine) FuelSavingsJourney(miles: miles, basis: .straightLine)
} }
/// Fuel types are never mixed: a station that does not sell the selected
/// fuel cannot be its baseline, and cannot be compared with it.
func testDifferentFuelNeverUsesAnotherGradeAsItsBaseline() {
let petrolOnly = FuelStation(id: "petrol", name: "Petrol", brand: "", address: "", postcode: "", lat: 53, lng: -1,
prices: [.e10: 199.9], priceUpdated: nil)
let dieselOnly = FuelStation(id: "diesel", name: "Diesel", brand: "", address: "", postcode: "", lat: 53, lng: -1,
prices: [.diesel: 129.9], priceUpdated: nil)
let nearest = FuelSavingsEstimator.baselineStation([petrolOnly, dieselOnly], fuel: .diesel) { station in
self.straightLine(station.id == "petrol" ? 0.5 : 1)
}
XCTAssertEqual(nearest?.id, "diesel")
let unavailable = FuelSavingsEstimator.availability(station: dieselOnly, fuel: .diesel, baseline: petrolOnly,
settings: settings, amount: amount, journey: straightLine(1), baselineJourney: straightLine(0.5))
XCTAssertEqual(unavailable, .unavailable("No comparison station"))
}
/// Ranking must still work when the list being ordered is filtered tighter
/// than the pool the baseline was chosen from.
func testBaselineOutsideFilteredPoolStillRanksByNetSaving() {
let baseline = station("nearest-outside-radius", price: 199.9)
let cheap = station("z-cheap", price: 129.9)
let expensive = station("a-expensive", price: 198.9)
let ranked = FuelSavingsEstimator.ranked(
[expensive, cheap], fuel: .e10, baseline: baseline,
settings: settings, amount: amount,
journeyMiles: { s in self.straightLine(s.id == baseline.id ? 0.8 : 4.0) }
)
XCTAssertEqual(ranked.map(\.id), ["z-cheap", "a-expensive"])
let expected = FuelSavingsEstimator.availability(
station: cheap, fuel: .e10, baseline: baseline,
settings: settings, amount: amount,
journey: straightLine(4.0), baselineJourney: straightLine(0.8)
)?.result
XCTAssertGreaterThan(expected?.netSavingGBP ?? -1, 0)
}
func testCheaperStationThreePointFiveMilesAwayIsRankedFirstWithASaving() { func testCheaperStationThreePointFiveMilesAwayIsRankedFirstWithASaving() {
// Nearest station: 1 mile away at 145.9p. The station the user can see // Nearest station: 1 mile away at 145.9p. The station the user can see
// in the Cheapest tab: 3.5 miles away at 138.9p. // in the Cheapest tab: 3.5 miles away at 138.9p.
@@ -284,9 +320,9 @@ final class FuelSavingsEstimateTests: XCTestCase {
/// (171.9p, 0.4 mi), candidate Shell Whetley Hill (167.9p, 3.8 mi). /// (171.9p, 0.4 mi), candidate Shell Whetley Hill (167.9p, 3.8 mi).
/// ///
/// Whetley Hill is 4p/litre cheaper, yet it is WORSE OFF — and that is /// Whetley Hill is 4p/litre cheaper, yet it is WORSE OFF — and that is
/// correct, not a calculation bug: £60 buys 34.90 L at 171.9p, so the /// correct, not a calculation bug: £60 buys 35.74 L at 167.9p, so the
/// cheaper pump saves 34.90 × 4p = £1.40, while the extra 6.8 return miles /// cheaper pump saves 35.74 × 4p = £1.43, while the extra 6.8 return miles
/// burn 6.8/30 × 4.54609 = 1.03 L at 167.9p = £1.73. Net ≈ −£0.33. /// burn 6.8/30 × 4.54609 = 1.03 L at 167.9p = £1.73. Net ≈ −£0.30.
func testCheaperStationFurtherAwayIsWorseOffAfterTravel() { func testCheaperStationFurtherAwayIsWorseOffAfterTravel() {
let baseline = station("rontec-shelf", price: 171.9) let baseline = station("rontec-shelf", price: 171.9)
let candidate = station("shell-whetley-hill", price: 167.9) let candidate = station("shell-whetley-hill", price: 167.9)
@@ -304,16 +340,16 @@ final class FuelSavingsEstimateTests: XCTestCase {
guard let result = availability?.result else { guard let result = availability?.result else {
return XCTFail("expected an estimate, got \(String(describing: availability))") return XCTFail("expected an estimate, got \(String(describing: availability))")
} }
XCTAssertEqual(result.fillLitres, 34.904, accuracy: 0.005, XCTAssertEqual(result.fillLitres, 35.736, accuracy: 0.005,
"the £60 budget buys litres at the BASELINE pump price") "the £60 budget buys litres at the candidate pump price")
XCTAssertEqual(result.grossSavingGBP, 1.396, accuracy: 0.005) XCTAssertEqual(result.grossSavingGBP, 1.429, accuracy: 0.005)
XCTAssertEqual(result.extraDistanceMiles, 6.8, accuracy: 0.001, XCTAssertEqual(result.extraDistanceMiles, 6.8, accuracy: 0.001,
"only the return-trip DELTA counts — the shared journey is never counted twice") "only the return-trip DELTA counts — the shared journey is never counted twice")
XCTAssertEqual(result.extraDrivingCostGBP, 1.730, accuracy: 0.005) XCTAssertEqual(result.extraDrivingCostGBP, 1.730, accuracy: 0.005)
XCTAssertEqual(result.netSavingGBP, -0.334, accuracy: 0.005) XCTAssertEqual(result.netSavingGBP, -0.301, accuracy: 0.005)
XCTAssertEqual(result.status, .notWorthTheDrive) XCTAssertEqual(result.status, .notWorthTheDrive)
XCTAssertEqual(result.journeyConfidence, .estimated) XCTAssertEqual(result.journeyConfidence, .estimated)
XCTAssertEqual(result.headline(compact: true), "Approx. £0.33 worse off after travel") XCTAssertEqual(result.headline(compact: true), "Approx. Costs £0.30 more")
} }
func testMeasuredRoadRoutesDropTheEstimateMarker() { func testMeasuredRoadRoutesDropTheEstimateMarker() {
@@ -332,8 +368,8 @@ final class FuelSavingsEstimateTests: XCTestCase {
XCTAssertEqual(availability?.result?.distanceBasis, .roadRoute) XCTAssertEqual(availability?.result?.distanceBasis, .roadRoute)
XCTAssertEqual(availability?.result?.journeyConfidence, .confirmed) XCTAssertEqual(availability?.result?.journeyConfidence, .confirmed)
XCTAssertEqual(availability?.result?.headline(compact: true), "£0.33 worse off after travel") XCTAssertEqual(availability?.result?.headline(compact: true), "Costs £0.30 more")
XCTAssertEqual(availability?.result?.headline(), "£0.33 worse off after travel") XCTAssertEqual(availability?.result?.headline(), "Costs £0.30 more")
} }
func testBaselineRowIsLabelledClosestStation() { func testBaselineRowIsLabelledClosestStation() {
@@ -375,10 +411,10 @@ final class FuelSavingsEstimateTests: XCTestCase {
return XCTFail("expected an estimate, got \(String(describing: availability))") return XCTFail("expected an estimate, got \(String(describing: availability))")
} }
XCTAssertEqual(result.status, .worthTheDrive) XCTAssertEqual(result.status, .worthTheDrive)
// £60 buys 37.5 L at 160p; 10p/litre cheaper saves £3.75; 0.4 extra // £60 buys 40 L at 150p; 10p/litre cheaper saves £4.00; 0.4 extra
// return miles cost ~£0.09. Net ≈ £3.66. // return miles cost ~£0.09. Net ≈ £3.91.
XCTAssertEqual(result.netSavingGBP, 3.659, accuracy: 0.005) XCTAssertEqual(result.netSavingGBP, 3.909, accuracy: 0.005)
XCTAssertEqual(result.headline(compact: true), "Approx. £3.66 better off after travel") XCTAssertEqual(result.headline(compact: true), "Approx. Save £3.91")
} }
func testNeutralResultHeadlineIsBreakEven() { func testNeutralResultHeadlineIsBreakEven() {
@@ -413,7 +449,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
netSavingGBP: 0.52, netSavingGBP: 0.52,
status: .worthTheDrive, status: .worthTheDrive,
distanceBasis: .roadRoute) distanceBasis: .roadRoute)
XCTAssertEqual(saving.headline(), "£0.52 better off after travel") XCTAssertEqual(saving.headline(), "Save £0.52")
let loss = FuelSavingsResult(fillLitres: 34.9, let loss = FuelSavingsResult(fillLitres: 34.9,
grossSavingGBP: 1.40, grossSavingGBP: 1.40,
@@ -422,7 +458,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
netSavingGBP: -0.31, netSavingGBP: -0.31,
status: .notWorthTheDrive, status: .notWorthTheDrive,
distanceBasis: .roadRoute) distanceBasis: .roadRoute)
XCTAssertEqual(loss.headline(), "£0.31 worse off after travel") XCTAssertEqual(loss.headline(), "Costs £0.31 more")
} }
/// The sort must order by NET saving, not pump price: a pricier station can /// The sort must order by NET saving, not pump price: a pricier station can
@@ -454,6 +490,25 @@ final class FuelSavingsEstimateTests: XCTestCase {
// MARK: Row copy // MARK: Row copy
func testCompactComparisonLabelUsesGenericNearestStationWording() {
XCTAssertEqual(
FuelSavingsFormat.comparisonLabel(status: .worthTheDrive),
"vs closest station"
)
XCTAssertEqual(
FuelSavingsFormat.comparisonLabel(status: .notWorthTheDrive),
"vs closest station"
)
XCTAssertEqual(
FuelSavingsFormat.comparisonLabel(status: .breakEven),
"vs closest station"
)
XCTAssertEqual(
FuelSavingsFormat.comparisonLabel(status: .baseline),
"your baseline"
)
}
/// The row's extra-driving caption must follow the DISPLAY unit: the stored /// The row's extra-driving caption must follow the DISPLAY unit: the stored
/// figure is always miles, and converting by the current unit instead would /// figure is always miles, and converting by the current unit instead would
/// leave a km user's figure unlabelled and 1.6× too large. /// leave a km user's figure unlabelled and 1.6× too large.
@@ -486,7 +541,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
netSavingGBP: 0, netSavingGBP: 0,
status: .baseline status: .baseline
) )
XCTAssertEqual(baseline.capsuleHeadline(), "Closest station · your baseline") XCTAssertEqual(baseline.capsuleHeadline(), "Closest station")
let saving = FuelSavingsResult( let saving = FuelSavingsResult(
fillLitres: 30, fillLitres: 30,
@@ -497,7 +552,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
status: .worthTheDrive, status: .worthTheDrive,
distanceBasis: .straightLine distanceBasis: .straightLine
) )
XCTAssertEqual(saving.capsuleHeadline(), "Approx. £1.00 better off after travel") XCTAssertEqual(saving.capsuleHeadline(), "Approx. Save £1.00")
let worse = FuelSavingsResult( let worse = FuelSavingsResult(
fillLitres: 30, fillLitres: 30,
@@ -507,7 +562,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
netSavingGBP: -0.31, netSavingGBP: -0.31,
status: .notWorthTheDrive status: .notWorthTheDrive
) )
XCTAssertEqual(worse.capsuleHeadline(), "£0.31 worse off after travel") XCTAssertEqual(worse.capsuleHeadline(), "Costs £0.31 more")
} }
// MARK: - Estimate wording (Approx. labels) // MARK: - Estimate wording (Approx. labels)
@@ -524,7 +579,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
status: .worthTheDrive, status: .worthTheDrive,
distanceBasis: .straightLine distanceBasis: .straightLine
) )
XCTAssertEqual(saving.headline(), "Approx. £1.25 better off after travel") XCTAssertEqual(saving.headline(), "Approx. Save £1.25")
let loss = FuelSavingsResult( let loss = FuelSavingsResult(
fillLitres: 30, fillLitres: 30,
@@ -535,7 +590,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
status: .notWorthTheDrive, status: .notWorthTheDrive,
distanceBasis: .straightLine distanceBasis: .straightLine
) )
XCTAssertEqual(loss.headline(), "Approx. £0.77 worse off after travel") XCTAssertEqual(loss.headline(), "Approx. Costs £0.77 more")
} }
/// A confirmed road-route comparison must never carry the marker — in either /// A confirmed road-route comparison must never carry the marker — in either
@@ -551,7 +606,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
distanceBasis: .roadRoute, distanceBasis: .roadRoute,
journeyConfidence: .confirmed journeyConfidence: .confirmed
) )
XCTAssertEqual(saving.headline(), "£1.25 better off after travel") XCTAssertEqual(saving.headline(), "Save £1.25")
let loss = FuelSavingsResult( let loss = FuelSavingsResult(
fillLitres: 30, fillLitres: 30,
@@ -563,7 +618,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
distanceBasis: .roadRoute, distanceBasis: .roadRoute,
journeyConfidence: .confirmed journeyConfidence: .confirmed
) )
XCTAssertEqual(loss.headline(), "£0.77 worse off after travel") XCTAssertEqual(loss.headline(), "Costs £0.77 more")
for headline in [saving.headline(), loss.headline(), saving.capsuleHeadline()] { for headline in [saving.headline(), loss.headline(), saving.capsuleHeadline()] {
XCTAssertFalse(headline.contains("Approx"), "\"\(headline)\" must not claim to be an estimate") XCTAssertFalse(headline.contains("Approx"), "\"\(headline)\" must not claim to be an estimate")
@@ -597,7 +652,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
status: .notWorthTheDrive, status: .notWorthTheDrive,
distanceBasis: .straightLine distanceBasis: .straightLine
) )
XCTAssertEqual(estimated.spokenHeadline(), "Approximately £0.77 worse off after travel") XCTAssertEqual(estimated.spokenHeadline(), "Approximately Costs £0.77 more")
XCTAssertEqual( XCTAssertEqual(
FuelSavingsFormat.extraTravelSpokenLabel(extraDistanceMiles: 6.4, unit: .miles, confidence: .estimated), FuelSavingsFormat.extraTravelSpokenLabel(extraDistanceMiles: 6.4, unit: .miles, confidence: .estimated),
@@ -8,15 +8,15 @@ final class FuelSavingsCalculatorTests: XCTestCase {
XCTAssertEqual(FuelSavingsCalculator.fuelUsedLitres(distanceMiles: 10, mpg: 45), 1.0102, accuracy: 0.0001) XCTAssertEqual(FuelSavingsCalculator.fuelUsedLitres(distanceMiles: 10, mpg: 45), 1.0102, accuracy: 0.0001)
} }
func testPoundsBudgetConvertsToLitresUsingBaselinePrice() throws { func testPoundsBudgetConvertsToLitresUsingGivenPrice() throws {
let amount = FuelSavingsFillAmount(value: 40, unit: .pounds) let amount = FuelSavingsFillAmount(value: 40, unit: .pounds)
let litres = try FuelSavingsCalculator.fillLitres(amount: amount, baselinePricePencePerLitre: 160) let litres = try FuelSavingsCalculator.fillLitres(amount: amount, pricePencePerLitre: 160)
XCTAssertEqual(litres, 25.0, accuracy: 0.0001) XCTAssertEqual(litres, 25.0, accuracy: 0.0001)
} }
func testLitresAmountPassesThrough() throws { func testLitresAmountPassesThrough() throws {
let amount = FuelSavingsFillAmount(value: 35, unit: .litres) let amount = FuelSavingsFillAmount(value: 35, unit: .litres)
let litres = try FuelSavingsCalculator.fillLitres(amount: amount, baselinePricePencePerLitre: 160) let litres = try FuelSavingsCalculator.fillLitres(amount: amount, pricePencePerLitre: 160)
XCTAssertEqual(litres, 35, accuracy: 0.0001) XCTAssertEqual(litres, 35, accuracy: 0.0001)
} }
@@ -29,11 +29,11 @@ final class FuelSavingsCalculatorTests: XCTestCase {
baselineJourneyMiles: 2, baselineJourneyMiles: 2,
candidateJourneyMiles: 8 candidateJourneyMiles: 8
) )
XCTAssertEqual(result.fillLitres, 25, accuracy: 0.0001) XCTAssertEqual(result.fillLitres, 26.6667, accuracy: 0.0001)
XCTAssertEqual(result.grossSavingGBP, 2.50, accuracy: 0.0001) XCTAssertEqual(result.grossSavingGBP, 2.6667, accuracy: 0.0001)
XCTAssertEqual(result.extraDistanceMiles, 6, accuracy: 0.0001) XCTAssertEqual(result.extraDistanceMiles, 6, accuracy: 0.0001)
XCTAssertEqual(result.extraDrivingCostGBP, 0.9092, accuracy: 0.0001) XCTAssertEqual(result.extraDrivingCostGBP, 0.9092, accuracy: 0.0001)
XCTAssertEqual(result.netSavingGBP, 1.5908, accuracy: 0.0001) XCTAssertEqual(result.netSavingGBP, 1.7574, accuracy: 0.0001)
XCTAssertEqual(result.status, .worthTheDrive) XCTAssertEqual(result.status, .worthTheDrive)
} }
@@ -61,7 +61,7 @@ final class FuelSavingsCalculatorTests: XCTestCase {
} }
func testInvalidInputsRejected() { func testInvalidInputsRejected() {
XCTAssertThrowsError(try FuelSavingsCalculator.fillLitres(amount: FuelSavingsFillAmount(value: 40, unit: .pounds), baselinePricePencePerLitre: 0)) XCTAssertThrowsError(try FuelSavingsCalculator.fillLitres(amount: FuelSavingsFillAmount(value: 40, unit: .pounds), pricePencePerLitre: 0))
XCTAssertThrowsError(try FuelSavingsCalculator.calculate(mpg: 0, amount: FuelSavingsFillAmount(value: 40, unit: .pounds), baselinePricePencePerLitre: 160, candidatePricePencePerLitre: 150, baselineJourneyMiles: 1, candidateJourneyMiles: 2)) XCTAssertThrowsError(try FuelSavingsCalculator.calculate(mpg: 0, amount: FuelSavingsFillAmount(value: 40, unit: .pounds), baselinePricePencePerLitre: 160, candidatePricePencePerLitre: 150, baselineJourneyMiles: 1, candidateJourneyMiles: 2))
XCTAssertThrowsError(try FuelSavingsCalculator.calculate(mpg: 500, amount: FuelSavingsFillAmount(value: 40, unit: .pounds), baselinePricePencePerLitre: 160, candidatePricePencePerLitre: 150, baselineJourneyMiles: 1, candidateJourneyMiles: 2)) XCTAssertThrowsError(try FuelSavingsCalculator.calculate(mpg: 500, amount: FuelSavingsFillAmount(value: 40, unit: .pounds), baselinePricePencePerLitre: 160, candidatePricePencePerLitre: 150, baselineJourneyMiles: 1, candidateJourneyMiles: 2))
} }
@@ -143,6 +143,15 @@ final class FuelSavingsCalculatorTests: XCTestCase {
} }
final class FuelSavingsSettingsTests: XCTestCase { final class FuelSavingsSettingsTests: XCTestCase {
func testSwitchingFillUnitStartsAnExplicitNewComparison() {
let budget = FuelSavingsFillAmount(value: 60, unit: .pounds)
let litres = FuelSavingsCalculator.newComparisonAmount(afterSwitching: budget, to: .litres)
XCTAssertEqual(litres, FuelSavingsFillAmount(value: 30, unit: .litres))
XCTAssertEqual(FuelSavingsCalculator.newComparisonAmount(afterSwitching: litres, to: .pounds),
FuelSavingsFillAmount(value: 40, unit: .pounds))
XCTAssertEqual(FuelSavingsCalculator.newComparisonAmount(afterSwitching: budget, to: .pounds), budget)
}
func testSettingsValidationRequiresEnabledMPGAndFillAmount() { func testSettingsValidationRequiresEnabledMPGAndFillAmount() {
XCTAssertFalse(FuelSavingsSettings(enabled: false, mpg: 45, preferredAmount: .init(value: 40, unit: .pounds)).isConfigured) XCTAssertFalse(FuelSavingsSettings(enabled: false, mpg: 45, preferredAmount: .init(value: 40, unit: .pounds)).isConfigured)
XCTAssertFalse(FuelSavingsSettings(enabled: true, mpg: 0, preferredAmount: .init(value: 40, unit: .pounds)).isConfigured) XCTAssertFalse(FuelSavingsSettings(enabled: true, mpg: 0, preferredAmount: .init(value: 40, unit: .pounds)).isConfigured)
@@ -150,3 +159,101 @@ final class FuelSavingsSettingsTests: XCTestCase {
XCTAssertTrue(FuelSavingsSettings(enabled: true, mpg: 45, preferredAmount: .init(value: 40, unit: .pounds)).isConfigured) XCTAssertTrue(FuelSavingsSettings(enabled: true, mpg: 45, preferredAmount: .init(value: 40, unit: .pounds)).isConfigured)
} }
} }
/// The row's single recommendation badge. Presentation only, but the rules are
/// worth pinning: they decide which of two true statements a row makes, and
/// "no badge" is itself an answer.
final class StationRecommendationBadgeTests: XCTestCase {
private let threshold = 1.0
func testSavingAtTheThresholdEarnsBestValue() {
XCTAssertEqual(
StationRecommendationBadge.badge(netSavingGBP: 1.0, isCheapest: false,
bestValueThresholdGBP: threshold),
.bestValue
)
}
func testSavingBelowTheThresholdDoesNot() {
XCTAssertNil(
StationRecommendationBadge.badge(netSavingGBP: 0.42, isCheapest: false,
bestValueThresholdGBP: threshold)
)
}
func testCheapestWithoutAWorthwhileSavingStillSaysCheapest() {
XCTAssertEqual(
StationRecommendationBadge.badge(netSavingGBP: 0.42, isCheapest: true,
bestValueThresholdGBP: threshold),
.cheapest
)
}
/// The cheapest station keeps its badge even when the drive costs more than
/// the saving buys — it IS the cheapest price; the capsule underneath is
/// what says the trip is not worth it.
func testCheapestKeepsItsBadgeWhenTheDriveCostsMoreThanItSaves() {
XCTAssertEqual(
StationRecommendationBadge.badge(netSavingGBP: -14.30, isCheapest: true,
bestValueThresholdGBP: threshold),
.cheapest
)
}
/// One badge per row: the stronger statement wins.
func testBestValueOutranksCheapestWhenBothApply() {
XCTAssertEqual(
StationRecommendationBadge.badge(netSavingGBP: 3.15, isCheapest: true,
bestValueThresholdGBP: threshold),
.bestValue
)
}
/// A near-by station with no saving to speak of is context, not a
/// recommendation — the mockup gives NEAREST no capsule, and nothing else
/// here may invent one.
func testNoSavingAndNotCheapestMeansNoBadge() {
XCTAssertNil(
StationRecommendationBadge.badge(netSavingGBP: 0.0, isCheapest: false,
bestValueThresholdGBP: threshold)
)
XCTAssertNil(
StationRecommendationBadge.badge(netSavingGBP: -2.50, isCheapest: false,
bestValueThresholdGBP: threshold)
)
}
func testUnavailableSavingsLeaveOnlyTheCheapestBadge() {
XCTAssertEqual(
StationRecommendationBadge.badge(netSavingGBP: nil, isCheapest: true,
bestValueThresholdGBP: threshold),
.cheapest
)
XCTAssertNil(
StationRecommendationBadge.badge(netSavingGBP: nil, isCheapest: false,
bestValueThresholdGBP: threshold)
)
}
/// A rubbish figure must not become a recommendation.
func testNonFiniteFiguresProduceNoBadge() {
XCTAssertNil(
StationRecommendationBadge.badge(netSavingGBP: .nan, isCheapest: false,
bestValueThresholdGBP: threshold)
)
XCTAssertNil(
StationRecommendationBadge.badge(netSavingGBP: 5.0, isCheapest: false,
bestValueThresholdGBP: .nan)
)
}
/// The threshold is the user's alert setting: set it to zero and any saving
/// that is not a loss counts.
func testZeroThresholdAwardsBestValueToAnyNonNegativeSaving() {
XCTAssertEqual(
StationRecommendationBadge.badge(netSavingGBP: 0, isCheapest: false,
bestValueThresholdGBP: 0),
.bestValue
)
}
}
@@ -0,0 +1,33 @@
import XCTest
#if SWIFT_PACKAGE
@testable import FuelBoardShared
#endif
/// The Best Value gate's option list.
///
/// This one array is the figure behind two user-facing things — the BEST VALUE
/// badge on a station row and the proximity alert — so its granularity is a
/// setting, not an implementation detail. It was four coarse values (50p, £1,
/// £2, £5); these tests pin the 50p step and the £5 ceiling so a later edit
/// cannot quietly coarsen it back.
final class FuelStoreBestValueThresholdTests: XCTestCase {
func testOptionsStepByFiftyPenceUpToFivePounds() {
let options = FuelStore.bestValueAlertThresholdOptionsGBP
XCTAssertEqual(options, [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0])
XCTAssertEqual(options.count, 10)
XCTAssertEqual(options.first, 0.5, "the floor is the cheapest worth-the-drive saving offered")
XCTAssertEqual(options.last, 5.0, "£5 is the ceiling")
}
/// The store writes the threshold as a string and, on load, rejects any
/// value that is not one of these options — falling back to the £1 default.
/// So an option that does not survive `String` → `Double` exactly would
/// silently discard the user's choice. Multiples of 0.5 are exactly
/// representable in binary, and this keeps them that way.
func testEveryOptionSurvivesTheStoresStringRoundTrip() {
for option in FuelStore.bestValueAlertThresholdOptionsGBP {
XCTAssertEqual(Double(String(option)), option,
"£\(option) does not round-trip through the store's string encoding")
}
}
}
@@ -0,0 +1,219 @@
import XCTest
#if SWIFT_PACKAGE
@testable import FuelBoardShared
#endif
/// Regression: a station's price age never removes it from Best Value.
///
/// The relay publishes one `price_updated` per station — the newest
/// `price_last_updated` across the grades it maps — which cannot vouch for the
/// selected grade. It is therefore display-only: Best Value, Cheapest and
/// Closest rank stations on their prices and distances exactly as before,
/// whether the timestamp is minutes, months or absent.
final class StationPriceAgePolicyTests: XCTestCase {
private let now = Date(timeIntervalSince1970: 1_800_000_000)
private let settings = FuelSavingsSettings(
enabled: true,
mpg: 30,
preferredAmount: FuelSavingsFillAmount(value: 60, unit: .pounds)
)
private func station(_ id: String,
price: Double,
fuel: FuelType = .e10,
ageDays: Double?,
lat: Double = 53,
lng: Double = -1) -> FuelStation {
FuelStation(
id: id, name: id, brand: "X", address: "", postcode: "", lat: lat, lng: lng,
prices: [fuel: price],
priceUpdated: ageDays.map { now.addingTimeInterval(-$0 * 86_400).timeIntervalSince1970 }
)
}
private func straightLine(_ miles: Double) -> FuelSavingsJourney {
FuelSavingsJourney(miles: miles, basis: .straightLine)
}
private func distanceProvider(_ miles: [String: Double]) -> (FuelStation) -> FuelSavingsJourney? {
{ station in miles[station.id].map { self.straightLine($0) } }
}
// MARK: - The baseline is the closest seller, whatever its age
func testClosestSellerIsTheBaselineEvenWhenItsTimestampIsAncient() {
let ancientClosest = station("ancient-closest", price: 199.9, ageDays: 250)
let freshFurther = station("fresh-further", price: 170.9, ageDays: 1)
let journeys = distanceProvider(["ancient-closest": 0.8, "fresh-further": 3.0])
XCTAssertEqual(
FuelSavingsEstimator.baselineStation([ancientClosest, freshFurther], fuel: .e10,
journeyMiles: journeys)?.id,
"ancient-closest",
"the baseline is the closest station selling the selected fuel — age is not a criterion"
)
}
func testBaselineStillRequiresTheSelectedFuelAndAUsableJourney() {
let wrongFuel = station("wrong-fuel", price: 140, fuel: .diesel, ageDays: 1)
let unusableJourney = station("bad-journey", price: 141, ageDays: 1)
let sellsFuel = station("sells-fuel", price: 145, ageDays: 1)
let journeys = distanceProvider(["wrong-fuel": 0.1, "sells-fuel": 2.0]) // bad-journey has none
XCTAssertEqual(
FuelSavingsEstimator.baselineStation([wrongFuel, unusableJourney, sellsFuel], fuel: .e10,
journeyMiles: journeys)?.id,
"sells-fuel"
)
}
// MARK: - Old, missing and invalid timestamps still rank
func testOldPriceTimestampsRankByNetSavingForEveryFuel() {
for fuel in FuelType.allCases {
let base = station("base", price: 199.9, fuel: fuel, ageDays: 250)
let cheap = station("cheap", price: 129.9, fuel: fuel, ageDays: 250)
let dear = station("dear", price: 198.9, fuel: fuel, ageDays: 250)
let journeys = distanceProvider(["base": 0.8, "cheap": 1.2, "dear": 1.0])
let ranked = FuelSavingsEstimator.ranked([dear, cheap, base], fuel: fuel, baseline: base,
settings: settings, amount: settings.preferredAmount,
journeyMiles: journeys)
XCTAssertEqual(ranked.map(\.id), ["cheap", "dear", "base"], fuel.rawValue)
let saving = FuelSavingsEstimator.availability(
station: cheap, fuel: fuel, baseline: base, settings: settings,
amount: settings.preferredAmount, journey: straightLine(1.2), baselineJourney: straightLine(0.8)
)?.result
XCTAssertGreaterThan(saving?.netSavingGBP ?? -1, 0,
"\(fuel.rawValue): a 250-day-old price still produces a saving")
}
}
func testNetSavingStillOutranksPumpPriceWhenTimestampsAreOld() {
// Net saving decides the order: the cheapest station is 30 miles away,
// so a pricier one a mile from home wins. Nothing here consults the age.
let base = station("base", price: 171.9, ageDays: 120)
let cheapFar = station("cheap-far", price: 169.9, ageDays: 250)
let pricierNear = station("pricier-near", price: 170.9, ageDays: 200)
let journeys = distanceProvider(["base": 0.8, "cheap-far": 30, "pricier-near": 1.2])
let ranked = FuelSavingsEstimator.ranked([cheapFar, pricierNear, base], fuel: .e10, baseline: base,
settings: settings, amount: settings.preferredAmount,
journeyMiles: journeys)
XCTAssertEqual(ranked.map(\.id), ["pricier-near", "base", "cheap-far"])
XCTAssertEqual(ranked.first?.prices[.e10], 170.9, "the winner is chosen on net saving, not pump price")
}
func testMissingFutureAndAbsurdTimestampsDoNotRemoveStations() {
let invalid = FuelStation(id: "absurd", name: "Absurd", brand: "", address: "", postcode: "",
lat: 53, lng: -1, prices: [.e10: 150.9],
priceUpdated: -Double.greatestFiniteMagnitude)
let pool = [station("base", price: 199.9, ageDays: 250),
station("cheap", price: 129.9, ageDays: 100),
FuelStation(id: "future", name: "Future", brand: "", address: "", postcode: "",
lat: 53, lng: -1, prices: [.e10: 160.9],
priceUpdated: now.addingTimeInterval(86_400).timeIntervalSince1970),
station("undated", price: 170.9, ageDays: nil),
invalid]
let journeys = distanceProvider(["base": 0.8, "cheap": 1.2, "future": 1.6,
"undated": 2.0, "absurd": 2.8])
let ranked = FuelSavingsEstimator.ranked(pool, fuel: .e10, baseline: pool[0],
settings: settings, amount: settings.preferredAmount,
journeyMiles: journeys)
XCTAssertEqual(Set(ranked.map(\.id)), Set(pool.map(\.id)),
"every station stays in the pool: no timestamp can filter a row out")
XCTAssertEqual(ranked.first?.id, "cheap", "the cheapest station still wins")
}
func testEveryPricedStationKeepsAResultWhateverItsTimestamp() {
let pool = [
station("base", price: 199.9, ageDays: 1),
station("fresh", price: 180.9, ageDays: 1),
station("old", price: 175.9, ageDays: 40),
station("ancient", price: 170.9, ageDays: 250),
station("undated", price: 165.9, ageDays: nil)
]
let journeys = distanceProvider(["base": 0.8, "fresh": 1.0, "old": 1.4, "ancient": 1.8, "undated": 2.2])
let ranked = FuelSavingsEstimator.ranked(pool, fuel: .e10, baseline: pool[0],
settings: settings, amount: settings.preferredAmount,
journeyMiles: journeys)
XCTAssertEqual(ranked.map(\.id).sorted(), ["ancient", "base", "fresh", "old", "undated"])
for station in pool {
let result = FuelSavingsEstimator.availability(
station: station, fuel: .e10, baseline: pool[0], settings: settings,
amount: settings.preferredAmount,
journey: journeys(station), baselineJourney: straightLine(0.8)
)?.result
XCTAssertNotNil(result, "\(station.id) still shows a Best Value row")
}
}
func testCheapestAndClosestOrdersAreUnaffectedByTimestampAge() {
// Cheapest sorts on pump price, Closest on distance — the only inputs are
// prices and distances, so no age combination changes either order.
let specs: [(String, Double, Double)] = [("a", 199.9, 0.8), ("b", 129.9, 30), ("c", 170.9, 1.2)]
for ages in [[1.0, 1.0, 1.0], [250.0, 250.0, 250.0]] {
let pool = zip(specs, ages).map { spec, age in
station(spec.0, price: spec.1, ageDays: age)
}
let journeys = distanceProvider(Dictionary(uniqueKeysWithValues:
zip(specs.map(\.0), specs.map(\.2))))
let cheapestFirst = pool.sorted { lhs, rhs in
let left = lhs.prices[.e10] ?? .infinity
let right = rhs.prices[.e10] ?? .infinity
if left != right { return left < right }
return (journeys(lhs)?.miles ?? .infinity) < (journeys(rhs)?.miles ?? .infinity)
}
XCTAssertEqual(cheapestFirst.map(\.id), ["b", "c", "a"])
let closestFirst = pool.sorted { lhs, rhs in
let left = journeys(lhs)?.miles ?? .infinity
let right = journeys(rhs)?.miles ?? .infinity
if left != right { return left < right }
return (lhs.prices[.e10] ?? .infinity) < (rhs.prices[.e10] ?? .infinity)
}
XCTAssertEqual(closestFirst.map(\.id), ["a", "c", "b"])
}
}
// MARK: - The bundled / offline dataset
func testBundledDatasetWithMonthOldTimestampsStillRecommendsBestValue() {
// The bundled dump ships one pull of the whole UK feed, so every station
// arrives with the same months-old timestamp. Best Value must still
// recommend — it used to read "unavailable" for the entire offline list.
var specs: [(String, Double, Double, Double?)] = [("base", 171.9, 0.8, 90),
("pricier-near", 170.9, 1.2, 200),
("cheap-far", 149.9, 40, 250),
("dear-near", 179.9, 1.6, nil),
("old-undated", 160.9, 5.0, 240)]
let pool = specs.map { station($0.0, price: $0.1, ageDays: $0.3) }
let journeys = distanceProvider(Dictionary(uniqueKeysWithValues:
specs.map { ($0.0, $0.2) }))
let ranked = FuelSavingsEstimator.ranked(pool, fuel: .e10, baseline: pool[0],
settings: settings, amount: settings.preferredAmount,
journeyMiles: journeys)
let savings = pool.map { station in
(station.id, FuelSavingsEstimator.availability(
station: station, fuel: .e10, baseline: pool[0], settings: settings,
amount: settings.preferredAmount, journey: journeys(station), baselineJourney: straightLine(0.8)
)?.result?.netSavingGBP ?? -Double.infinity)
}
let expectedWinner = savings.max { $0.1 < $1.1 }?.0
XCTAssertEqual(ranked.first?.id, expectedWinner,
"the offline list is still ordered by net saving")
XCTAssertNotNil(ranked.first?.prices[.e10], "the top station has a price to show")
XCTAssertGreaterThan(savings.first { $0.0 == expectedWinner }?.1 ?? -1, 0,
"and that recommendation carries a real saving")
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ private enum WatchDistanceUnit: String, Codable {
func format(km: Double) -> String { func format(km: Double) -> String {
switch self { switch self {
case .miles: case .miles:
return String(format: "%.1f mi", km * 0.621371) return String(format: "%.1f mi", km / 1.609344)
case .kilometers: case .kilometers:
return String(format: "%.1f km", km) return String(format: "%.1f km", km)
} }
+61 -8
View File
@@ -95,7 +95,8 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
data: FuelPriceWidgetEntryData( data: FuelPriceWidgetEntryData(
date: Date(), stations: Array(sample.prefix(8)), date: Date(), stations: Array(sample.prefix(8)),
fuel: .e10, sort: .cheapest, isFavourites: false, fuel: .e10, sort: .cheapest, isFavourites: false,
location: nil, locationSource: "none", unit: unit location: nil, locationSource: "none", unit: unit,
bestValueResult: nil
) )
) )
} }
@@ -146,8 +147,9 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
// Per-widget config: fuel + sort + distance come from THIS widget instance. // Per-widget config: fuel + sort + distance come from THIS widget instance.
let fuel = FuelType(rawValue: configuration.fuel.rawValue) ?? .e10 let fuel = FuelType(rawValue: configuration.fuel.rawValue) ?? .e10
let isFavourites = configuration.sort == .favourites let isFavourites = configuration.sort == .favourites
let sort: SortMode = configuration.sort == .closest ? .closest : .cheapest let sort: SortMode = configuration.sort == .closest ? .closest :
let radiusKM = Double(configuration.distance.miles) * 1.60934 (configuration.sort == .worthTheDrive ? .worthTheDrive : .cheapest)
let radiusKM = Double(configuration.distance.miles) * FuelSavingsCalculator.kilometresPerMile
// 1) Try a fresh location fix (bounded to a few seconds). The fix's own // 1) Try a fresh location fix (bounded to a few seconds). The fix's own
// accuracy is kept: the extension runs its own CLLocationManager and is // accuracy is kept: the extension runs its own CLLocationManager and is
@@ -200,6 +202,7 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
// 3) Load + order stations per widget mode. // 3) Load + order stations per widget mode.
let ordered: [FuelStation] let ordered: [FuelStation]
var bestValueResult: FuelSavingsResult?
if isFavourites { if isFavourites {
let favourites = FuelStore.loadFavourites() let favourites = FuelStore.loadFavourites()
.filter { $0.station.prices[$0.fuel] != nil } .filter { $0.station.prices[$0.fuel] != nil }
@@ -265,7 +268,7 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
let filtered = stations.filter { $0.prices[fuel] != nil } let filtered = stations.filter { $0.prices[fuel] != nil }
switch sort { switch sort {
case .closest: case .closest:
// Nearest first; price only breaks ties. // Closest first; price only breaks ties.
ordered = filtered.sorted { lhs, rhs in ordered = filtered.sorted { lhs, rhs in
if let origin { if let origin {
let lDist = FuelStore.displayDistanceKM(station: lhs, userLat: origin.lat, userLng: origin.lng) let lDist = FuelStore.displayDistanceKM(station: lhs, userLat: origin.lat, userLng: origin.lng)
@@ -274,9 +277,59 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
} }
return lhs.prices[fuel]! < rhs.prices[fuel]! return lhs.prices[fuel]! < rhs.prices[fuel]!
} }
case .cheapest, .worthTheDrive: case .worthTheDrive:
// Cheapest first; distance only breaks ties. Worth-the-Drive is app-only; guard let origin else {
// widgets fall back to cheapest ordering if a stored config ever carries it. ordered = filtered.sorted { $0.prices[fuel]! < $1.prices[fuel]! }
break
}
let journey: (FuelStation) -> FuelSavingsJourney? = { station in
if let meters = FuelStore.roadJourneyMeters(for: station, userLat: origin.lat, userLng: origin.lng) {
let confidence: JourneyConfidence = FuelStore.hasMeasuredReturnRoadDistance(
for: station, userLat: origin.lat, userLng: origin.lng
) ? .confirmed : .estimated
return FuelSavingsJourney(
miles: meters / FuelSavingsCalculator.metresPerMile,
basis: .roadRoute,
confidence: confidence
)
}
return FuelSavingsJourney(
miles: FuelStore.displayDistanceKM(station: station, userLat: origin.lat, userLng: origin.lng) /
FuelSavingsCalculator.kilometresPerMile * 2,
basis: .straightLine,
confidence: .estimated
)
}
let settings = FuelStore.loadFuelSavingsSettings()
guard settings.isConfigured else {
ordered = filtered.sorted { $0.prices[fuel]! < $1.prices[fuel]! }
break
}
let amount = settings.preferredAmount
let baseline = FuelSavingsEstimator.baselineStation(filtered, fuel: fuel, journeyMiles: journey)
let ranked = FuelSavingsEstimator.ranked(
filtered,
fuel: fuel,
baseline: baseline,
settings: settings,
amount: amount,
journeyMiles: journey
)
ordered = ranked
if let first = ranked.first, let baseline {
let baselineJourney = journey(baseline)
let result = FuelSavingsEstimator.availability(
station: first,
fuel: fuel,
baseline: baseline,
settings: settings,
amount: amount,
journey: journey(first),
baselineJourney: baselineJourney
)
bestValueResult = result?.result
}
case .cheapest:
ordered = filtered.sorted { lhs, rhs in ordered = filtered.sorted { lhs, rhs in
let lPrice = lhs.prices[fuel]! let lPrice = lhs.prices[fuel]!
let rPrice = rhs.prices[fuel]! let rPrice = rhs.prices[fuel]!
@@ -295,7 +348,7 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
date: Date(), stations: Array(ordered.prefix(8)), date: Date(), stations: Array(ordered.prefix(8)),
fuel: fuel, sort: sort, isFavourites: isFavourites, fuel: fuel, sort: sort, isFavourites: isFavourites,
location: origin, locationSource: source, location: origin, locationSource: source,
unit: unit unit: unit, bestValueResult: bestValueResult
) )
), originSource) ), originSource)
} }
+10
View File
@@ -30,6 +30,7 @@ enum WidgetFuel: String, AppEnum, CaseIterable, Codable {
enum WidgetSort: String, AppEnum, CaseIterable, Codable { enum WidgetSort: String, AppEnum, CaseIterable, Codable {
case cheapest case cheapest
case closest case closest
case worthTheDrive
case favourites case favourites
static var typeDisplayRepresentation: TypeDisplayRepresentation = "Sort by" static var typeDisplayRepresentation: TypeDisplayRepresentation = "Sort by"
@@ -37,6 +38,7 @@ enum WidgetSort: String, AppEnum, CaseIterable, Codable {
static var caseDisplayRepresentations: [WidgetSort: DisplayRepresentation] = [ static var caseDisplayRepresentations: [WidgetSort: DisplayRepresentation] = [
.cheapest: "Cheapest", .cheapest: "Cheapest",
.closest: "Closest", .closest: "Closest",
.worthTheDrive: "Best Value",
.favourites: "Favourites", .favourites: "Favourites",
] ]
} }
@@ -111,6 +113,13 @@ struct FuelBoardWidgetConfigurationIntent: WidgetConfigurationIntent, WidgetConf
\.$fuel \.$fuel
\.$sort \.$sort
} }
} otherwise: {
When(\.$sort, .equalTo, WidgetSort.worthTheDrive) {
Summary("Show \(\.$fuel) by \(\.$sort) within \(\.$distance)") {
\.$fuel
\.$sort
\.$distance
}
} otherwise: { } otherwise: {
Summary("Show \(\.$fuel) by \(\.$sort)") { Summary("Show \(\.$fuel) by \(\.$sort)") {
\.$fuel \.$fuel
@@ -119,4 +128,5 @@ struct FuelBoardWidgetConfigurationIntent: WidgetConfigurationIntent, WidgetConf
} }
} }
} }
}
} }
+101
View File
@@ -0,0 +1,101 @@
import Foundation
enum FuelPriceTimestamp {
static func parse(_ value: String?) -> Date? {
guard let value, !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter.date(from: value) ?? {
formatter.formatOptions = [.withInternetDateTime]
return formatter.date(from: value)
}()
}
}
/// Station-level price freshness — informational only.
///
/// The relay publishes ONE `price_updated` per station, derived from the
/// GOV.UK Fuel Finder field `price_last_updated` as the MAXIMUM across the
/// fuel grades it maps. It is therefore a station-level figure and never a
/// verified timestamp for the grade the user has selected, so every label
/// describes the station's price information rather than one fuel.
///
/// Age excludes nothing: a station with a valid price is ranked on that price
/// however old its timestamp is. `outdatedAge` only decides whether More info
/// adds a discreet "May be outdated" note.
enum FuelPriceFreshness {
/// Price information older than this is flagged as possibly out of date.
/// A display threshold only — it gates nothing.
static let outdatedAge: TimeInterval = 30 * 24 * 60 * 60
/// Tolerated clock skew. A timestamp further into the future than this is
/// unusable (a feed error), never silently treated as "just now".
static let futureTolerance: TimeInterval = 5 * 60
/// Ages beyond this are unusable rather than displayed. It also keeps the
/// day count inside `Int`, so an absurd epoch cannot trap.
static let maximumAge: TimeInterval = 365 * 24 * 60 * 60 * 10
enum Status: Equatable {
/// Readable timestamp within `outdatedAge`.
case fresh
/// Readable timestamp older than `outdatedAge`.
case outdated
/// The record carries no timestamp.
case unknown
/// A timestamp is present but unreadable, or implausibly in the future.
case invalid
}
struct Assessment: Equatable {
let status: Status
/// Age in seconds. nil exactly when the timestamp is unusable, so no
/// caller can print an age that was never measured.
let age: TimeInterval?
var isOutdated: Bool { status == .outdated }
/// The one age More info reports. Missing or unreadable timestamps read
/// "Not provided" rather than implying freshness.
var updateAgeLabel: String {
guard let age else {
return String(localized: "Not provided", comment: "Price update time is missing")
}
return String(format: String(localized: "%@ ago", comment: "Price age, e.g. 28h ago"),
Self.ageText(age))
}
/// Discreet flag for price information past `outdatedAge`. nil while the
/// information is fresh, and nil when there is nothing to measure.
var outdatedNotice: String? {
guard status == .outdated else { return nil }
return String(localized: "May be outdated",
comment: "Station price information older than 30 days")
}
/// Compact age: minutes under an hour, hours under two days, then days.
static func ageText(_ age: TimeInterval) -> String {
let minutes = max(0, Int(age / 60))
if minutes < 60 { return "\(minutes)m" }
let hours = minutes / 60
if hours < 48 { return "\(hours)h" }
return "\(hours / 24)d"
}
}
/// The station's own timestamp. Deliberately takes no fuel: there is one
/// figure per station and every grade reads the same one, so the policy
/// cannot differ between fuels.
static func assessment(for station: FuelStation, now: Date = Date()) -> Assessment {
assessment(priceUpdated: station.priceUpdated, now: now)
}
static func assessment(priceUpdated: TimeInterval?, now: Date = Date()) -> Assessment {
guard let priceUpdated else { return Assessment(status: .unknown, age: nil) }
guard priceUpdated.isFinite else { return Assessment(status: .invalid, age: nil) }
let age = now.timeIntervalSince1970 - priceUpdated
guard age.isFinite, age >= -futureTolerance, age <= maximumAge else {
return Assessment(status: .invalid, age: nil)
}
let boundedAge = max(0, age)
return Assessment(status: boundedAge > outdatedAge ? .outdated : .fresh, age: boundedAge)
}
}
+20 -1
View File
@@ -38,7 +38,7 @@ enum FuelPriceProvider {
lat: relay.lat ?? 0, lat: relay.lat ?? 0,
lng: relay.lng ?? 0, lng: relay.lng ?? 0,
prices: relay.allPrices, prices: relay.allPrices,
priceUpdated: nil priceUpdated: relay.priceUpdatedDate?.timeIntervalSince1970
) )
} }
} }
@@ -65,6 +65,15 @@ enum FuelPriceProvider {
return result return result
} }
static func fuelType(for grade: String) -> FuelType? {
switch grade.uppercased() {
case "E10": return .e10
case "E5": return .e5
case "DIESEL", "B7", "B7S", "B7P", "B10": return .diesel
default: return nil
}
}
/// Decodes mirror envelope metadata (source, dataset update time) — the /// Decodes mirror envelope metadata (source, dataset update time) — the
/// About section shows these so the user can see which data source is /// About section shows these so the user can see which data source is
/// live and how fresh the GOV.UK data itself is. The fields are additive /// live and how fresh the GOV.UK data itself is. The fields are additive
@@ -106,6 +115,16 @@ private struct MirrorResponse: Codable {
let lng: Double? let lng: Double?
let price: Double? let price: Double?
let prices: [String: Double]? let prices: [String: Double]?
let priceUpdated: String?
enum CodingKeys: String, CodingKey {
case id, name, brand, address, postcode, lat, lng, price, prices
case priceUpdated = "price_updated"
}
var priceUpdatedDate: Date? {
FuelPriceTimestamp.parse(priceUpdated)
}
/// Map mirror grade keys (E5/E10/DIESEL) to FuelType for ALL fuels the /// Map mirror grade keys (E5/E10/DIESEL) to FuelType for ALL fuels the
/// station sells — one fetch populates every fuel tab. Defensive guard: /// station sells — one fetch populates every fuel tab. Defensive guard:
+27 -6
View File
@@ -29,11 +29,12 @@ struct FuelPriceWidgetEntryData {
let date: Date let date: Date
let stations: [FuelStation] // already filtered + sorted per config let stations: [FuelStation] // already filtered + sorted per config
let fuel: FuelType let fuel: FuelType
let sort: SortMode // per-widget: cheapest | closest let sort: SortMode // per-widget: cheapest | closest | Best Value
let isFavourites: Bool // favourites mode: pinned stations, cheapest-first let isFavourites: Bool // favourites mode: pinned stations
let location: Coordinate? let location: Coordinate?
let locationSource: String // "live" | "cached" | "none" let locationSource: String // "live" | "cached" | "none"
let unit: DistanceUnit // user's display unit for distances let unit: DistanceUnit // user's display unit for distances
let bestValueResult: FuelSavingsResult? // only populated for the small Best Value face
} }
/// The widget face, parameterised by family so the app can preview it. /// The widget face, parameterised by family so the app can preview it.
@@ -67,9 +68,11 @@ struct FuelPriceWidgetContent: View {
private var heading: String { private var heading: String {
if entry.isFavourites { return "Favourite \(entry.fuel.displayName)" } if entry.isFavourites { return "Favourite \(entry.fuel.displayName)" }
return entry.sort == .closest switch entry.sort {
? "Closest \(entry.fuel.displayName)" case .closest: return "Closest \(entry.fuel.displayName)"
: "Cheapest \(entry.fuel.displayName)" case .worthTheDrive: return "Best Value \(entry.fuel.displayName)"
case .cheapest: return "Cheapest \(entry.fuel.displayName)"
}
} }
private var singleStation: some View { private var singleStation: some View {
@@ -85,9 +88,27 @@ struct FuelPriceWidgetContent: View {
Text(station.name) Text(station.name)
.font(.headline) .font(.headline)
.lineLimit(1) .lineLimit(1)
if entry.sort == .worthTheDrive, let result = entry.bestValueResult {
Text(result.headline(compact: true))
.font(.title3.weight(.bold))
.lineLimit(1)
Text(result.status == .baseline ? "your baseline" : "vs closest station")
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if entry.sort == .worthTheDrive {
if let price = station.prices[entry.fuel] { if let price = station.prices[entry.fuel] {
FuelStore.priceTextAttributed(price, size: 26, weight: .bold, color: .green) FuelStore.priceTextAttributed(price, size: 26, weight: .bold, color: .green)
} }
if entry.location == nil {
Text("Best Value unavailable · location needed")
.font(.caption2)
.foregroundStyle(.orange)
.lineLimit(2)
}
} else if let price = station.prices[entry.fuel] {
FuelStore.priceTextAttributed(price, size: 26, weight: .bold, color: .green)
}
if let location = entry.location { if let location = entry.location {
let distance = FuelStore.stationDistanceDisplay( let distance = FuelStore.stationDistanceDisplay(
station: station, userLat: location.lat, userLng: location.lng station: station, userLat: location.lat, userLng: location.lng
@@ -126,7 +147,7 @@ struct FuelPriceWidgetContent: View {
.font(.caption2) .font(.caption2)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
Spacer() Spacer()
Text(entry.isFavourites ? "cheapest first" Text(entry.isFavourites ? "your order"
: (entry.locationSource == "none" ? "by price" : "near you")) : (entry.locationSource == "none" ? "by price" : "near you"))
.font(.caption2) .font(.caption2)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
+63 -13
View File
@@ -82,6 +82,7 @@ enum JourneyConfidence: String, Codable, Equatable {
struct FuelSavingsResult: Codable, Equatable { struct FuelSavingsResult: Codable, Equatable {
let fillLitres: Double let fillLitres: Double
let grossSavingGBP: Double let grossSavingGBP: Double
let extraFuelLitres: Double
let extraDrivingCostGBP: Double let extraDrivingCostGBP: Double
let extraDistanceMiles: Double let extraDistanceMiles: Double
let netSavingGBP: Double let netSavingGBP: Double
@@ -91,6 +92,7 @@ struct FuelSavingsResult: Codable, Equatable {
init(fillLitres: Double, init(fillLitres: Double,
grossSavingGBP: Double, grossSavingGBP: Double,
extraFuelLitres: Double = 0,
extraDrivingCostGBP: Double, extraDrivingCostGBP: Double,
extraDistanceMiles: Double, extraDistanceMiles: Double,
netSavingGBP: Double, netSavingGBP: Double,
@@ -99,6 +101,7 @@ struct FuelSavingsResult: Codable, Equatable {
journeyConfidence: JourneyConfidence? = nil) { journeyConfidence: JourneyConfidence? = nil) {
self.fillLitres = fillLitres self.fillLitres = fillLitres
self.grossSavingGBP = grossSavingGBP self.grossSavingGBP = grossSavingGBP
self.extraFuelLitres = extraFuelLitres
self.extraDrivingCostGBP = extraDrivingCostGBP self.extraDrivingCostGBP = extraDrivingCostGBP
self.extraDistanceMiles = extraDistanceMiles self.extraDistanceMiles = extraDistanceMiles
self.netSavingGBP = netSavingGBP self.netSavingGBP = netSavingGBP
@@ -140,6 +143,13 @@ enum FuelSavingsFormat {
: "\(distanceText) extra return travel" : "\(distanceText) extra return travel"
} }
/// Compact comparison copy kept outside the coloured verdict capsule.
/// "Closest" refers to the existing shortest-journey baseline selection;
/// it does not claim a straight-line comparison.
static func comparisonLabel(status: FuelSavingsStatus) -> String {
status == .baseline ? "your baseline" : "vs closest station"
}
/// VoiceOver form of `extraTravelLabel`. The abbreviation and the unit suffix /// VoiceOver form of `extraTravelLabel`. The abbreviation and the unit suffix
/// are spoken as words ("Approximately 6.4 miles extra return travel") because /// are spoken as words ("Approximately 6.4 miles extra return travel") because
/// synthesizers render "Approx." and "mi" inconsistently. /// synthesizers render "Approx." and "mi" inconsistently.
@@ -174,6 +184,7 @@ extension FuelSavingsResult {
FuelSavingsResult( FuelSavingsResult(
fillLitres: fillLitres, fillLitres: fillLitres,
grossSavingGBP: 0, grossSavingGBP: 0,
extraFuelLitres: 0,
extraDrivingCostGBP: 0, extraDrivingCostGBP: 0,
extraDistanceMiles: 0, extraDistanceMiles: 0,
netSavingGBP: 0, netSavingGBP: 0,
@@ -199,9 +210,9 @@ extension FuelSavingsResult {
case .breakEven: case .breakEven:
return Self.breakEvenHeadline return Self.breakEvenHeadline
case .worthTheDrive: case .worthTheDrive:
return "\(prefix)\(FuelSavingsFormat.money(netSavingGBP)) better off after travel" return "\(prefix)Save \(FuelSavingsFormat.money(netSavingGBP))"
case .notWorthTheDrive: case .notWorthTheDrive:
return "\(prefix)\(FuelSavingsFormat.money(abs(netSavingGBP))) worse off after travel" return "\(prefix)Costs \(FuelSavingsFormat.money(abs(netSavingGBP))) more"
} }
} }
@@ -211,13 +222,11 @@ extension FuelSavingsResult {
headline().replacingOccurrences(of: "Approx. ", with: "Approximately ") headline().replacingOccurrences(of: "Approx. ", with: "Approximately ")
} }
/// Row capsule copy: the headline, plus what the baseline row IS. Without the /// Row capsule copy. The baseline relationship is shown as secondary text
/// suffix the baseline capsule just repeated the status word above it /// beside the capsule in the station listing and detail summary, so the
/// ("Closest station" twice) and said nothing about the saving being measured /// capsule itself contains only the verdict.
/// against it.
func capsuleHeadline() -> String { func capsuleHeadline() -> String {
let headline = headline(compact: true) headline(compact: true)
return status == .baseline ? "\(headline) · your baseline" : headline
} }
} }
@@ -253,6 +262,29 @@ struct FuelSavingsRankedStation: Equatable {
let pricePencePerLitre: Double let pricePencePerLitre: Double
} }
/// Which recommendation badge a station listing row shows, if any.
///
/// Presentation only — no new rules: the BEST VALUE qualification reuses the
/// app's existing Best Value gate (the user's alert threshold, the same figure
/// `FuelSavingsCalculator.bestValueAlertCandidate` is given) and CHEAPEST
/// reuses the caller's existing "cheapest in range" flag (the station behind
/// `topStationID`). One badge per row: a station that is both the cheapest and
/// worth the drive shows BEST VALUE, the stronger of the two.
enum StationRecommendationBadge: Equatable {
case bestValue
case cheapest
static func badge(netSavingGBP: Double?,
isCheapest: Bool,
bestValueThresholdGBP: Double) -> StationRecommendationBadge? {
if let netSavingGBP, netSavingGBP.isFinite, bestValueThresholdGBP.isFinite,
netSavingGBP >= bestValueThresholdGBP {
return .bestValue
}
return isCheapest ? .cheapest : nil
}
}
struct BestValueAlertCandidate: Equatable { struct BestValueAlertCandidate: Equatable {
let station: FuelStation let station: FuelStation
let result: FuelSavingsResult let result: FuelSavingsResult
@@ -321,16 +353,29 @@ enum FuelSavingsCalculator {
distanceMiles / mpg * imperialGallonLitres distanceMiles / mpg * imperialGallonLitres
} }
static func fillLitres(amount: FuelSavingsFillAmount, baselinePricePencePerLitre: Double) throws -> Double { static func fillLitres(amount: FuelSavingsFillAmount, pricePencePerLitre: Double) throws -> Double {
guard amount.isValid else { throw FuelSavingsError.invalidAmount } guard amount.isValid else { throw FuelSavingsError.invalidAmount }
switch amount.unit { switch amount.unit {
case .litres: case .litres:
return amount.value return amount.value
case .pounds: case .pounds:
guard baselinePricePencePerLitre.isFinite, baselinePricePencePerLitre > 0 else { guard pricePencePerLitre.isFinite, pricePencePerLitre > 0 else {
throw FuelSavingsError.invalidPrice throw FuelSavingsError.invalidPrice
} }
return amount.value / (baselinePricePencePerLitre / 100.0) return amount.value / (pricePencePerLitre / 100.0)
}
}
/// Changing between a per-candidate monetary budget and a fixed litre
/// quantity has no lossless conversion across all stations. Start a new
/// comparison at that mode's stated default; the UI must tell the user
/// explicitly that the comparison basis changed and invite adjustment.
static func newComparisonAmount(afterSwitching amount: FuelSavingsFillAmount,
to unit: FuelSavingsFillUnit) -> FuelSavingsFillAmount {
guard amount.unit != unit else { return amount }
switch unit {
case .pounds: return FuelSavingsFillAmount(value: 40, unit: .pounds)
case .litres: return FuelSavingsFillAmount(value: 30, unit: .litres)
} }
} }
@@ -376,7 +421,7 @@ enum FuelSavingsCalculator {
baselineJourneyMiles >= 0, candidateJourneyMiles >= 0 else { baselineJourneyMiles >= 0, candidateJourneyMiles >= 0 else {
throw FuelSavingsError.invalidDistance throw FuelSavingsError.invalidDistance
} }
let fillLitres = try fillLitres(amount: amount, baselinePricePencePerLitre: baselinePricePencePerLitre) let fillLitres = try fillLitres(amount: amount, pricePencePerLitre: candidatePricePencePerLitre)
let baselinePriceGBP = baselinePricePencePerLitre / 100.0 let baselinePriceGBP = baselinePricePencePerLitre / 100.0
let candidatePriceGBP = candidatePricePencePerLitre / 100.0 let candidatePriceGBP = candidatePricePencePerLitre / 100.0
let grossSaving = fillLitres * (baselinePriceGBP - candidatePriceGBP) let grossSaving = fillLitres * (baselinePriceGBP - candidatePriceGBP)
@@ -395,6 +440,7 @@ enum FuelSavingsCalculator {
return FuelSavingsResult( return FuelSavingsResult(
fillLitres: fillLitres, fillLitres: fillLitres,
grossSavingGBP: grossSaving, grossSavingGBP: grossSaving,
extraFuelLitres: extraFuelLitres,
extraDrivingCostGBP: extraFuelCost, extraDrivingCostGBP: extraFuelCost,
extraDistanceMiles: extraDistance, extraDistanceMiles: extraDistance,
netSavingGBP: netSaving, netSavingGBP: netSaving,
@@ -572,7 +618,11 @@ enum FuelSavingsEstimator {
journeys[station.id] = journey journeys[station.id] = journey
} }
} }
let baselineJourney = baseline.flatMap { journeys[$0.id] } // The baseline is normally in the pool, so this is the same lookup it has
// always been; asking for its journey directly covers the case where the
// list being ranked is filtered tighter than the baseline was chosen from,
// which would otherwise mark every row unavailable.
let baselineJourney = baseline.flatMap { journeys[$0.id] ?? journeyMiles($0) }
let ranked = stations.map { station -> FuelSavingsRankedStation in let ranked = stations.map { station -> FuelSavingsRankedStation in
let journey = journeys[station.id] let journey = journeys[station.id]
let availability = availability(station: station, let availability = availability(station: station,
+114 -30
View File
@@ -183,13 +183,13 @@ enum DistanceUnit: String, Codable, CaseIterable, Identifiable {
/// shown in this unit, rounded to a whole number for picker labels: /// shown in this unit, rounded to a whole number for picker labels:
/// 5 miles -> "5" (miles unit) or "8" (km unit). /// 5 miles -> "5" (miles unit) or "8" (km unit).
func displayMiles(_ miles: Int) -> Int { func displayMiles(_ miles: Int) -> Int {
Int(fromKM(Double(miles) * 1.60934).rounded()) Int(fromKM(Double(miles) * FuelSavingsCalculator.kilometresPerMile).rounded())
} }
/// Convert a value expressed in this unit to km. /// Convert a value expressed in this unit to km.
func toKM(_ value: Double) -> Double { func toKM(_ value: Double) -> Double {
switch self { switch self {
case .miles: return value * 1.60934 case .miles: return value * FuelSavingsCalculator.kilometresPerMile
case .kilometers: return value case .kilometers: return value
} }
} }
@@ -197,7 +197,7 @@ enum DistanceUnit: String, Codable, CaseIterable, Identifiable {
/// Convert a km value to this unit. /// Convert a km value to this unit.
func fromKM(_ km: Double) -> Double { func fromKM(_ km: Double) -> Double {
switch self { switch self {
case .miles: return km * 0.621371 case .miles: return km / FuelSavingsCalculator.kilometresPerMile
case .kilometers: return km case .kilometers: return km
} }
} }
@@ -273,8 +273,56 @@ struct FuelStation: Identifiable, Codable, Equatable {
let lng: Double let lng: Double
/// Price per fuel type in pence per litre. Missing type = station doesn't sell it. /// Price per fuel type in pence per litre. Missing type = station doesn't sell it.
let prices: [FuelType: Double] let prices: [FuelType: Double]
/// Updated timestamp (seconds since 1970) — nil for sample data. /// Station-level price timestamp (seconds since 1970): the relay's
/// `price_updated`, i.e. the newest price submission across the grades it
/// maps — never a per-grade time. nil when the source omits it (sample data).
let priceUpdated: TimeInterval? let priceUpdated: TimeInterval?
init(id: String, name: String, brand: String, address: String, postcode: String,
lat: Double, lng: Double, prices: [FuelType: Double],
priceUpdated: TimeInterval?) {
self.id = id
self.name = name
self.brand = brand
self.address = address
self.postcode = postcode
self.lat = lat
self.lng = lng
self.prices = prices
self.priceUpdated = priceUpdated
}
private enum CodingKeys: String, CodingKey {
case id, name, brand, address, postcode, lat, lng, prices
case priceUpdated = "priceUpdated"
case priceUpdatedSnake = "price_updated"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(String.self, forKey: .id)
name = try values.decode(String.self, forKey: .name)
brand = try values.decode(String.self, forKey: .brand)
address = try values.decode(String.self, forKey: .address)
postcode = try values.decode(String.self, forKey: .postcode)
lat = try values.decode(Double.self, forKey: .lat)
lng = try values.decode(Double.self, forKey: .lng)
prices = try values.decode([FuelType: Double].self, forKey: .prices)
priceUpdated = try values.decodeIfPresent(TimeInterval.self, forKey: .priceUpdated)
?? values.decodeIfPresent(TimeInterval.self, forKey: .priceUpdatedSnake)
}
func encode(to encoder: Encoder) throws {
var values = encoder.container(keyedBy: CodingKeys.self)
try values.encode(id, forKey: .id)
try values.encode(name, forKey: .name)
try values.encode(brand, forKey: .brand)
try values.encode(address, forKey: .address)
try values.encode(postcode, forKey: .postcode)
try values.encode(lat, forKey: .lat)
try values.encode(lng, forKey: .lng)
try values.encode(prices, forKey: .prices)
try values.encodeIfPresent(priceUpdated, forKey: .priceUpdated)
}
/// Cheap haversine distance to a location, in km. /// Cheap haversine distance to a location, in km.
func distanceKM(to lat2: Double, lng2: Double) -> Double { func distanceKM(to lat2: Double, lng2: Double) -> Double {
@@ -663,7 +711,16 @@ struct FuelStore {
saveString(mode.rawValue, service: alertsModeKey) saveString(mode.rawValue, service: alertsModeKey)
} }
static let bestValueAlertThresholdOptionsGBP: [Double] = [0.5, 1.0, 2.0, 5.0] /// The Best Value gate's options, in 50p steps from 50p to £5. The gate is
/// the same figure for the listing's BEST VALUE badges and for the alert, so
/// its granularity decides how finely the two can be tuned: the old four
/// values (50p, £1, £2, £5) made £2.50 and £3 unreachable, and a whole extra
/// detour's worth of saving sat between £1 and £2. Multiples of 0.5 are
/// exactly representable, so the stored value and the picker's tags cannot
/// drift apart.
static let bestValueAlertThresholdOptionsGBP: [Double] = [
0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0
]
static func loadAlertsBestValueThresholdGBP() -> Double { static func loadAlertsBestValueThresholdGBP() -> Double {
if let raw = loadString(service: alertsBestValueThresholdKey), if let raw = loadString(service: alertsBestValueThresholdKey),
@@ -979,7 +1036,7 @@ struct FuelStore {
/// "Follow search" caps the geofence at 8 miles so a 10/15-mile Stations /// "Follow search" caps the geofence at 8 miles so a 10/15-mile Stations
/// search never creates huge region-monitoring circles. /// search never creates huge region-monitoring circles.
static let alertFollowCapKM: Double = 8 * 1.60934 static let alertFollowCapKM: Double = 8 * FuelSavingsCalculator.kilometresPerMile
/// The effective alert radius: the manual radius, or — when alerts follow /// The effective alert radius: the manual radius, or — when alerts follow
/// the Stations-tab search — that distance (miles, converted via the /// the Stations-tab search — that distance (miles, converted via the
@@ -1618,10 +1675,22 @@ struct FuelStore {
// what the rows show. // what the rows show.
if accurateDistancesEnabled, if accurateDistancesEnabled,
accurateDistancesReady(userLat: userLat, userLng: userLng), accurateDistancesReady(userLat: userLat, userLng: userLng),
let meters = roadDistanceMeters(for: station, userLat: userLat, userLng: userLng) { let entry = roadDistanceEntry(for: station, userLat: userLat, userLng: userLng) {
return StationDistanceDisplay(km: meters / 1000.0, isApproximate: false) let returnKM = (entry.meters + (entry.returnMeters ?? entry.meters)) / 1000.0
return StationDistanceDisplay(
km: entry.meters / 1000.0,
isApproximate: false,
returnKM: returnKM,
returnIsApproximate: entry.returnMeters == nil
)
} }
return StationDistanceDisplay(km: station.distanceKM(to: userLat, lng2: userLng), isApproximate: true) let km = station.distanceKM(to: userLat, lng2: userLng)
return StationDistanceDisplay(
km: km,
isApproximate: true,
returnKM: km * 2,
returnIsApproximate: true
)
} }
/// Radius test on the SAME distance the UI shows. Filtering straight-line /// Radius test on the SAME distance the UI shows. Filtering straight-line
@@ -1710,35 +1779,50 @@ struct RoadDistanceDiagnostics: Equatable {
/// road distance or the straight-line fallback. The confidence travels WITH the /// road distance or the straight-line fallback. The confidence travels WITH the
/// value, so a label can never claim a confidence the figure doesn't have. /// value, so a label can never claim a confidence the figure doesn't have.
struct StationDistanceDisplay: Equatable { struct StationDistanceDisplay: Equatable {
let km: Double let km: Double
let isApproximate: Bool let isApproximate: Bool
let returnKM: Double
let returnIsApproximate: Bool
/// Row/sheet label: a straight-line fallback is marked "Approx." so a figure init(km: Double,
/// that is NOT a routed road distance can never be read as one, and a cached isApproximate: Bool,
/// road distance stays a bare figure. It updates by itself once routing lands, returnKM: Double? = nil,
/// because `FuelStore.stationDistanceDisplay` re-reads the cache every call. returnIsApproximate: Bool? = nil) {
func label(unit: DistanceUnit) -> String { self.km = km
self.isApproximate = isApproximate
self.returnKM = returnKM ?? km * 2
self.returnIsApproximate = returnIsApproximate ?? isApproximate
}
/// Row/sheet label: a straight-line fallback is marked "Approx." so a figure
/// that is NOT a routed road distance can never be read as one, and a cached
/// road distance stays a bare figure. It updates by itself once routing lands,
/// because `FuelStore.stationDistanceDisplay` re-reads the cache every call.
func label(unit: DistanceUnit) -> String {
let text = unit.format(km) let text = unit.format(km)
return isApproximate ? "Approx. \(text)" : text return isApproximate ? "Approx. \(text)" : text
} }
/// Row/sheet label that keeps the one-way station distance primary, then /// Row/sheet label that keeps the one-way station distance primary, then
/// adds the out-and-back distance in brackets. This matches Best Value's /// adds the independently measured or estimated out-and-back distance.
/// "extra return travel" basis without changing the actual distance model. func labelWithReturn(unit: DistanceUnit) -> String {
func labelWithReturn(unit: DistanceUnit) -> String { let returnText = unit.format(returnKM)
"\(label(unit: unit)) (\(unit.format(km * 2)) return)" let returnLabel = returnIsApproximate ? "Approx. \(returnText)" : returnText
} return "\(label(unit: unit)) (\(returnLabel) return)"
}
/// VoiceOver form of `label(unit:)`. /// VoiceOver form of `label(unit:)`.
func spokenLabel(unit: DistanceUnit) -> String { func spokenLabel(unit: DistanceUnit) -> String {
let text = unit.spoken(km) let text = unit.spoken(km)
return isApproximate ? "Approximately \(text)" : text return isApproximate ? "Approximately \(text)" : text
} }
/// VoiceOver form of `labelWithReturn(unit:)`. /// VoiceOver form of `labelWithReturn(unit:)`.
func spokenLabelWithReturn(unit: DistanceUnit) -> String { func spokenLabelWithReturn(unit: DistanceUnit) -> String {
"\(spokenLabel(unit: unit)), \(unit.spoken(km * 2)) return" let returnText = unit.spoken(returnKM)
} let returnLabel = returnIsApproximate ? "Approximately \(returnText)" : returnText
return "\(spokenLabel(unit: unit)), \(returnLabel) return"
}
} }
/// Cached Apple-Maps road distances for nearby stations (see /// Cached Apple-Maps road distances for nearby stations (see
+1 -1
View File
@@ -21,7 +21,7 @@ enum SiriCheapestLookup {
lng: Double, lng: Double,
withinMiles: Double withinMiles: Double
) -> FuelStation? { ) -> FuelStation? {
let radiusKM = withinMiles * 1.60934 let radiusKM = withinMiles * FuelSavingsCalculator.kilometresPerMile
// Same radius rule as the app list: the distance the answer would SHOW // Same radius rule as the app list: the distance the answer would SHOW
// (cached road route where there is one). // (cached road route where there is one).
return stations return stations