Repository Public
1import Foundation2import MCCCore34/// Presentation modes of the Maintenance section.5enum MaintenanceMode: String, CaseIterable, Identifiable, Sendable {6 case month, week, agenda, notes7 var id: String { rawValue }8 var title: String { Localization.shared.string("maintenance.mode." + rawValue) }9 var isCalendar: Bool { self != .notes }10}1112/// One occurrence of a window, as selected in the calendar (a recurring window has many).13struct OccurrenceRef: Hashable, Sendable, Identifiable {14 var windowID: String15 var start: Date16 var end: Date17 var id: String { "\(windowID)@\(Int(start.timeIntervalSince1970))" }1819 init(windowID: String, start: Date, end: Date) {20 self.windowID = windowID; self.start = start; self.end = end21 }22 init(_ o: API.MaintenanceOccurrence) {23 self.init(windowID: o.window.id, start: o.occurrenceStart, end: o.occurrenceEnd)24 }25}2627/// What a new note is attached to.28struct NoteTarget: Hashable, Sendable {29 var windowID: String?30 var nodeID: String?31 var occurrence: Date?32 var isEmpty: Bool { windowID == nil && nodeID == nil }33}3435/// Pure helpers of the Maintenance screens (tested in `MaintenanceTests`).36enum MaintenanceLogic {37 /// Keeps the wall-clock reading of `date` when the form's time zone changes: 22:00 in Toronto becomes38 /// 22:00 in Paris, i.e. another instant.39 static func reinterpret(_ date: Date, from old: TimeZone, to new: TimeZone) -> Date {40 var a = Calendar(identifier: .gregorian); a.timeZone = old41 var b = Calendar(identifier: .gregorian); b.timeZone = new42 let comps = a.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)43 return b.date(from: comps) ?? date44 }4546 /// Pinned notes first, then the most recent.47 static func sorted(_ notes: [API.MaintenanceNote]) -> [API.MaintenanceNote] {48 notes.sorted { a, b in49 if a.pinned != b.pinned { return a.pinned }50 if a.createdAt != b.createdAt { return a.createdAt > b.createdAt }51 return a.id < b.id52 }53 }5455 /// "Hebdomadaire jusqu’au 12 déc. 2026" / "Aucune".56 static func recurrenceSummary(_ recurrence: API.MaintenanceRecurrence, until: Date?, timeZone: TimeZone = .current) -> String {57 guard recurrence != .none else { return recurrence.label }58 guard let until else { return recurrence.label }59 return String(format: Localization.shared.string("maintenance.recurrence.until"), recurrence.label, Format.date(until, timeZone: timeZone))60 }6162 /// Vertical extent (fractions of the day, 0...1) of an occurrence inside `day`, or nil when it does not touch it.63 /// A multi-day occurrence is clipped to each day it spans.64 static func dayExtent(start: Date, end: Date, day: Date, calendar: Calendar) -> (top: Double, bottom: Double)? {65 let dayStart = calendar.startOfDay(for: day)66 guard let dayEnd = calendar.date(byAdding: .day, value: 1, to: dayStart), start < dayEnd, end > dayStart else { return nil }67 let top = start <= dayStart ? 0 : CalendarMath.dayFraction(of: start, in: day, calendar: calendar)68 let bottom = end >= dayEnd ? 1 : CalendarMath.dayFraction(of: end, in: day, calendar: calendar)69 return (top, max(bottom, top))70 }7172 /// Side-by-side columns for the occurrences of one day that overlap in time: (column, columnCount) per item.73 static func columns(for items: [(start: Date, end: Date)]) -> [(column: Int, count: Int)] {74 var result = [(column: Int, count: Int)](repeating: (0, 1), count: items.count)75 let order = items.indices.sorted { (items[$0].start, items[$0].end) < (items[$1].start, items[$1].end) }76 var cluster: [Int] = []77 var clusterEnd = Date.distantPast78 var columnEnds: [Date] = []79 func flush() {80 for i in cluster { result[i].count = max(1, columnEnds.count) }81 cluster = []; columnEnds = []82 }83 for i in order {84 if !cluster.isEmpty, items[i].start >= clusterEnd { flush(); clusterEnd = .distantPast }85 let col = columnEnds.firstIndex { $0 <= items[i].start } ?? columnEnds.count86 if col == columnEnds.count { columnEnds.append(items[i].end) } else { columnEnds[col] = items[i].end }87 result[i].column = col88 cluster.append(i)89 clusterEnd = max(clusterEnd, items[i].end)90 }91 flush()92 return result93 }9495 /// "22:00 – 23:30" or, across days, "18 nov. 22:00 – 19 nov. 02:00".96 static func timeRange(start: Date, end: Date, timeZone: TimeZone = .current) -> String {97 var cal = Calendar(identifier: .gregorian); cal.timeZone = timeZone98 if cal.isDate(start, inSameDayAs: end) {99 return "\(Format.time(start, timeZone: timeZone)) – \(Format.time(end, timeZone: timeZone))"100 }101 return "\(Format.dateTime(start, timeZone: timeZone)) – \(Format.dateTime(end, timeZone: timeZone))"102 }103104 /// Spoken / tooltip summary of one occurrence: time, title, status.105 static func summary(of o: API.MaintenanceOccurrence, timeZone: TimeZone = .current) -> String {106 "\(Format.time(o.occurrenceStart, timeZone: timeZone)) \(o.window.title), \(o.window.category.label), \(displayStatus(o).label)"107 }108109 /// The status to show for one occurrence: the window's, except that an occurrence the server marks active is110 /// in progress and past/future occurrences of a recurring window in progress are not.111 static func displayStatus(_ o: API.MaintenanceOccurrence) -> API.MaintenanceStatus {112 if o.active == true { return .inProgress }113 if o.window.status == .inProgress, o.window.recurrence != .none { return .scheduled }114 return o.window.status115 }116117 /// Title of the visible period.118 static func periodTitle(mode: MaintenanceMode, anchor: Date, calendar: Calendar) -> String {119 switch mode {120 case .month:121 var style = Date.FormatStyle().month(.wide).year()122 style.locale = calendar.locale ?? Localization.shared.locale123 style.timeZone = calendar.timeZone124 return anchor.formatted(style).capitalizedFirst125 case .week:126 let days = CalendarMath.week(containing: anchor, calendar: calendar)127 guard let a = days.first?.date, let b = days.last?.date else { return "" }128 return "\(Format.date(a, timeZone: calendar.timeZone)) – \(Format.date(b, timeZone: calendar.timeZone))"129 case .agenda:130 return String(format: Localization.shared.string("maintenance.agenda.from"), Format.date(anchor, timeZone: calendar.timeZone))131 case .notes:132 return ""133 }134 }135136 /// The interval requested from the server for a mode and an anchor date.137 static func interval(mode: MaintenanceMode, anchor: Date, calendar: Calendar, nodeID: String?) -> DateWindow? {138 switch mode {139 case .month: return CalendarMath.window(for: CalendarMath.monthGrid(containing: anchor, calendar: calendar), calendar: calendar, nodeID: nodeID)140 case .week: return CalendarMath.window(for: CalendarMath.week(containing: anchor, calendar: calendar), calendar: calendar, nodeID: nodeID)141 case .agenda:142 let from = calendar.startOfDay(for: anchor)143 guard let to = calendar.date(byAdding: .day, value: agendaDays, to: from) else { return nil }144 return DateWindow(from: from, to: to, nodeID: nodeID)145 case .notes: return nil146 }147 }148149 static let agendaDays = 90150151 static func shift(_ anchor: Date, mode: MaintenanceMode, by n: Int, calendar: Calendar) -> Date {152 switch mode {153 case .month: return calendar.date(byAdding: .month, value: n, to: CalendarMath.startOfMonth(anchor, calendar: calendar)) ?? anchor154 case .week: return calendar.date(byAdding: .day, value: 7 * n, to: anchor) ?? anchor155 case .agenda: return calendar.date(byAdding: .day, value: 30 * n, to: anchor) ?? anchor156 case .notes: return anchor157 }158 }159}160161extension String {162 var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() }163}164165/// State of the create / edit window form. Dates are instants; the pickers show them in `timeZone`.166struct WindowForm: Equatable, Sendable {167 enum Problem: String, Sendable, CaseIterable {168 case titleMissing, endNotAfterStart, noNodes, untilBeforeStart169 var message: String { Localization.shared.string("maintenance.form.problem." + rawValue) }170 }171172 var title = ""173 var details = ""174 var category: API.MaintenanceCategory = .planned175 var start: Date176 var end: Date177 var timeZoneID: String178 var recurrence: API.MaintenanceRecurrence = .none179 var hasUntil = false180 var until: Date181 var nodeIDs: Set<String> = []182 var setMaintenanceMode = true183 var silenceAlerts = true184185 var timeZone: TimeZone { TimeZone(identifier: timeZoneID) ?? .current }186187 /// A new window: tomorrow-ish defaults on `day` (22:00 → 23:00 in the Mac's time zone) or the next full hour.188 init(day: Date? = nil, nodeID: String? = nil, now: Date = Date(), timeZone: TimeZone = .current) {189 var cal = Calendar(identifier: .gregorian); cal.timeZone = timeZone190 let s: Date191 if let day {192 s = cal.date(bySettingHour: 22, minute: 0, second: 0, of: day) ?? day193 } else {194 let hour = cal.dateInterval(of: .hour, for: now)?.end ?? now195 s = hour196 }197 start = s198 end = s.addingTimeInterval(3600)199 until = cal.date(byAdding: .month, value: 3, to: s) ?? s200 timeZoneID = timeZone.identifier201 if let nodeID { nodeIDs = [nodeID] }202 }203204 init(window w: API.MaintenanceWindow) {205 title = w.title206 details = w.description207 category = w.category208 start = w.startsAt209 end = w.endsAt210 timeZoneID = TimeZone(identifier: w.timezone) != nil ? w.timezone : TimeZone.current.identifier211 recurrence = w.recurrence212 hasUntil = w.recurrenceUntil != nil213 until = w.recurrenceUntil ?? w.startsAt.addingTimeInterval(90 * 86_400)214 nodeIDs = Set(w.scope.nodeIds)215 setMaintenanceMode = w.setMaintenanceMode216 silenceAlerts = w.silenceAlerts217 }218219 /// Changes the time zone while keeping what the pickers display.220 mutating func setTimeZone(_ id: String) {221 guard let new = TimeZone(identifier: id), id != timeZoneID else { return }222 let old = timeZone223 start = MaintenanceLogic.reinterpret(start, from: old, to: new)224 end = MaintenanceLogic.reinterpret(end, from: old, to: new)225 until = MaintenanceLogic.reinterpret(until, from: old, to: new)226 timeZoneID = id227 }228229 /// Local completeness only; the server validates everything again.230 var problems: [Problem] {231 var p: [Problem] = []232 if title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { p.append(.titleMissing) }233 if end <= start { p.append(.endNotAfterStart) }234 if nodeIDs.isEmpty { p.append(.noNodes) }235 if recurrence != .none, hasUntil, until < start { p.append(.untilBeforeStart) }236 return p237 }238239 var isValid: Bool { problems.isEmpty }240 private var effectiveUntil: Date? { recurrence != .none && hasUntil ? until : nil }241 private var trimmedTitle: String { title.trimmingCharacters(in: .whitespacesAndNewlines) }242 private var trimmedDetails: String { details.trimmingCharacters(in: .whitespacesAndNewlines) }243244 func createRequest() -> API.CreateMaintenanceWindowRequest {245 API.CreateMaintenanceWindowRequest(246 title: trimmedTitle, description: trimmedDetails.isEmpty ? nil : trimmedDetails, category: category,247 startsAt: start, endsAt: end, timezone: timeZoneID, recurrence: recurrence, recurrenceUntil: effectiveUntil,248 scope: .init(nodeIds: nodeIDs.sorted()), setMaintenanceMode: setMaintenanceMode, silenceAlerts: silenceAlerts)249 }250251 /// Only what differs from `original` is sent. (The contract has no way to clear `recurrence_until` alone:252 /// switching the recurrence to none is what removes it.)253 func updateRequest(original w: API.MaintenanceWindow) -> API.UpdateMaintenanceWindowRequest {254 var r = API.UpdateMaintenanceWindowRequest()255 if trimmedTitle != w.title { r.title = trimmedTitle }256 if trimmedDetails != w.description { r.description = trimmedDetails }257 if category != w.category { r.category = category }258 if start != w.startsAt { r.startsAt = start }259 if end != w.endsAt { r.endsAt = end }260 if timeZoneID != w.timezone { r.timezone = timeZoneID }261 if recurrence != w.recurrence { r.recurrence = recurrence }262 if let u = effectiveUntil, u != w.recurrenceUntil { r.recurrenceUntil = u }263 if nodeIDs != Set(w.scope.nodeIds) { r.scope = .init(nodeIds: nodeIDs.sorted()) }264 if setMaintenanceMode != w.setMaintenanceMode { r.setMaintenanceMode = setMaintenanceMode }265 if silenceAlerts != w.silenceAlerts { r.silenceAlerts = silenceAlerts }266 return r267 }268269 func hasChanges(from w: API.MaintenanceWindow) -> Bool { updateRequest(original: w) != API.UpdateMaintenanceWindowRequest() }270}271