SPB Git

Repository Public

GroupCTests.swift 12.7 KB 208 lines swift

1import Foundation2import MCCCore3import Testing4@testable import MCCiOS56@Suite("Maintenance calendar, notes and settings logic")7@MainActor8struct GroupCTests {9    static let utc = TimeZone(identifier: "UTC")!10    static var calendar: Calendar { CalendarMath.calendar(language: .fr, timeZone: utc) }11    static func date(_ y: Int, _ m: Int, _ d: Int, _ h: Int = 0, zone: TimeZone = utc) -> Date {12        MaintenanceLogic.date(year: y, month: m, day: d, hour: h, in: zone)!13    }1415    static func window(id: String = "00000000-0000-7000-8000-000000000001", category: String = "planned", start: Date, end: Date,16                       nodes: [String] = [], timezone: String = "UTC") throws -> API.MaintenanceWindow {17        let f = ISO8601DateFormatter()18        let json = """19        {"id":"\(id)","title":"Fenêtre","description":"","category":"\(category)","starts_at":"\(f.string(from: start))","ends_at":"\(f.string(from: end))",20         "timezone":"\(timezone)","recurrence":"none","scope":{"node_ids":[\(nodes.map { "\"\($0)\"" }.joined(separator: ","))]},21         "set_maintenance_mode":true,"silence_alerts":false,"status":"scheduled","created_at":"2026-11-01T00:00:00Z","updated_at":"2026-11-01T00:00:00Z"}22        """23        return try decoder.decode(API.MaintenanceWindow.self, from: Data(json.utf8))24    }2526    static var decoder: JSONDecoder {27        let d = JSONDecoder()28        d.dateDecodingStrategy = .iso860129        return d30    }3132    static func note(_ id: String, pinned: Bool, created: Date) -> API.MaintenanceNote {33        API.MaintenanceNote(id: id, windowId: nil, nodeId: "n", nodeAlias: nil, occurrence: nil, authorId: "a", authorDisplayName: "A", body: id, pinned: pinned, createdAt: created, editedAt: nil)34    }3536    @Test("month navigation crosses the year boundary in both directions and lands on the first day")37    func monthNavigation() {38        let cal = Self.calendar39        let dec = Self.date(2026, 12, 17, 15)40        let jan = MaintenanceLogic.month(dec, offset: 1, calendar: cal)41        #expect(cal.dateComponents([.year, .month, .day, .hour], from: jan) == DateComponents(year: 2027, month: 1, day: 1, hour: 0))42        let back = MaintenanceLogic.month(jan, offset: -1, calendar: cal)43        #expect(cal.dateComponents([.year, .month, .day], from: back) == DateComponents(year: 2026, month: 12, day: 1))44        #expect(MaintenanceLogic.month(dec, offset: -12, calendar: cal) == Self.date(2025, 12, 1))45        #expect(MaintenanceLogic.isSameMonth(dec, back, calendar: cal))46        #expect(!MaintenanceLogic.isSameMonth(dec, jan, calendar: cal))47        #expect(MaintenanceLogic.monthTitle(jan, calendar: cal).lowercased().contains("janvier"))48        #expect(MaintenanceLogic.monthTitle(jan, calendar: cal).contains("2027"))49    }5051    @Test("default selection: today inside the displayed month, otherwise the first of the month")52    func defaultSelection() {53        let cal = Self.calendar54        let today = Self.date(2026, 11, 19, 9)55        #expect(MaintenanceLogic.defaultSelection(month: Self.date(2026, 11, 3), today: today, calendar: cal) == Self.date(2026, 11, 19))56        #expect(MaintenanceLogic.defaultSelection(month: Self.date(2027, 1, 20), today: today, calendar: cal) == Self.date(2027, 1, 1))57    }5859    @Test("day markers: count, distinct category symbols, in-progress flag, midnight-spanning windows on both days")60    func markers() throws {61        let cal = Self.calendar62        let a = try Self.window(category: "planned", start: Self.date(2026, 11, 20, 22), end: Self.date(2026, 11, 21, 2))63        let b = try Self.window(id: "00000000-0000-7000-8000-000000000002", category: "hardware", start: Self.date(2026, 11, 20, 8), end: Self.date(2026, 11, 20, 9))64        let c = try Self.window(id: "00000000-0000-7000-8000-000000000003", category: "planned", start: Self.date(2026, 11, 20, 10), end: Self.date(2026, 11, 20, 11))65        let list = [66            API.MaintenanceOccurrence(window: a, occurrenceStart: a.startsAt, occurrenceEnd: a.endsAt, active: true, noteCount: 0),67            API.MaintenanceOccurrence(window: b, occurrenceStart: b.startsAt, occurrenceEnd: b.endsAt, active: false, noteCount: 2),68            API.MaintenanceOccurrence(window: c, occurrenceStart: c.startsAt, occurrenceEnd: c.endsAt, active: nil, noteCount: 0),69        ]70        let m20 = try #require(MaintenanceLogic.marker(on: Self.date(2026, 11, 20), in: list, calendar: cal))71        #expect(m20.count == 3)72        #expect(m20.hasActive)73        #expect(m20.symbols == [API.MaintenanceCategory.hardware.symbol, API.MaintenanceCategory.planned.symbol])74        let m21 = try #require(MaintenanceLogic.marker(on: Self.date(2026, 11, 21), in: list, calendar: cal))75        #expect(m21 == DayMarker(count: 1, symbols: [API.MaintenanceCategory.planned.symbol], hasActive: true))76        #expect(MaintenanceLogic.marker(on: Self.date(2026, 11, 22), in: list, calendar: cal) == nil)77    }7879    @Test("notes: pinned first, then newest first, stable on ties")80    func noteSorting() {81        let t = Self.date(2026, 11, 1)82        let notes = [Self.note("old", pinned: false, created: t), Self.note("pinned-old", pinned: true, created: t.addingTimeInterval(-500)),83                     Self.note("new", pinned: false, created: t.addingTimeInterval(60)), Self.note("pinned-new", pinned: true, created: t.addingTimeInterval(10)),84                     Self.note("a-tie", pinned: false, created: t)]85        #expect(MaintenanceLogic.sorted(notes).map(\.id) == ["pinned-new", "pinned-old", "new", "a-tie", "old"])86    }8788    @Test("window request: wall-clock dates are interpreted in the chosen, non-local time zone; changing zone keeps the wall clock")89    func windowRequestInZone() throws {90        let tokyo = TimeZone(identifier: "Asia/Tokyo")!91        let now = Self.date(2026, 11, 19, 12)92        // The day comes from the device calendar (here UTC); the default start is 22:00 on that day in the window's zone.93        var draft = WindowDraft(day: Self.date(2026, 12, 1), nodeID: "node-b", now: now, zone: tokyo, dayCalendar: Self.calendar)94        #expect(draft.timezone == "Asia/Tokyo")95        #expect(draft.startsAt == Self.date(2026, 12, 1, 13))          // 22:00 JST = 13:00 UTC96        #expect(draft.endsAt.timeIntervalSince(draft.startsAt) == 3600)97        #expect(draft.problems == [.titleMissing])98        draft.title = "  Mise à jour  "99        draft.nodeIDs.insert("node-a")100        draft.recurrence = .weekly101        var request = draft.createRequest()102        #expect(request.title == "Mise à jour")103        #expect(request.description == nil)104        #expect(request.timezone == "Asia/Tokyo")105        #expect(request.startsAt == Self.date(2026, 12, 1, 13))106        #expect(request.scope.nodeIds == ["node-a", "node-b"])107        #expect(request.recurrence == .weekly)108        #expect(request.recurrenceUntil == nil)                         // no end date unless asked109        draft.hasUntil = true110        #expect(draft.createRequest().recurrenceUntil == draft.until)111        // Moving the start keeps the duration; an end before the start is flagged locally (the server decides).112        draft.setStart(draft.startsAt.addingTimeInterval(7200))113        #expect(draft.endsAt.timeIntervalSince(draft.startsAt) == 3600)114        draft.endsAt = draft.startsAt115        #expect(draft.problems.contains(.endNotAfterStart))116        #expect(!draft.canSave)117        draft.endsAt = draft.startsAt.addingTimeInterval(1800)118        #expect(draft.canSave)119        // Same wall clock in Montréal (UTC-5 in December): 00:00 on Dec 2 local = 05:00 UTC.120        draft.setTimezone("America/Toronto")121        request = draft.createRequest()122        #expect(request.timezone == "America/Toronto")123        #expect(request.startsAt == Self.date(2026, 12, 2, 5))124        // A recurrence of "none" never sends an end date.125        draft.recurrence = .none126        #expect(draft.updateRequest().recurrenceUntil == nil)127        // Editing starts from the server's window.128        let w = try Self.window(start: Self.date(2026, 12, 5, 1), end: Self.date(2026, 12, 5, 3), nodes: ["x"], timezone: "Europe/Paris")129        let edit = WindowDraft(window: w)130        #expect(edit.timezone == "Europe/Paris" && edit.nodeIDs == ["x"] && edit.startsAt == w.startsAt && !edit.hasUntil && !edit.silenceAlerts)131    }132133    @Test("time range: window zone always, local time only when it differs; scope summary never invents aliases")134    func rangesAndScope() {135        let tokyo = "Asia/Tokyo"136        let start = Self.date(2026, 12, 1, 13), end = Self.date(2026, 12, 1, 15)137        let same = MaintenanceLogic.timeRange(start: start, end: end, zoneID: "UTC", local: Self.utc, calendar: Self.calendar)138        #expect(same.local == nil)139        let diff = MaintenanceLogic.timeRange(start: start, end: end, zoneID: tokyo, local: Self.utc, calendar: Self.calendar)140        #expect(diff.local != nil)141        #expect(diff.zone != diff.local)142        #expect(diff.zone.contains("22"))143        let aliases = ["1": "node-b", "2": "node-a"]144        #expect(MaintenanceLogic.scopeSummary(nodeIDs: ["1", "2", "3", "4"], limit: 3) { aliases[$0] } == "node-a, node-b +2")145        #expect(MaintenanceLogic.scopeSummary(nodeIDs: ["1"]) { aliases[$0] } == "node-b")146        #expect(MaintenanceLogic.filterZones(["America/New_York", "Europe/Paris"], query: "new york") == ["America/New_York"])147    }148149    @Test("note draft: a quick note needs a node or a window; an occurrence is only sent with its window")150    func noteDraft() {151        var quick = NoteDraft(context: NoteContext())152        #expect(quick.needsTarget)153        quick.body = "  vérifier le ventilateur \n"154        #expect(!quick.canSave)155        quick.nodeID = "node-1"156        #expect(quick.canSave)157        #expect(quick.createRequest() == API.CreateMaintenanceNoteRequest(windowId: nil, nodeId: "node-1", occurrence: nil, body: "vérifier le ventilateur", pinned: false))158        quick.target = .window159        #expect(!quick.canSave)160        let occ = Self.date(2026, 12, 1, 13)161        quick.windowID = "w"; quick.occurrence = occ; quick.pinned = true162        #expect(quick.createRequest() == API.CreateMaintenanceNoteRequest(windowId: "w", nodeId: nil, occurrence: occ, body: "vérifier le ventilateur", pinned: true))163164        var attached = NoteDraft(context: NoteContext(windowID: "w", occurrence: occ))165        #expect(!attached.needsTarget && !attached.canSave)166        attached.body = "ok"167        #expect(attached.createRequest().occurrence == occ)168        var orphan = NoteDraft(context: NoteContext(nodeID: "n", occurrence: occ))169        orphan.body = "ok"170        #expect(orphan.createRequest().occurrence == nil)171        let editing = NoteDraft(context: NoteContext(noteID: "id", nodeID: "n", body: "texte", pinned: true))172        #expect(editing.isEditing && editing.canSave && editing.pinned)173    }174175    @Test("settings: admin panes follow the permissions; personal panes are always there")176    func paneVisibility() {177        #expect(SettingsLogic.adminPanes { _ in false }.isEmpty)178        #expect(SettingsLogic.adminPanes { _ in true } == [.users, .invitations, .agents, .system])179        #expect(SettingsLogic.adminPanes { $0 == "invitations.manage" || $0 == "settings.manage" } == [.invitations, .system])180        #expect(SettingsPane.personal.allSatisfy { $0.permission == nil })181        #expect(Set(SettingsPane.personal + SettingsPane.admin) == Set(SettingsPane.allCases))182    }183184    @Test("settings: diagnostics carry no secret; grace labels; QR code is generated")185    func diagnosticsAndQR() {186        let d = SettingsLogic.Diagnostics(appVersion: "1.0.0", build: "1", system: "iOS 26.5", model: "iPhone", origin: "https://clustr.spboucher.ai", serverVersion: nil,187                                          apiVersion: "v1", stream: "connected", offline: false, lastEventAt: nil, language: "fr", userHandle: "simon", role: "owner")188        #expect(d.text.contains("MacLustr CC 1.0.0 (1)"))189        #expect(d.text.contains("Server version: unknown · API v1"))190        #expect(d.text.contains("User: simon (owner)"))191        #expect(!d.text.lowercased().contains("token") && !d.text.lowercased().contains("bearer"))192        #expect(SettingsLogic.graceOptions.first == 0)193        #expect(SettingsLogic.graceLabel(0) != SettingsLogic.graceLabel(60))194        let qr = SettingsLogic.qrCode(for: "https://clustr.spboucher.ai/setup#example-token-not-real")195        #expect((qr?.size.width ?? 0) >= 200)196    }197198    @Test("every key built at runtime by the maintenance and settings screens exists in French and English")199    func dynamicKeys() {200        Localization.shared.register(bundle: Bundle(for: AppDelegate.self))201        for key in SettingsLogic.dynamicKeys {202            for lang in AppLanguage.allCases {203                #expect(Localization.shared.has(key, language: lang), "missing \(key) in \(lang.rawValue)")204            }205        }206    }207}208
Files main
Menu

Theme