// The person's notification switches, as this device holds them. // // **DEVICE-LOCAL and never synced.** They live under `@cotton:notifprefs`, and // they are not a record: nothing about them is // an op, and a second phone has its own. That is why the crate takes them as an // ARGUMENT on every reminder call and never looks for a place to keep them — // inventing a home for a preference the person's file does not hold would be // the engine deciding something the app already decided. // // **4j owns the SHAPE; `/settings#notifications` is 4h's screen.** This file is // what that screen writes and what the reminder pass reads, so the two lanes // meet on a struct rather than on a dictionary. // // Everything defaults ON, and that is not the same as // "notifications default on": nothing can be scheduled until the OS grants // permission, and Cotton never asks for that at boot. These switches describe // what a person would want IF they said yes; the OS prompt is the real gate. // // The one entry point stored data comes in through is ``NotificationPrefs // /init(stored:)``, which is deliberately suspicious of TYPES and not only of // shape — a stored `"yes"` is not `true`. The crate's `migrate_notification_prefs` is the authority and // applies the same rules on the way in; this side exists so the SCREEN reads // the same defaults the engine would. import Foundation /// What a person can switch off, one line at a time. /// /// `alarms` is the alarm-mirror category. Its toggle lives here even though /// `/alarms` is 4e's subsystem, so the shape does not change under it later. public enum NotificationCategory: String, CaseIterable, Sendable, Codable { case reminders case events case birthdays case alarms } /// What a scheduled notification is ABOUT — one kind per record type. /// /// The same four the crate declares (`cotton_core::rules::reminders /// ::NotificationKind`), and the same four a fired notification carries back in /// its `{kind, id}` payload. There is no mood kind: nothing asks about mood on /// a schedule (owner, 11 Oct 2026). public enum NotificationKind: String, CaseIterable, Sendable, Codable { case todo case event case birthday case alarm /// Which switch governs this kind. A `switch` and not a map, so a new kind /// is a COMPILE error rather than a kind that quietly goes ungoverned. public var category: NotificationCategory { switch self { case .todo: return .reminders case .event: return .events case .birthday: return .birthdays case .alarm: return .alarms } } } /// The switches, and the record of whether the one inline prompt was spent. /// /// `askedAt` shares the record because it is the same question's other half: /// "have we ever asked?" travels with "what did they say?". One key, one write /// path, no chance of the two halves disagreeing. public struct NotificationPrefs: Codable, Equatable, Sendable { /// The master switch. Off means the engine schedules nothing at all — /// which is a WIPE and not a no-op, because an empty desired set cancels /// everything already standing. public var enabled: Bool /// One flag per ``NotificationCategory``, held TOTAL. public var categories: [NotificationCategory: Bool] /// ISO instant of the ONE inline permission ask, or `nil` if never asked. public var askedAt: String? // These are DELIVERY switches only — whether this device notifies. // Nothing asks about mood on a schedule (owner, 11 Oct 2026), so a stored // `mood` switch or `moodHour` from an older build is simply not read. /// The storage key. Declared in ``StandingKey`` rather than written out /// here, because that list is what `NoStandingTests` reads: a key this app /// writes and does not declare is exactly what that guard exists to catch. public static let storageKey = StandingKey.notificationPrefs.rawValue public static let defaults = NotificationPrefs() public init( enabled: Bool = true, categories: [NotificationCategory: Bool]? = nil, askedAt: String? = nil ) { self.enabled = enabled self.categories = categories ?? Dictionary( uniqueKeysWithValues: NotificationCategory.allCases.map { ($0, true) } ) self.askedAt = askedAt } /// Is this kind switched on right now? Master AND its own category. /// /// **A MISSING KEY IS OFF.** The map is held total by ``init(stored:)``, so /// in practice there is no hole; the question is which way this fails if /// there ever is one. Defaulting to on would SCHEDULE against a /// preference record that does not say to — a person who turned a category /// off and whose stored map then lost the key would start being reminded /// again, silently. Failing closed costs a reminder nobody asked for; /// failing open sends one somebody declined. public func enabled(_ kind: NotificationKind) -> Bool { enabled && categories[kind.category] == true } // ── Reading what was stored ─────────────────────────────────────────── /// The ONE entry point stored preferences come in through. /// /// Anything malformed or partial resolves to the defaults for the parts it /// cannot supply, exactly as a fresh install gets them. public init(stored: JSONValue?) { let defaults = NotificationPrefs() guard let stored else { self = defaults return } var categories: [NotificationCategory: Bool] = [:] for category in NotificationCategory.allCases { categories[category] = stored["categories"]?[category.rawValue]?.bool ?? true } self.init( enabled: stored["enabled"]?.bool ?? defaults.enabled, categories: categories, askedAt: stored["askedAt"]?.string ) } /// The prefs as the crate reads them — the argument on every reminder call. public var wire: JSONValue { var bag: [String: JSONValue] = [ "enabled": .bool(enabled), "categories": .object( Dictionary( uniqueKeysWithValues: categories.map { ($0.key.rawValue, JSONValue.bool($0.value)) } ) ), ] if let askedAt { bag["askedAt"] = .string(askedAt) } return .object(bag) } // ── `Codable`, over the wire shape rather than over the Swift one ───── // // A `[NotificationCategory: Bool]` encodes as an ARRAY under Swift's own // rules for a non-`String` key, and the stored record is a JSON object // keyed by category. So the coding is written out against that object // rather than synthesised. private enum CodingKeys: String, CodingKey { case enabled, categories, askedAt } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let stored = try values.decodeIfPresent([String: Bool].self, forKey: .categories) ?? [:] var categories: [NotificationCategory: Bool] = [:] for category in NotificationCategory.allCases { categories[category] = stored[category.rawValue] ?? true } self.init( enabled: try values.decodeIfPresent(Bool.self, forKey: .enabled) ?? true, categories: categories, askedAt: try values.decodeIfPresent(String.self, forKey: .askedAt) ) } public func encode(to encoder: Encoder) throws { var values = encoder.container(keyedBy: CodingKeys.self) try values.encode(enabled, forKey: .enabled) try values.encode( Dictionary(uniqueKeysWithValues: categories.map { ($0.key.rawValue, $0.value) }), forKey: .categories ) try values.encodeIfPresent(askedAt, forKey: .askedAt) } } /// Where the switches are kept between launches. /// /// A protocol because the reminder pass and the ask both read them, and a test /// must be able to hand them a record without touching `UserDefaults` — which /// is process-wide state two tests running in one bundle would share. public protocol NotificationPrefsStore: Sendable { func read() -> NotificationPrefs func write(_ prefs: NotificationPrefs) } /// The real store: JSON under ``NotificationPrefs/storageKey``. /// /// The app group's suite, because `Standing.swift` says there is ONE — the /// share extension reads the same container, and a second suite is a /// second place to look for a preference. Nothing outside the app reads these /// switches today; the rule is about where a preference LIVES, not about who /// happens to want one. /// /// `@unchecked Sendable` because `UserDefaults` is not marked `Sendable` and is /// documented thread-safe — the promise being made by hand is Apple's own, and /// it is made here rather than avoided because a store that could not cross a /// thread would have to be read on the main actor, which is where a reminder /// pass must not be. public struct DefaultsNotificationPrefsStore: NotificationPrefsStore, @unchecked Sendable { private let defaults: UserDefaults public init(defaults: UserDefaults = .standard) { self.defaults = defaults } public func read() -> NotificationPrefs { guard let text = defaults.string(forKey: NotificationPrefs.storageKey), let value = try? JSONDecoder().decode(JSONValue.self, from: Data(text.utf8)) else { return NotificationPrefs.defaults } return NotificationPrefs(stored: value) } public func write(_ prefs: NotificationPrefs) { guard let data = try? JSONEncoder().encode(prefs), let text = String(data: data, encoding: .utf8) else { return } defaults.set(text, forKey: NotificationPrefs.storageKey) } } /// A store held in memory, for a test and for nothing else. public final class InMemoryNotificationPrefsStore: NotificationPrefsStore, @unchecked Sendable { private let lock = NSLock() private var held: NotificationPrefs public init(_ prefs: NotificationPrefs = .defaults) { held = prefs } public func read() -> NotificationPrefs { lock.lock() defer { lock.unlock() } return held } public func write(_ prefs: NotificationPrefs) { lock.lock() defer { lock.unlock() } held = prefs } }