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
32 changed files with 1673 additions and 331 deletions
+8 -8
View File
@@ -533,7 +533,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = Config/WatchApp.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -599,7 +599,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = Config/WatchApp.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -663,7 +663,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -728,7 +728,7 @@
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
ENABLE_PREVIEWS = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -826,7 +826,7 @@
CODE_SIGN_ENTITLEMENTS = Config/App.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/App-Info.plist";
@@ -851,7 +851,7 @@
CODE_SIGN_ENTITLEMENTS = Config/App.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/App-Info.plist";
@@ -875,7 +875,7 @@
APPLICATION_EXTENSION_API_ONLY = YES;
CODE_SIGN_ENTITLEMENTS = Config/Widget.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/Widget-Info.plist";
@@ -900,7 +900,7 @@
APPLICATION_EXTENSION_API_ONLY = YES;
CODE_SIGN_ENTITLEMENTS = Config/Widget.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 26;
CURRENT_PROJECT_VERSION = 27;
DEVELOPMENT_TEAM = F3BE6NE7U3;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "Config/Widget-Info.plist";
+11 -11
View File
@@ -13,7 +13,10 @@ struct AlertsView: View {
@Binding var radius: Double // stored in km (monitor + storage)
@Binding var fuel: FuelType // the fuel alerts monitor for
@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
@Binding var favouriteDropEnabled: Bool
@Binding var favouriteDropFuel: FuelType
@@ -178,16 +181,13 @@ struct AlertsView: View {
.font(.caption)
.foregroundStyle(.secondary)
if alertMode == .bestValue {
Picker(String(localized: "Minimum saving", comment: "Best Value alert threshold picker title"), selection: $bestValueThresholdGBP) {
ForEach(FuelStore.bestValueAlertThresholdOptionsGBP, id: \.self) { value in
Text(FuelSavingsFormat.money(value)).tag(value)
}
}
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)
.foregroundStyle(.secondary)
}
// The threshold is edited in Settings → Fuel Savings: it
// labels station rows BEST VALUE as well as gating this
// 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)))
.font(.caption)
.foregroundStyle(.secondary)
}
if enabled && monitoredCount == 0 {
Text(String(localized: "No stations monitored yet — open the Stations tab to load prices first.", comment: "No monitored stations hint"))
+303 -134
View File
@@ -29,7 +29,7 @@ struct ContentView: View {
@State private var sortMode: SortMode = ContentView.qaSortModeOverride(default: FuelStore.loadSortMode())
@State private var stationLimit: Int = ContentView.qaStationRadiusOverride(default: FuelStore.loadStationLimit())
@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 fuelSavingsSettings: FuelSavingsSettings = FuelStore.loadFuelSavingsSettings()
@State private var sessionFuelSavingsAmount: FuelSavingsFillAmount = FuelStore.loadFuelSavingsSettings().preferredAmount
@@ -114,6 +114,21 @@ struct ContentView: View {
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 {
#if DEBUG
let args = ProcessInfo.processInfo.arguments
@@ -161,7 +176,7 @@ struct ContentView: View {
}
private func installLocationUpdateHook() {
locationManager.onLocationUpdate = { [weak monitor] in
locationManager.onLocationUpdate = {
self.updateAlertMonitor()
// The Live Activity follows the same wake-ups — this hook
// 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
/// all AGAIN to fill the per-station map. Both now share one result.
///
/// The baseline is chosen with EXACTLY the loop and guards of
/// `FuelSavingsEstimator.baselineStation`, so the row labelled "Closest
/// station" cannot move — and it is still selected when the feature is
/// unconfigured (it names that row), while the maps are only built when the
/// labels will actually be shown.
/// The baseline is chosen with the same journey guards as
/// `FuelSavingsEstimator.baselineStation` when configured; with the feature
/// off, the ordinary Closest station still names that row.
private func savingsScaffold() -> (baseline: FuelStation?, journeys: [String: FuelSavingsJourney]) {
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 bestStation: FuelStation?
var bestMiles = Double.infinity
for station in stations where station.prices[selectedFuel] != nil {
guard let journey = savingsJourneyMiles(for: station, location: location) else { continue }
if configured { journeys[station.id] = journey }
let miles = journey.miles
guard miles.isFinite, miles >= 0 else { continue }
if miles < bestMiles {
bestMiles = miles
bestStation = station
if let journey = savingsJourneyMiles(for: station, location: location) {
journeys[station.id] = journey
}
}
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
@@ -1119,6 +1133,11 @@ struct ContentView: View {
}
}
.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
// effective sort follows automatically (no stored sort is touched).
#if DEBUG
@@ -1523,7 +1542,6 @@ struct ContentView: View {
fuelSavingsSettings: fuelSavingsSettings,
fuelSavingsAmount: $sessionFuelSavingsAmount,
savingsForStation: savingsLookup(baseline: baselineStation, journeys: scaffold.journeys),
savingsBaselineStationName: baselineStation?.name,
journeyDiagnosticsForStation: { station in journeyDiagnostics(for: station, baseline: baselineStation) },
onToggleFavourite: toggleFavourite,
onRefresh: { await refresh(force: true) }
@@ -1545,7 +1563,6 @@ struct ContentView: View {
fuelSavingsSettings: fuelSavingsSettings,
fuelSavingsAmount: $sessionFuelSavingsAmount,
savingsForStation: savingsLookup(baseline: baselineStation, journeys: scaffold.journeys),
savingsBaselineStationName: baselineStation?.name,
journeyDiagnosticsForStation: { station in journeyDiagnostics(for: station, baseline: baselineStation) },
onToggleFavourite: toggleFavourite,
onReorder: reorderFavourites,
@@ -1562,7 +1579,7 @@ struct ContentView: View {
radius: $alertsRadius,
fuel: $alertsFuel,
alertMode: $alertsMode,
bestValueThresholdGBP: $alertsBestValueThresholdGBP,
bestValueThresholdGBP: alertsBestValueThresholdGBP,
bestValueConfigured: fuelSavingsSettings.isConfigured,
favouriteDropEnabled: $favouriteDropAlertsEnabled,
favouriteDropFuel: $favouriteDropAlertsFuel,
@@ -1590,6 +1607,7 @@ struct ContentView: View {
priceDisplayStyle: $priceDisplayStyle,
stationTapAction: $stationTapAction,
fuelSavingsSettings: $fuelSavingsSettings,
bestValueThresholdGBP: $alertsBestValueThresholdGBP,
dataRefreshMode: $dataRefreshMode,
alertsFuel: alertsFuel,
alertsRadiusKM: alertsRadius,
@@ -1773,20 +1791,47 @@ struct StationRow: View {
let distanceUnit: DistanceUnit
let priceDisplayStyle: PriceDisplayStyle
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 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 fuelSavings: FuelSavingsAvailability?
/// The session fill-up figure (the one the adjustment control edits). The
/// compact banner does not print it today, but a row that carried a hard
/// zero would print "for £0" the moment it did — pass the real figure.
var fuelSavingsAmount: FuelSavingsFillAmount = FuelSavingsSettings.defaultPreferredAmount
/// The user's Best Value alert threshold — the app's existing gate for
/// calling a saving worth the drive, so a row labels itself BEST VALUE by
/// exactly the rule the alerts already use. Read per row (the alert path
/// reads it per evaluation too); pass explicitly to inject a value.
var bestValueThresholdGBP: Double = FuelStore.loadAlertsBestValueThresholdGBP()
var onToggleFavourite: () -> Void = {}
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 {
guard let price = station.prices[fuel], let baselinePrice else { return .gray }
switch RAGRating.rating(price: price, cheapest: baselinePrice) {
@@ -1812,6 +1857,26 @@ struct StationRow: View {
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() {
switch tapAction {
case .openMap:
@@ -1828,132 +1893,236 @@ struct StationRow: View {
}
var body: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 12) {
// LEFT — round brand logo (or generic fuel pump fallback)
Group {
if let asset = station.brandImageName {
Image(asset)
.resizable()
.scaledToFit()
.padding(5)
} else {
Image(systemName: "fuelpump.fill")
.font(.system(size: 22, weight: .semibold))
.foregroundStyle(Color.black.opacity(0.82))
}
}
.frame(width: 46, height: 46)
.background(Circle().fill(Color.white))
.clipShape(Circle())
.overlay(Circle().stroke(Color.primary.opacity(0.10), lineWidth: 1))
.shadow(color: .black.opacity(0.08), radius: 2, y: 1)
// Two sections, one hairline: station identity on the left, price and
// savings on the right. No wrapper VStack and no full-width verdict
// 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 {
if let asset = station.brandImageName {
Image(asset)
.resizable()
.scaledToFit()
.padding(5)
} else {
Image(systemName: "fuelpump.fill")
.font(.system(size: 22, weight: .semibold))
.foregroundStyle(Color.black.opacity(0.82))
}
}
.frame(width: 46, height: 46)
.background(Circle().fill(Color.white))
.clipShape(Circle())
.overlay(Circle().stroke(Color.primary.opacity(0.10), lineWidth: 1))
.shadow(color: .black.opacity(0.08), radius: 2, y: 1)
// MIDDLE — name, full address, distance
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 6) {
Text(station.name)
.font(.headline)
.lineLimit(1)
.truncationMode(.tail)
ForEach(StationNotice.notices(for: station)) { notice in
Image(systemName: notice.symbolName)
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
.accessibilityLabel(notice.title)
favouriteButton
}
// Name, full address, distance
VStack(alignment: .leading, spacing: 2) {
// 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)
.font(.headline)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
ForEach(StationNotice.notices(for: station)) { notice in
Image(systemName: notice.symbolName)
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
.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,
postcode: station.postcode,
name: station.name))
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
if let location {
let distance = FuelStore.stationDistanceDisplay(
station: station, userLat: location.lat, userLng: location.lng
)
// 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)
.monospacedDigit()
}
.foregroundStyle(.secondary)
.accessibilityElement(children: .ignore)
.accessibilityLabel(distance.spokenLabel(unit: distanceUnit))
}
}
Text(StationAddressLine.display(address: station.address,
postcode: station.postcode,
name: station.name))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.tail)
if let location {
let distance = FuelStore.stationDistanceDisplay(
station: station, userLat: location.lat, userLng: location.lng
)
Text(distance.labelWithReturn(unit: distanceUnit))
.font(.caption2)
.foregroundStyle(.secondary)
.monospacedDigit()
.accessibilityLabel(distance.spokenLabelWithReturn(unit: distanceUnit))
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxWidth: .infinity, alignment: .leading)
.containerRelativeFrame(.horizontal, alignment: .leading) { length, _ in
length * Self.leftSectionShare
}
// 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()
// 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] {
HStack(spacing: 5) {
Circle()
.fill(ragColor)
.frame(width: 8, height: 8)
FuelStore.priceTextAttributed(price, style: priceDisplayStyle, size: 20, 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)
.minimumScaleFactor(0.8)
}
FuelStore.priceTextAttributed(price, style: priceDisplayStyle,
size: priceSize, weight: .bold)
.lineLimit(1)
.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)
}
}
// FAR RIGHT — favourite star
Button {
onToggleFavourite()
} label: {
Image(systemName: isFavourite ? "star.fill" : "star")
.foregroundStyle(isFavourite ? .yellow : .secondary)
}
.buttonStyle(.borderless)
}
if fuelSavings != nil {
// Full-width verdict banner under the row. Inline in the middle
// column it truncated ("Approx. £2.75 better off after tra…")
// because the
// price block squeezes that column — and the verdict is the
// point of this sort mode, so it gets its own line.
FuelSavingsSummaryView(
availability: fuelSavings,
amount: fuelSavingsAmount,
baselineStationName: nil,
compact: true,
distanceUnit: distanceUnit
)
}
.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)
}
/// 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 {
onToggleFavourite()
} label: {
Image(systemName: isFavourite ? "star.fill" : "star")
.foregroundStyle(isFavourite ? .yellow : .secondary)
}
.buttonStyle(.borderless)
}
/// The savings capsule plus the comparison it is measured against. The
/// capsule itself is the shared verdict view, so a row, the detail sheet and
/// the compact summary cannot drift apart. The comparison label sits beside
/// the capsule only where there is width for both.
@ViewBuilder
private func savingsCapsule(_ result: FuelSavingsResult) -> some View {
let comparison = Text(FuelSavingsFormat.comparisonLabel(status: result.status))
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1)
// 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
}
}
}
/// 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
+5 -13
View File
@@ -21,10 +21,9 @@ struct FavouritesView: View {
/// still never touches the Settings default.
let fuelSavingsSettings: FuelSavingsSettings
@Binding var fuelSavingsAmount: FuelSavingsFillAmount
/// Estimated saving for a favourite, against the nearest eligible station —
/// the same baseline and definition the Stations list uses.
/// Estimated saving for a favourite, against the closest station by
/// journey distance — the same baseline and definition the Stations list uses.
var savingsForStation: (FuelStation) -> FuelSavingsAvailability? = { _ in nil }
var savingsBaselineStationName: String?
var journeyDiagnosticsForStation: (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil }
var onToggleFavourite: (FuelStation, FuelType) -> Void = { _, _ in }
/// Persists a reordered favourites array (after drag-and-drop).
@@ -84,7 +83,6 @@ struct FavouritesView: View {
fuelSavingsSettings: FuelSavingsSettings = .defaults,
fuelSavingsAmount: Binding<FuelSavingsFillAmount>,
savingsForStation: @escaping (FuelStation) -> FuelSavingsAvailability? = { _ in nil },
savingsBaselineStationName: String? = nil,
journeyDiagnosticsForStation: @escaping (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil },
onToggleFavourite: @escaping (FuelStation, FuelType) -> Void = { _, _ in },
onReorder: @escaping ([FavouriteEntry]) -> Void = { _ in },
@@ -99,7 +97,6 @@ struct FavouritesView: View {
self.fuelSavingsSettings = fuelSavingsSettings
_fuelSavingsAmount = fuelSavingsAmount
self.savingsForStation = savingsForStation
self.savingsBaselineStationName = savingsBaselineStationName
self.journeyDiagnosticsForStation = journeyDiagnosticsForStation
self.onToggleFavourite = onToggleFavourite
self.onReorder = onReorder
@@ -147,12 +144,9 @@ struct FavouritesView: View {
if fuelSavingsSettings.isConfigured {
Section {
FuelSavingsAdjustmentView(
amount: $fuelSavingsAmount,
referencePricePencePerLitre: cheapestPrice
)
FuelSavingsAdjustmentView(amount: $fuelSavingsAmount)
} 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,
isTopResult: station.id == cheapest?.id,
isFavourite: activeFuelFavouriteIDs.contains(station.id),
topBadgeText: "CHEAPEST",
tapAction: stationTapAction,
fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount,
onToggleFavourite: { onToggleFavourite(station, activeFuel) },
onShowDetails: { detailStation = $0 }
)
@@ -219,9 +211,9 @@ struct FavouritesView: View {
station: station,
location: location,
distanceUnit: distanceUnit,
selectedFuel: activeFuel,
fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount,
savingsBaselineStationName: savingsBaselineStationName,
journeyDiagnostics: journeyDiagnosticsForStation(station),
// Every station listed here IS a favourite for the tab's
// fuel, so the star starts filled; tapping it unstars.
+94 -29
View File
@@ -2,7 +2,8 @@ import SwiftUI
struct FuelSavingsAdjustmentView: View {
@Binding var amount: FuelSavingsFillAmount
let referencePricePencePerLitre: Double?
@State private var unitChangeNotice: String?
private var range: ClosedRange<Double> {
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.")
.font(.caption2)
.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 },
set: { newUnit in
guard newUnit != amount.unit else { return }
if let referencePricePencePerLitre,
let converted = try? FuelSavingsCalculator.convert(amount: amount, to: newUnit, referencePricePencePerLitre: referencePricePencePerLitre) {
amount = converted
} else {
amount = FuelSavingsFillAmount(value: newUnit == .pounds ? 40 : 30, unit: newUnit)
}
// No one litre figure equals a budget at every candidate price.
// A unit change starts a new, explicitly labelled comparison.
amount = FuelSavingsCalculator.newComparisonAmount(afterSwitching: amount, to: newUnit)
unitChangeNotice = "New comparison basis — adjust the \(newUnit.displayName) amount to your intended fill-up."
}
)
}
@@ -73,13 +80,17 @@ struct FuelSavingsAdjustmentView: View {
struct FuelSavingsSummaryView: View {
let availability: FuelSavingsAvailability?
let amount: FuelSavingsFillAmount
let baselineStationName: String?
var baselineStationName: String? = nil
var compact: Bool = false
/// 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.
var distanceUnit: DistanceUnit = .miles
var showInfoAction: (() -> Void)? = nil
private func comparisonLabel(for result: FuelSavingsResult) -> String {
FuelSavingsFormat.comparisonLabel(status: result.status)
}
var body: some View {
switch availability {
case .available(let result):
@@ -93,8 +104,19 @@ struct FuelSavingsSummaryView: View {
// break even, blue baseline. lineLimit + minimumScaleFactor keep
// it to one line, so rows stay even.
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)
.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(
extraDistanceMiles: result.extraDistanceMiles,
unit: distanceUnit,
@@ -118,11 +140,27 @@ struct FuelSavingsSummaryView: View {
// room for. The old shape led with a status word + headline that
// matched neither the listing nor each other.
VStack(alignment: .leading, spacing: 10) {
capsule(for: result, compact: false)
.accessibilityLabel(accessibilityHeadline(for: result))
// 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)
.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(
extraDistanceMiles: result.extraDistanceMiles,
unit: distanceUnit,
@@ -134,11 +172,11 @@ struct FuelSavingsSummaryView: View {
.accessibilityLabel(spokenExtraTravel(for: result, fallback: extraTravel))
}
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)
.foregroundStyle(.secondary)
} else {
Text("Compared with \(baselineStationName ?? "your nearest station").")
Text(baselineStationName.map { "Compared with \($0)." } ?? "Compared with your closest station.")
.font(.caption)
.foregroundStyle(.secondary)
LabeledContent(
@@ -213,39 +251,66 @@ struct FuelSavingsSummaryView: View {
}
/// VoiceOver form of the verdict. `spokenHeadline()` spells "Approx." out for
/// estimated comparisons and leaves the plain words ("Break even", "Closest
/// station") alone — one source, so visible and spoken copy cannot drift.
/// and leaves the plain words ("Break even", "Closest station") alone —
/// one source, so visible and spoken copy cannot drift.
private func accessibilityHeadline(for result: FuelSavingsResult) -> String {
result.spokenHeadline()
}
/// The colour-coded verdict capsule — ONE implementation for the listing rows
/// and the detail sheet, so the verdict reads identically in both; 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.
/// The colour-coded verdict capsule lives in `FuelSavingsCapsule` — ONE
/// implementation for the listing rows, the detail sheet and this compact
/// summary, so the verdict reads identically everywhere; the sheet just
/// gets the larger font and padding.
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) {
Image(systemName: symbol(for: result.status))
Image(systemName: Self.symbol(for: result.status))
.accessibilityHidden(true)
Text(result.capsuleHeadline())
.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)
.foregroundStyle(capsuleColor(for: result.status))
.foregroundStyle(Self.color(for: result.status))
.padding(.horizontal, compact ? 8 : 12)
.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
/// 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 {
case .worthTheDrive: return .green
case .notWorthTheDrive: return .red
@@ -254,7 +319,7 @@ struct FuelSavingsSummaryView: View {
}
}
private func symbol(for status: FuelSavingsStatus) -> String {
static func symbol(for status: FuelSavingsStatus) -> String {
switch status {
case .worthTheDrive: return "checkmark.circle.fill"
case .breakEven: return "equal.circle.fill"
+3 -1
View File
@@ -14,8 +14,10 @@ struct HowBestValueSheet: View {
List {
Section {
VStack(alignment: .leading, spacing: 10) {
Text("Best Value compares each station with the closest one. It works out what you could save at the pump, then takes off the fuel used for the extra return journey.")
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)
}
+1 -1
View File
@@ -79,7 +79,7 @@ enum LiveActivityManager {
currentStartDate = nil
start(attributes: attributes, state: state)
} else {
Task { await current.update(using: state) }
Task { await current.update(ActivityContent(state: state, staleDate: nil)) }
}
} else {
start(attributes: attributes, state: state)
+2 -2
View File
@@ -111,7 +111,7 @@ struct OnboardingView: View {
.padding(.bottom, 16)
Text(String(localized: "Welcome to\nFuelBoard", comment: "Onboarding welcome title"))
.font(.title.bold())
.font(.largeTitle.bold())
.multilineTextAlignment(.center)
Text(String(localized: "The cheapest petrol, diesel and premium fuel near you — from the official UK Fuel Finder data.", comment: "Onboarding welcome subtitle"))
@@ -156,7 +156,7 @@ struct OnboardingView: View {
permissionStatusLabel(
granted: prompter.locationGranted,
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)
+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.
import Foundation
import CoreLocation
import MapKit
import UIKit
import WidgetKit
@@ -407,8 +408,14 @@ enum RoadDistanceService {
/// Driving distance (metres) between two coordinates via Apple Maps routing.
private static func roadMeters(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) async -> Double? {
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: from))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: to))
request.source = MKMapItem(
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.requestsAlternateRoutes = false
do {
+31 -5
View File
@@ -20,6 +20,12 @@ struct SettingsView: View {
@Binding var priceDisplayStyle: PriceDisplayStyle
@Binding var stationTapAction: StationTapAction
@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
/// The fuel + radius currently configured for alerts (mirrors the Alerts
/// 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
/// 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.
@State private var settingsUnitChangeNotice: String?
@FocusState private var focusedSavingsField: SavingsField?
private enum SavingsField: Hashable {
@@ -148,6 +155,25 @@ struct SettingsView: View {
step: FuelSavingsCalculator.fillAmountSliderStep(for: fuelSavingsSettings.preferredAmount.unit))
.accessibilityLabel("Typical fill-up")
.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 {
Text("Set a realistic UK MPG and fill-up amount before Best Value appears in sorting.")
.font(.caption)
@@ -285,7 +311,7 @@ struct SettingsView: View {
} header: {
Text("Debug")
} 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() }
@@ -709,10 +735,10 @@ struct SettingsView: View {
Binding(
get: { fuelSavingsSettings.preferredAmount.unit },
set: { newUnit in
fuelSavingsSettings.preferredAmount.unit = newUnit
if !fuelSavingsSettings.preferredAmount.isValid {
fuelSavingsSettings.preferredAmount.value = newUnit == .pounds ? 40 : 30
}
guard newUnit != fuelSavingsSettings.preferredAmount.unit else { return }
fuelSavingsSettings.preferredAmount = FuelSavingsCalculator.newComparisonAmount(
afterSwitching: fuelSavingsSettings.preferredAmount, to: newUnit)
settingsUnitChangeNotice = "New comparison basis — adjust the \(newUnit.displayName) amount to your intended fill-up."
persistFuelSavingsSettings()
}
)
+17
View File
@@ -17,6 +17,8 @@ struct StationDetailView: View {
let station: FuelStation
let location: Coordinate?
let distanceUnit: DistanceUnit
/// Fuel whose price is being shown by the surrounding station list.
var selectedFuel: FuelType = FuelStore.loadSelectedFuel()
var fuelSavings: FuelSavingsAvailability? = nil
var fuelSavingsAmount: FuelSavingsFillAmount = FuelSavingsSettings.defaultPreferredAmount
var savingsBaselineStationName: String? = nil
@@ -57,6 +59,18 @@ struct StationDetailView: View {
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
/// URL) the Directions button below uses, so the map and the button can
/// never point at two different places.
@@ -197,6 +211,9 @@ struct StationDetailView: View {
LabeledContent("Distance", value: distance.labelWithReturn(unit: distanceUnit))
.monospacedDigit()
}
LabeledContent("\(selectedFuel.displayName) price", value: selectedFuelPriceText)
.monospacedDigit()
StationPriceAgeView(assessment: priceFreshness)
ForEach(StationNotice.notices(for: station)) { notice in
Label(notice.title, systemImage: notice.symbolName)
.font(.subheadline.weight(.semibold))
+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)
}
}
}
}
+44 -38
View File
@@ -19,7 +19,6 @@ struct StationsView: View {
let fuelSavingsSettings: FuelSavingsSettings
@Binding var fuelSavingsAmount: FuelSavingsFillAmount
var savingsForStation: (FuelStation) -> FuelSavingsAvailability? = { _ in nil }
var savingsBaselineStationName: String?
var journeyDiagnosticsForStation: (FuelStation) -> FuelSavingsJourneyDiagnostics? = { _ in nil }
var onToggleFavourite: (FuelStation, FuelType) -> Void = { _, _ in }
var onRefresh: () async -> Void = {}
@@ -68,7 +67,7 @@ struct StationsView: View {
}
if location != nil {
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)"
}
@@ -94,7 +93,7 @@ struct StationsView: View {
}
.pickerStyle(.segmented)
// 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
// kept for when the user switches back to Cheapest.
.disabled(sortMode == .closest)
@@ -121,10 +120,7 @@ struct StationsView: View {
// stale stored sort mode must not keep the control on screen
// for a switched-off feature.
if sortMode == .worthTheDrive && fuelSavingsSettings.isConfigured {
FuelSavingsAdjustmentView(
amount: $fuelSavingsAmount,
referencePricePencePerLitre: baselinePrice
)
FuelSavingsAdjustmentView(amount: $fuelSavingsAmount)
}
if isLoading && stations.isEmpty {
@@ -149,22 +145,7 @@ struct StationsView: View {
.padding(.vertical, 4)
} else {
ForEach(Array(stations.prefix(visibleCount)), id: \.id) { station in
StationRow(
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 }
)
stationRow(station)
}
if visibleCount < stations.count {
@@ -260,6 +241,29 @@ struct StationsView: View {
}
}
.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 {
List {
Section {
@@ -340,21 +344,23 @@ struct StationsView: View {
}
.presentationDetents([.fraction(0.6)])
.presentationBackground(Color(UIColor.systemGroupedBackground))
}
.sheet(item: $detailStation) { station in
StationDetailView(
station: station,
location: location,
distanceUnit: distanceUnit,
fuelSavings: savingsForStation(station),
fuelSavingsAmount: fuelSavingsAmount,
savingsBaselineStationName: savingsBaselineStationName,
journeyDiagnostics: journeyDiagnosticsForStation(station),
isFavourite: favouriteIDs.contains(station.id),
onToggleFavourite: { onToggleFavourite(station, selectedFuel) }
)
}
}
}
private func stationRow(_ station: FuelStation) -> some View {
StationRow(
station: station,
fuel: selectedFuel,
location: location,
distanceUnit: distanceUnit,
priceDisplayStyle: priceDisplayStyle,
baselinePrice: baselinePrice,
isTopResult: station.id == topStationID,
isFavourite: favouriteIDs.contains(station.id),
tapAction: stationTapAction,
fuelSavings: savingsForStation(station),
onToggleFavourite: { onToggleFavourite(station, selectedFuel) },
onShowDetails: { detailStation = $0 }
)
}
private var availableSortModes: [SortMode] {
+3 -2
View File
@@ -76,7 +76,7 @@ struct WidgetMockScreen: View {
let location = FuelStore.loadLocation().map { Coordinate(lat: $0.lat, lng: $0.lng) }
// 5 miles — the widget config's default Distance. WidgetDistance itself
// 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 selling = all.filter { station in
guard station.prices[fuel] != nil else { return false }
@@ -94,7 +94,8 @@ struct WidgetMockScreen: View {
isFavourites: false,
location: location,
locationSource: location != nil ? "live" : "none",
unit: FuelStore.loadDistanceUnit()
unit: FuelStore.loadDistanceUnit(),
bestValueResult: nil
)
}
}
+22 -5
View File
@@ -10,9 +10,11 @@
"Settings" = "Settings";
"FuelBoard" = "FuelBoard";
"TOP" = "TOP";
"BEST VALUE" = "BEST VALUE";
"CHEAPEST" = "CHEAPEST";
/* 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.";
"%@ %@ — tap a station for directions." = "%@ %@ — tap a station for directions.";
"Fuel type" = "Fuel type";
@@ -36,7 +38,10 @@
"Remove from favourites" = "Remove from favourites";
"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 one. 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 one. 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." = "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.";
@@ -70,7 +75,6 @@
"More info" = "More info";
"Name" = "Name";
"Address" = "Address";
"Distance" = "Distance";
"Copies the postcode" = "Copies the postcode";
"Postcode copied" = "Postcode copied";
"Address: %@" = "Address: %@";
@@ -81,7 +85,7 @@
"Test alert notification (real data)" = "Test alert notification (real data)";
"Send plain test notification" = "Send plain test notification";
"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";
"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: %@";
@@ -139,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.";
"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.";
"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";
"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.";
@@ -205,6 +209,7 @@
"Best Value" = "Best Value";
"Total" = "Total";
"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 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.";
@@ -217,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.";
"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() {
// 5 miles ≈ 8.05 km (app uses × 1.60934)
XCTAssertEqual(5 * 1.60934, 8.0467, accuracy: 0.001)
// 262 km ≈ 162.8 miles (display uses × 0.621371)
XCTAssertEqual(262 * 0.621371, 162.8, accuracy: 0.1)
// 5 miles ≈ 8.05 km using the shared exact conversion
XCTAssertEqual(5 * FuelSavingsCalculator.kilometresPerMile, 8.04672, accuracy: 0.001)
// 262 km ≈ 162.8 miles using the shared exact conversion
XCTAssertEqual(262 / FuelSavingsCalculator.kilometresPerMile, 162.8, accuracy: 0.1)
}
}
@@ -267,14 +267,14 @@ final class FuelTypeLabelTests: XCTestCase {
}
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.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)
}
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")
}
}
@@ -400,7 +400,7 @@ final class AlertRadiusFollowTests: XCTestCase {
FuelStore.saveDistanceUnit(.miles)
FuelStore.saveStationLimit(5)
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,
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,
"fixture: the straight line must sit INSIDE the 10-mile radius")
XCTAssertGreaterThan(FuelStore.displayDistanceKM(station: far, userLat: sourceLat, userLng: sourceLng),
@@ -743,7 +743,7 @@ final class RoadDistanceCacheTests: XCTestCase {
userLat: sourceLat, userLng: sourceLng),
"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.
XCTAssertTrue(FuelStore.isWithinDisplayRadius(station: far, radiusKM: 15 * 1.60934,
XCTAssertTrue(FuelStore.isWithinDisplayRadius(station: far, radiusKM: 15 * FuelSavingsCalculator.kilometresPerMile,
userLat: sourceLat, userLng: sourceLng))
// …and an unknown station (no cached route) still tests its displayed
// 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")
XCTAssertEqual(confirmed.km, 3.2, accuracy: 0.0001)
XCTAssertEqual(confirmed.label(unit: .miles), "2.0 mi")
XCTAssertEqual(confirmed.labelWithReturn(unit: .miles), "2.0 mi (4.0 mi return)")
XCTAssertEqual(confirmed.labelWithReturn(unit: .kilometers), "3.2 km (6.4 km return)")
XCTAssertEqual(confirmed.labelWithReturn(unit: .miles), "2.0 mi (4.2 mi return)")
XCTAssertEqual(confirmed.labelWithReturn(unit: .kilometers), "3.2 km (6.8 km return)")
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)
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),
"Approx. " + DistanceUnit.miles.format(approximate.km))
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),
"Approximately " + DistanceUnit.kilometers.spoken(approximate.km))
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
@@ -961,7 +990,7 @@ final class RoadDistanceCacheTests: XCTestCase {
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")
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),
"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)
XCTAssertFalse(display.isApproximate)
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),
"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
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() {
XCTAssertEqual(FuelSavingsCalculator.imperialGallonLitres, 4.54609)
XCTAssertNotEqual(FuelSavingsCalculator.imperialGallonLitres, 3.785411784,
@@ -263,6 +299,23 @@ final class FuelSavingsCalculationAuditTests: XCTestCase {
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() {
// 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.
@@ -41,6 +41,42 @@ final class FuelSavingsEstimateTests: XCTestCase {
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() {
// 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.
@@ -454,6 +490,25 @@ final class FuelSavingsEstimateTests: XCTestCase {
// 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
/// figure is always miles, and converting by the current unit instead would
/// leave a km user's figure unlabelled and 1.6× too large.
@@ -486,7 +541,7 @@ final class FuelSavingsEstimateTests: XCTestCase {
netSavingGBP: 0,
status: .baseline
)
XCTAssertEqual(baseline.capsuleHeadline(), "Closest station · your baseline")
XCTAssertEqual(baseline.capsuleHeadline(), "Closest station")
let saving = FuelSavingsResult(
fillLitres: 30,
@@ -143,6 +143,15 @@ final class FuelSavingsCalculatorTests: 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() {
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)
@@ -150,3 +159,101 @@ final class FuelSavingsSettingsTests: XCTestCase {
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 {
switch self {
case .miles:
return String(format: "%.1f mi", km * 0.621371)
return String(format: "%.1f mi", km / 1.609344)
case .kilometers:
return String(format: "%.1f km", km)
}
+61 -8
View File
@@ -95,7 +95,8 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
data: FuelPriceWidgetEntryData(
date: Date(), stations: Array(sample.prefix(8)),
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.
let fuel = FuelType(rawValue: configuration.fuel.rawValue) ?? .e10
let isFavourites = configuration.sort == .favourites
let sort: SortMode = configuration.sort == .closest ? .closest : .cheapest
let radiusKM = Double(configuration.distance.miles) * 1.60934
let sort: SortMode = configuration.sort == .closest ? .closest :
(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
// 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.
let ordered: [FuelStation]
var bestValueResult: FuelSavingsResult?
if isFavourites {
let favourites = FuelStore.loadFavourites()
.filter { $0.station.prices[$0.fuel] != nil }
@@ -265,7 +268,7 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
let filtered = stations.filter { $0.prices[fuel] != nil }
switch sort {
case .closest:
// Nearest first; price only breaks ties.
// Closest first; price only breaks ties.
ordered = filtered.sorted { lhs, rhs in
if let origin {
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]!
}
case .cheapest, .worthTheDrive:
// Cheapest first; distance only breaks ties. Worth-the-Drive is app-only;
// widgets fall back to cheapest ordering if a stored config ever carries it.
case .worthTheDrive:
guard let origin else {
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
let lPrice = lhs.prices[fuel]!
let rPrice = rhs.prices[fuel]!
@@ -295,7 +348,7 @@ struct FuelPriceTimelineProvider<Configuration: WidgetConfigurationIntent & Widg
date: Date(), stations: Array(ordered.prefix(8)),
fuel: fuel, sort: sort, isFavourites: isFavourites,
location: origin, locationSource: source,
unit: unit
unit: unit, bestValueResult: bestValueResult
)
), originSource)
}
+13 -3
View File
@@ -30,6 +30,7 @@ enum WidgetFuel: String, AppEnum, CaseIterable, Codable {
enum WidgetSort: String, AppEnum, CaseIterable, Codable {
case cheapest
case closest
case worthTheDrive
case favourites
static var typeDisplayRepresentation: TypeDisplayRepresentation = "Sort by"
@@ -37,6 +38,7 @@ enum WidgetSort: String, AppEnum, CaseIterable, Codable {
static var caseDisplayRepresentations: [WidgetSort: DisplayRepresentation] = [
.cheapest: "Cheapest",
.closest: "Closest",
.worthTheDrive: "Best Value",
.favourites: "Favourites",
]
}
@@ -112,9 +114,17 @@ struct FuelBoardWidgetConfigurationIntent: WidgetConfigurationIntent, WidgetConf
\.$sort
}
} otherwise: {
Summary("Show \(\.$fuel) by \(\.$sort)") {
\.$fuel
\.$sort
When(\.$sort, .equalTo, WidgetSort.worthTheDrive) {
Summary("Show \(\.$fuel) by \(\.$sort) within \(\.$distance)") {
\.$fuel
\.$sort
\.$distance
}
} otherwise: {
Summary("Show \(\.$fuel) by \(\.$sort)") {
\.$fuel
\.$sort
}
}
}
}
+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,
lng: relay.lng ?? 0,
prices: relay.allPrices,
priceUpdated: nil
priceUpdated: relay.priceUpdatedDate?.timeIntervalSince1970
)
}
}
@@ -65,6 +65,15 @@ enum FuelPriceProvider {
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
/// 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
@@ -106,6 +115,16 @@ private struct MirrorResponse: Codable {
let lng: Double?
let price: 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
/// station sells — one fetch populates every fuel tab. Defensive guard:
+28 -7
View File
@@ -29,11 +29,12 @@ struct FuelPriceWidgetEntryData {
let date: Date
let stations: [FuelStation] // already filtered + sorted per config
let fuel: FuelType
let sort: SortMode // per-widget: cheapest | closest
let isFavourites: Bool // favourites mode: pinned stations, cheapest-first
let sort: SortMode // per-widget: cheapest | closest | Best Value
let isFavourites: Bool // favourites mode: pinned stations
let location: Coordinate?
let locationSource: String // "live" | "cached" | "none"
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.
@@ -67,9 +68,11 @@ struct FuelPriceWidgetContent: View {
private var heading: String {
if entry.isFavourites { return "Favourite \(entry.fuel.displayName)" }
return entry.sort == .closest
? "Closest \(entry.fuel.displayName)"
: "Cheapest \(entry.fuel.displayName)"
switch entry.sort {
case .closest: return "Closest \(entry.fuel.displayName)"
case .worthTheDrive: return "Best Value \(entry.fuel.displayName)"
case .cheapest: return "Cheapest \(entry.fuel.displayName)"
}
}
private var singleStation: some View {
@@ -85,7 +88,25 @@ struct FuelPriceWidgetContent: View {
Text(station.name)
.font(.headline)
.lineLimit(1)
if let price = station.prices[entry.fuel] {
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] {
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 {
@@ -126,7 +147,7 @@ struct FuelPriceWidgetContent: View {
.font(.caption2)
.foregroundStyle(.secondary)
Spacer()
Text(entry.isFavourites ? "cheapest first"
Text(entry.isFavourites ? "your order"
: (entry.locationSource == "none" ? "by price" : "near you"))
.font(.caption2)
.foregroundStyle(.secondary)
+52 -7
View File
@@ -143,6 +143,13 @@ enum FuelSavingsFormat {
: "\(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
/// are spoken as words ("Approximately 6.4 miles extra return travel") because
/// synthesizers render "Approx." and "mi" inconsistently.
@@ -215,13 +222,11 @@ extension FuelSavingsResult {
headline().replacingOccurrences(of: "Approx. ", with: "Approximately ")
}
/// Row capsule copy: the headline, plus what the baseline row IS. Without the
/// suffix the baseline capsule just repeated the status word above it
/// ("Closest station" twice) and said nothing about the saving being measured
/// against it.
/// Row capsule copy. The baseline relationship is shown as secondary text
/// beside the capsule in the station listing and detail summary, so the
/// capsule itself contains only the verdict.
func capsuleHeadline() -> String {
let headline = headline(compact: true)
return status == .baseline ? "\(headline) · your baseline" : headline
headline(compact: true)
}
}
@@ -257,6 +262,29 @@ struct FuelSavingsRankedStation: Equatable {
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 {
let station: FuelStation
let result: FuelSavingsResult
@@ -338,6 +366,19 @@ enum FuelSavingsCalculator {
}
}
/// 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)
}
}
static func convert(amount: FuelSavingsFillAmount,
to unit: FuelSavingsFillUnit,
referencePricePencePerLitre: Double) throws -> FuelSavingsFillAmount {
@@ -577,7 +618,11 @@ enum FuelSavingsEstimator {
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 journey = journeys[station.id]
let availability = availability(station: station,
+118 -34
View File
@@ -183,13 +183,13 @@ enum DistanceUnit: String, Codable, CaseIterable, Identifiable {
/// shown in this unit, rounded to a whole number for picker labels:
/// 5 miles -> "5" (miles unit) or "8" (km unit).
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.
func toKM(_ value: Double) -> Double {
switch self {
case .miles: return value * 1.60934
case .miles: return value * FuelSavingsCalculator.kilometresPerMile
case .kilometers: return value
}
}
@@ -197,7 +197,7 @@ enum DistanceUnit: String, Codable, CaseIterable, Identifiable {
/// Convert a km value to this unit.
func fromKM(_ km: Double) -> Double {
switch self {
case .miles: return km * 0.621371
case .miles: return km / FuelSavingsCalculator.kilometresPerMile
case .kilometers: return km
}
}
@@ -273,8 +273,56 @@ struct FuelStation: Identifiable, Codable, Equatable {
let lng: Double
/// Price per fuel type in pence per litre. Missing type = station doesn't sell it.
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?
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.
func distanceKM(to lat2: Double, lng2: Double) -> Double {
@@ -663,7 +711,16 @@ struct FuelStore {
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 {
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
/// 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 Stations-tab search — that distance (miles, converted via the
@@ -1618,10 +1675,22 @@ struct FuelStore {
// what the rows show.
if accurateDistancesEnabled,
accurateDistancesReady(userLat: userLat, userLng: userLng),
let meters = roadDistanceMeters(for: station, userLat: userLat, userLng: userLng) {
return StationDistanceDisplay(km: meters / 1000.0, isApproximate: false)
let entry = roadDistanceEntry(for: station, userLat: userLat, userLng: userLng) {
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
@@ -1710,35 +1779,50 @@ struct RoadDistanceDiagnostics: Equatable {
/// 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.
struct StationDistanceDisplay: Equatable {
let km: Double
let isApproximate: Bool
let km: Double
let isApproximate: Bool
let returnKM: Double
let returnIsApproximate: Bool
/// 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)
return isApproximate ? "Approx. \(text)" : text
}
init(km: Double,
isApproximate: Bool,
returnKM: Double? = nil,
returnIsApproximate: Bool? = nil) {
self.km = km
self.isApproximate = isApproximate
self.returnKM = returnKM ?? km * 2
self.returnIsApproximate = returnIsApproximate ?? isApproximate
}
/// 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
/// "extra return travel" basis without changing the actual distance model.
func labelWithReturn(unit: DistanceUnit) -> String {
"\(label(unit: unit)) (\(unit.format(km * 2)) return)"
}
/// 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)
return isApproximate ? "Approx. \(text)" : text
}
/// VoiceOver form of `label(unit:)`.
func spokenLabel(unit: DistanceUnit) -> String {
let text = unit.spoken(km)
return isApproximate ? "Approximately \(text)" : text
}
/// Row/sheet label that keeps the one-way station distance primary, then
/// adds the independently measured or estimated out-and-back distance.
func labelWithReturn(unit: DistanceUnit) -> String {
let returnText = unit.format(returnKM)
let returnLabel = returnIsApproximate ? "Approx. \(returnText)" : returnText
return "\(label(unit: unit)) (\(returnLabel) return)"
}
/// VoiceOver form of `labelWithReturn(unit:)`.
func spokenLabelWithReturn(unit: DistanceUnit) -> String {
"\(spokenLabel(unit: unit)), \(unit.spoken(km * 2)) return"
}
/// VoiceOver form of `label(unit:)`.
func spokenLabel(unit: DistanceUnit) -> String {
let text = unit.spoken(km)
return isApproximate ? "Approximately \(text)" : text
}
/// VoiceOver form of `labelWithReturn(unit:)`.
func spokenLabelWithReturn(unit: DistanceUnit) -> String {
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
+1 -1
View File
@@ -21,7 +21,7 @@ enum SiriCheapestLookup {
lng: Double,
withinMiles: Double
) -> FuelStation? {
let radiusKM = withinMiles * 1.60934
let radiusKM = withinMiles * FuelSavingsCalculator.kilometresPerMile
// Same radius rule as the app list: the distance the answer would SHOW
// (cached road route where there is one).
return stations