Repository Public
1import Foundation2import MCCCore34/// The three faces of the maintenance section.5enum MaintenanceScope: String, CaseIterable, Identifiable, Sendable {6 case month, agenda, notes7 var id: String { rawValue }8 var title: String { trDynamic("maintenance.scope." + rawValue) }9 static var dynamicKeys: [String] { allCases.map { "maintenance.scope." + $0.rawValue } }10}1112/// What a day cell of the month grid says about its occurrences: a count and the category symbols (shape, not13/// colour), plus whether one of them is in progress.14struct DayMarker: Equatable, Sendable {15 var count: Int16 var symbols: [String]17 var hasActive: Bool18}1920/// Pure logic of the calendar and of the notes. No server rule lives here: the server validates everything.21enum MaintenanceLogic {22 /// First day of the month `offset` months away from the month of `date` (crosses year boundaries).23 static func month(_ date: Date, offset: Int, calendar: Calendar) -> Date {24 let start = CalendarMath.startOfMonth(date, calendar: calendar)25 return calendar.date(byAdding: .month, value: offset, to: start) ?? start26 }2728 static func monthTitle(_ date: Date, calendar: Calendar) -> String {29 let f = DateFormatter()30 f.calendar = calendar31 f.locale = calendar.locale32 f.timeZone = calendar.timeZone33 f.setLocalizedDateFormatFromTemplate("MMMM yyyy")34 let s = f.string(from: date)35 return s.prefix(1).uppercased() + s.dropFirst()36 }3738 static func isSameMonth(_ a: Date, _ b: Date, calendar: Calendar) -> Bool {39 calendar.isDate(a, equalTo: b, toGranularity: .month)40 }4142 /// Marker of a day, or nil when nothing overlaps it.43 static func marker(on day: Date, in list: [API.MaintenanceOccurrence], calendar: Calendar) -> DayMarker? {44 let items = CalendarMath.occurrences(on: day, in: list, calendar: calendar)45 guard !items.isEmpty else { return nil }46 var symbols: [String] = []47 for o in items where !symbols.contains(o.window.category.symbol) { symbols.append(o.window.category.symbol) }48 return DayMarker(count: items.count, symbols: Array(symbols.prefix(2)), hasActive: items.contains { $0.active == true })49 }5051 /// The day selected by default when a month is shown: today when it is in that month, else the first day.52 static func defaultSelection(month: Date, today: Date, calendar: Calendar) -> Date {53 isSameMonth(month, today, calendar: calendar) ? calendar.startOfDay(for: today) : CalendarMath.startOfMonth(month, calendar: calendar)54 }5556 /// Pinned notes first, then the most recent first.57 static func sorted(_ notes: [API.MaintenanceNote]) -> [API.MaintenanceNote] {58 notes.sorted { a, b in59 if a.pinned != b.pinned { return a.pinned }60 if a.createdAt != b.createdAt { return a.createdAt > b.createdAt }61 return a.id < b.id62 }63 }6465 /// "nœud-a, nœud-b +3": aliases of the scope, unknown nodes counted but not invented.66 static func scopeSummary(nodeIDs: [String], limit: Int = 3, alias: (String) -> String?) -> String {67 guard !nodeIDs.isEmpty else { return tr("maintenance.scope_none") }68 let names = nodeIDs.compactMap(alias).sorted()69 let shown = names.prefix(limit)70 let rest = nodeIDs.count - shown.count71 if shown.isEmpty { return tr("maintenance.scope_count", nodeIDs.count) }72 return shown.joined(separator: ", ") + (rest > 0 ? " +\(rest)" : "")73 }7475 static func timeZone(_ identifier: String) -> TimeZone { TimeZone(identifier: identifier) ?? .current }7677 /// Time range in the window's own time zone, and in the device's when the two differ at that instant.78 static func timeRange(start: Date, end: Date, zoneID: String, local: TimeZone = .current, calendar: Calendar = CalendarMath.calendar()) -> (zone: String, local: String?) {79 let zone = timeZone(zoneID)80 func text(_ tz: TimeZone) -> String {81 var c = calendar82 c.timeZone = tz83 let sameDay = c.isDate(start, inSameDayAs: end)84 let a = Format.dateTime(start, timeZone: tz)85 let b = sameDay ? Format.time(end, timeZone: tz) : Format.dateTime(end, timeZone: tz)86 return a + " → " + b87 }88 let zoned = text(zone) + " (" + abbreviation(zone, at: start) + ")"89 if zone.secondsFromGMT(for: start) == local.secondsFromGMT(for: start) { return (zoned, nil) }90 return (zoned, text(local) + " (" + abbreviation(local, at: start) + ")")91 }9293 static func abbreviation(_ tz: TimeZone, at date: Date) -> String { tz.abbreviation(for: date) ?? tz.identifier }9495 /// Same wall-clock time in another time zone (the user changed the zone of a window being edited).96 static func reinterpret(_ date: Date, from: TimeZone, to: TimeZone) -> Date {97 var a = Calendar(identifier: .gregorian)98 a.timeZone = from99 var b = Calendar(identifier: .gregorian)100 b.timeZone = to101 let comps = a.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)102 return b.date(from: comps) ?? date103 }104105 /// Wall-clock date in `zone` (used by tests and by the default start).106 static func date(year: Int, month: Int, day: Int, hour: Int, minute: Int = 0, in zone: TimeZone) -> Date? {107 var c = Calendar(identifier: .gregorian)108 c.timeZone = zone109 return c.date(from: DateComponents(year: year, month: month, day: day, hour: hour, minute: minute))110 }111112 static func filterZones(_ ids: [String], query: String) -> [String] {113 let q = query.trimmingCharacters(in: .whitespaces).lowercased().replacingOccurrences(of: " ", with: "_")114 guard !q.isEmpty else { return ids }115 return ids.filter { $0.lowercased().contains(q) }116 }117}118119/// A maintenance window being created or edited. Dates are instants; the pickers show them in `timezone`.120struct WindowDraft: Equatable, Sendable {121 enum Problem: String, Sendable { case titleMissing, endNotAfterStart, untilBeforeStart }122123 var title = ""124 var description = ""125 var category: API.MaintenanceCategory = .planned126 var startsAt: Date127 var endsAt: Date128 private(set) var timezone: String129 var recurrence: API.MaintenanceRecurrence = .none130 var hasUntil = false131 var until: Date132 var nodeIDs: Set<String> = []133 var setMaintenanceMode = true134 var silenceAlerts = true135136 /// New window: on `day` at 22:00 (wall clock of `zone`) when a day was picked, else at the next full hour; one hour long.137 init(day: Date?, nodeID: String?, now: Date = Date(), zone: TimeZone = .current, dayCalendar: Calendar = CalendarMath.calendar()) {138 timezone = zone.identifier139 var start: Date140 if let day {141 let c = dayCalendar.dateComponents([.year, .month, .day], from: day)142 start = MaintenanceLogic.date(year: c.year ?? 2026, month: c.month ?? 1, day: c.day ?? 1, hour: 22, in: zone) ?? day143 if start < now { start = WindowDraft.nextHour(after: now) }144 } else {145 start = WindowDraft.nextHour(after: now)146 }147 startsAt = start148 endsAt = start.addingTimeInterval(3600)149 until = start.addingTimeInterval(30 * 86_400)150 if let nodeID { nodeIDs = [nodeID] }151 }152153 init(window w: API.MaintenanceWindow) {154 title = w.title155 description = w.description156 category = w.category157 startsAt = w.startsAt158 endsAt = w.endsAt159 timezone = w.timezone160 recurrence = w.recurrence161 hasUntil = w.recurrenceUntil != nil162 until = w.recurrenceUntil ?? w.startsAt.addingTimeInterval(30 * 86_400)163 nodeIDs = Set(w.scope.nodeIds)164 setMaintenanceMode = w.setMaintenanceMode165 silenceAlerts = w.silenceAlerts166 }167168 static func nextHour(after now: Date) -> Date {169 Date(timeIntervalSince1970: (now.timeIntervalSince1970 / 3600).rounded(.up) * 3600)170 }171172 var zone: TimeZone { MaintenanceLogic.timeZone(timezone) }173174 /// Changes the zone and keeps what the user typed: 22:00 stays 22:00, in the new zone.175 mutating func setTimezone(_ id: String) {176 guard id != timezone, let new = TimeZone(identifier: id) else { return }177 let old = zone178 startsAt = MaintenanceLogic.reinterpret(startsAt, from: old, to: new)179 endsAt = MaintenanceLogic.reinterpret(endsAt, from: old, to: new)180 until = MaintenanceLogic.reinterpret(until, from: old, to: new)181 timezone = id182 }183184 /// Start moved: the duration is kept.185 mutating func setStart(_ date: Date) {186 let duration = max(60, endsAt.timeIntervalSince(startsAt))187 startsAt = date188 endsAt = date.addingTimeInterval(duration)189 }190191 private var trimmedTitle: String { title.trimmingCharacters(in: .whitespacesAndNewlines) }192 private var effectiveUntil: Date? { recurrence != .none && hasUntil ? until : nil }193194 /// Local convenience only (spares a round trip); the server validates the window.195 var problems: [Problem] {196 var out: [Problem] = []197 if trimmedTitle.isEmpty { out.append(.titleMissing) }198 if endsAt <= startsAt { out.append(.endNotAfterStart) }199 if let u = effectiveUntil, u < startsAt { out.append(.untilBeforeStart) }200 return out201 }202 var canSave: Bool { problems.isEmpty }203204 func createRequest() -> API.CreateMaintenanceWindowRequest {205 let d = description.trimmingCharacters(in: .whitespacesAndNewlines)206 return API.CreateMaintenanceWindowRequest(title: trimmedTitle, description: d.isEmpty ? nil : d, category: category, startsAt: startsAt, endsAt: endsAt,207 timezone: timezone, recurrence: recurrence, recurrenceUntil: effectiveUntil,208 scope: .init(nodeIds: nodeIDs.sorted()), setMaintenanceMode: setMaintenanceMode, silenceAlerts: silenceAlerts)209 }210211 func updateRequest() -> API.UpdateMaintenanceWindowRequest {212 API.UpdateMaintenanceWindowRequest(title: trimmedTitle, description: description.trimmingCharacters(in: .whitespacesAndNewlines), category: category,213 startsAt: startsAt, endsAt: endsAt, timezone: timezone, recurrence: recurrence, recurrenceUntil: effectiveUntil,214 scope: .init(nodeIds: nodeIDs.sorted()), setMaintenanceMode: setMaintenanceMode, silenceAlerts: silenceAlerts)215 }216}217218/// A note being written. One of window / node is required by the server.219struct NoteDraft: Equatable, Sendable {220 enum Target: String, CaseIterable, Identifiable, Sendable {221 case node, window222 var id: String { rawValue }223 var title: String { trDynamic("notes.target." + rawValue) }224 static var dynamicKeys: [String] { allCases.map { "notes.target." + $0.rawValue } }225 }226227 var noteID: String?228 var windowID: String?229 var nodeID: String?230 var occurrence: Date?231 var body: String232 var pinned: Bool233 /// True for a quick note: the user must say what it is about.234 let needsTarget: Bool235 var target: Target = .node236237 init(context: NoteContext) {238 noteID = context.noteID239 windowID = context.windowID240 nodeID = context.nodeID241 occurrence = context.occurrence242 body = context.body243 pinned = context.pinned244 needsTarget = context.noteID == nil && context.windowID == nil && context.nodeID == nil245 }246247 var isEditing: Bool { noteID != nil }248 private var trimmed: String { body.trimmingCharacters(in: .whitespacesAndNewlines) }249 var hasTarget: Bool {250 guard needsTarget else { return true }251 return target == .node ? nodeID != nil : windowID != nil252 }253 var canSave: Bool { !trimmed.isEmpty && hasTarget }254255 func createRequest() -> API.CreateMaintenanceNoteRequest {256 if needsTarget {257 return target == .node258 ? API.CreateMaintenanceNoteRequest(windowId: nil, nodeId: nodeID, occurrence: nil, body: trimmed, pinned: pinned)259 : API.CreateMaintenanceNoteRequest(windowId: windowID, nodeId: nil, occurrence: occurrence, body: trimmed, pinned: pinned)260 }261 // An occurrence only makes sense with its window (the server refuses it otherwise).262 return API.CreateMaintenanceNoteRequest(windowId: windowID, nodeId: nodeID, occurrence: windowID == nil ? nil : occurrence, body: trimmed, pinned: pinned)263 }264 var updateBody: String { trimmed }265}266