From 239e3de0aa01800b533feb294308519aa795d4bf Mon Sep 17 00:00:00 2001 From: Lichtkasten Dev Date: Thu, 5 Nov 2026 10:39:25 +0000 Subject: [PATCH] Code-Ersetzungen nach Liga sortiert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Teams haben eine Liga; beim Import ist das der Ordner der TXT (Codes/1. Bundesliga/…, 2. Bundesliga/…) - „Hinzufügen …“ nimmt auch ganze Ordner: jede TXT darin wird ein Team in ihrer Liga - Code-Fenster: Teams in Liga-Abschnitten, ganze Liga per Haken an/aus, einklappen, Suche, „In Liga verschieben“, Liga-Feld beim Team, Reihenfolge innerhalb der Liga per Ziehen - vorhandene Teams bekommen ihre Liga automatisch aus dem Ordner ihrer TXT - Spieltag-Assistent und Trikot-Erkennung zeigen die Code-Teams nach Liga gegliedert - Priorität bei doppelten Codes folgt der angezeigten Reihenfolge; Löschen ohne Index-Absturz Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D --- README.md | 2 +- Sources/Lichtkasten/Services/AppState.swift | 24 +++- Sources/Lichtkasten/Views/CodesWindow.swift | 127 ++++++++++++++---- .../Lichtkasten/Views/JerseySetupView.swift | 6 +- Sources/Lichtkasten/Views/SpieltagView.swift | 15 ++- .../Metadata/CodeLibrary.swift | 65 +++++++-- Tests/LichtkastenCoreTests/CoreTests.swift | 28 ++++ 7 files changed, 223 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index f5846fd..1d04f64 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Schneller Foto-Browser und Metadaten-Editor für macOS (Apple Silicon), gedacht | **Bewertung** | Sterne, Farbmarkierungen und Tags. Gespeichert als `xmp:Rating`, `xmp:Label` und `photomechanic:Tagged/ColorClass`, damit Lightroom **und** PM die Werte lesen | | **IPTC** | Alle Felder in der Reihenfolge des PM-Stationery-Pads. Geschrieben werden IIM **und** XMP synchron (UTF-8, `CodedCharacterSet`, `IPTCDigest`), bei RAWs als XMP-Sidecar. Byte-Zähler warnt bei IIM-Limits | | **Vorlagen** | Import von Photo-Mechanic-Vorlagen (`.snap` und `.xmp`) inklusive der PM-Häkchen, welche Felder angewendet werden, Stichwörter anhängen/ersetzen und „Datum = Aufnahmezeit“. Außerdem Import aus Bildern mit IPTC und Export als XMP | -| **Variablen & Codes** | `{date}`, `{city}`, `{filenamebase}`, `{model}` usw. sowie PM-Code-Ersetzungen `\code\` und `\code#2\` aus Tab-Dateien | +| **Variablen & Codes** | `{date}`, `{city}`, `{filenamebase}`, `{model}` usw. sowie PM-Code-Ersetzungen `\code\` und `\code#2\` aus Tab-Dateien. Teams nach Liga sortiert: einen Ordner wie `Codes/` mit `1. Bundesliga/`, `2. Bundesliga/` … importieren, jede TXT wird ein Team, der Ordner die Liga; ganze Ligen per Haken an/aus | | **Ingest** | Von einer oder mehreren Karten kopieren, mit Backup-Ziel, Ordner- und Umbenennungsmuster, Vorlage beim Ingest | | **Lightroom Classic** | ⌘⇧L importiert die Auswahl in den offenen Katalog. ⌘⌥L importiert, wendet die Entwicklungsvorgabe an und exportiert JPEGs, auf Wunsch mit automatischem Upload | | **FTP** | FTP, FTPS (explizit/implizit), SFTP. Mehrere Profile, Passwort im Schlüsselbund, Upload als `.part` mit anschließendem Umbenennen, Umbenennungsmuster | diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 8c8dfe0..42fbafe 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -977,20 +977,32 @@ final class AppState: ObservableObject { } /// PM "Add…": each TXT becomes a team – or, if the team exists already, only new players are added. - func importCodeFiles(into setID: UUID? = nil) { + /// Folders can be chosen too: every TXT inside becomes a team, sorted under the league = its folder + /// ("Codes/1. Bundesliga/…", "Codes/2. Bundesliga/…"). + func importCodeFiles(into setID: UUID? = nil, league: String? = nil) { let panel = NSOpenPanel() panel.allowsMultipleSelection = setID == nil - panel.message = setID == nil ? "Code-Dateien (TXT, Tab-getrennt wie in PM) – jede Datei wird ein Team" + panel.canChooseDirectories = setID == nil + panel.message = setID == nil ? "TXT-Dateien oder Liga-Ordner wählen – jede TXT wird ein Team, der Ordner ist die Liga" : "TXT mit neuen Spielern – vorhandene Codes bleiben unverändert" guard panel.runModal() == .OK else { return } - var lines: [String] = [] + var lib = codeLibrary + var results: [(team: String, added: Int, existing: Int)] = [] for url in panel.urls { do { - let r = try codeLibrary.importFile(url, into: setID) - lines.append("\(r.team): \(r.added) neu" + (r.existing > 0 ? ", \(r.existing) schon vorhanden" : "")) + if (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true { + results += try lib.importFolder(url) + } else { + results.append(try lib.importFile(url, into: setID, league: league)) + } } catch { report(error) } } - statusText = lines.joined(separator: " · ") + codeLibrary = lib // one save / rebuild for the whole import + let added = results.reduce(0) { $0 + $1.added } + statusText = results.count > 3 + ? "\(results.count) Teams importiert, \(added) neue Codes" + : results.map { "\($0.team): \($0.added) neu" + ($0.existing > 0 ? ", \($0.existing) schon vorhanden" : "") } + .joined(separator: " · ") } func reloadAllCodes() { diff --git a/Sources/Lichtkasten/Views/CodesWindow.swift b/Sources/Lichtkasten/Views/CodesWindow.swift index 5c19764..c77540c 100644 --- a/Sources/Lichtkasten/Views/CodesWindow.swift +++ b/Sources/Lichtkasten/Views/CodesWindow.swift @@ -11,12 +11,14 @@ struct CodesWindow: View { @State private var newText = "" @State private var test = "w10 trifft gegen h10, " @State private var search = "" + @State private var teamSearch = "" + @State private var collapsed: Set = [] private var teamIndex: Int? { state.codeLibrary.sets.firstIndex { $0.id == selectedTeam } } var body: some View { VStack(alignment: .leading, spacing: 10) { - Text("Diese Teams werden für Code-Ersetzungen verwendet. Bei doppelten Codes gewinnt das obere Team.") + Text("Teams nach Liga sortiert (Ordner der TXT). Aktive Teams werden für Code-Ersetzungen verwendet, bei doppelten Codes gewinnt das obere Team.") .font(.callout).foregroundStyle(.secondary) HSplitView { teamList.frame(minWidth: 300, idealWidth: 360) @@ -34,35 +36,30 @@ struct CodesWindow: View { private var teamList: some View { VStack(spacing: 6) { + TextField("Team oder Liga suchen", text: $teamSearch).textFieldStyle(.roundedBorder) List(selection: $selectedTeam) { - ForEach($state.codeLibrary.sets) { $set in - HStack { - Toggle("", isOn: $set.enabled).toggleStyle(.checkbox).labelsHidden() - .help("Aktiv (PM: Enable)") - VStack(alignment: .leading, spacing: 1) { - Text(set.name).lineLimit(1) - Text(set.sourcePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "manuell") - .font(.caption2).foregroundStyle(.secondary).lineLimit(1) + ForEach(state.codeLibrary.leagues, id: \.self) { league in + let list = teams(in: league) + if !list.isEmpty { + Section { + if !collapsed.contains(league) || !teamSearch.isEmpty { + ForEach(list) { set in teamRow(set) } + .onMove(perform: teamSearch.isEmpty ? { from, to in + state.codeLibrary.move(inLeague: league, from: from, to: to) + } : nil) + } + } header: { + leagueHeader(league) } - Spacer() - Text("\(set.entries.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary) - } - .tag(set.id) - .contextMenu { - Button("Neue Spieler aus TXT nachladen …") { state.importCodeFiles(into: set.id) } - Button("Im Finder zeigen") { - if let p = set.sourcePath { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: p)]) } - }.disabled(set.sourcePath == nil) - Button("Löschen", role: .destructive) { remove(set.id) } } } - .onMove { state.codeLibrary.sets.move(fromOffsets: $0, toOffset: $1) } }.scrollContentBackground(.hidden).background(LK.deep) HStack(spacing: 6) { Button("Hinzufügen …") { state.importCodeFiles() } - .help("TXT-Dateien als Teams importieren (wie PM „Add…“)") + .help("TXT-Dateien oder ganze Liga-Ordner importieren – der Ordner einer TXT wird ihre Liga") Button("Neues Team") { - let s = CodeSet(name: "Neues Team") + let league = state.codeLibrary.sets.first { $0.id == selectedTeam }?.league ?? "" + let s = CodeSet(name: "Neues Team", league: league) state.codeLibrary.sets.append(s) selectedTeam = s.id } @@ -75,6 +72,85 @@ struct CodesWindow: View { } } + private func teams(in league: String) -> [CodeSet] { + let q = teamSearch.trimmingCharacters(in: .whitespaces) + return state.codeLibrary.sets.filter { set in + set.league == league && (q.isEmpty || set.name.localizedCaseInsensitiveContains(q) + || league.localizedCaseInsensitiveContains(q)) + } + } + + /// League header: checkbox for the whole league (all / none / mixed), fold, number of active teams. + private func leagueHeader(_ league: String) -> some View { + let all = state.codeLibrary.sets.filter { $0.league == league } + let active = all.filter(\.enabled).count + let icon = active == all.count ? "checkmark.square.fill" : (active == 0 ? "square" : "minus.square.fill") + return HStack(spacing: 6) { + Button { + let on = active != all.count + for i in state.codeLibrary.sets.indices where state.codeLibrary.sets[i].league == league { + state.codeLibrary.sets[i].enabled = on + } + } label: { Image(systemName: icon).foregroundStyle(active > 0 ? LK.amber : LK.muted) } + .buttonStyle(.borderless) + .help(active == all.count ? "Ganze Liga deaktivieren" : "Ganze Liga aktivieren") + Button { + if collapsed.contains(league) { collapsed.remove(league) } else { collapsed.insert(league) } + } label: { + HStack(spacing: 4) { + Image(systemName: collapsed.contains(league) ? "chevron.right" : "chevron.down").font(.system(size: 9, weight: .bold)) + Text(league.isEmpty ? "Ohne Liga" : league).font(.system(size: 12, weight: .bold)).foregroundStyle(LK.text) + } + } + .buttonStyle(.plain) + Spacer() + Text("\(active)/\(all.count) aktiv").font(.caption.monospacedDigit()).foregroundStyle(LK.muted) + } + .contextMenu { + Button("Weitere Teams in diese Liga importieren …") { state.importCodeFiles(league: league) } + Button("Ganze Liga löschen", role: .destructive) { + let ids = Set(all.map(\.id)) + if let sel = selectedTeam, ids.contains(sel) { selectedTeam = nil } + DispatchQueue.main.async { state.codeLibrary.sets.removeAll { ids.contains($0.id) } } + } + } + } + + private func teamRow(_ set: CodeSet) -> some View { + HStack { + Toggle("", isOn: Binding( + get: { state.codeLibrary.sets.first { $0.id == set.id }?.enabled ?? false }, + set: { on in if let i = state.codeLibrary.sets.firstIndex(where: { $0.id == set.id }) { state.codeLibrary.sets[i].enabled = on } })) + .toggleStyle(.checkbox).labelsHidden() + .help("Aktiv (PM: Enable)") + VStack(alignment: .leading, spacing: 1) { + Text(set.name).lineLimit(1) + Text(set.sourcePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "manuell") + .font(.caption2).foregroundStyle(.secondary).lineLimit(1) + } + Spacer() + Text("\(set.entries.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary) + } + .tag(set.id) + .contextMenu { + Button("Neue Spieler aus TXT nachladen …") { state.importCodeFiles(into: set.id) } + Menu("In Liga verschieben") { + ForEach(state.codeLibrary.leagues.filter { $0 != set.league && !$0.isEmpty }, id: \.self) { l in + Button(l) { setLeague(set.id, l) } + } + if !set.league.isEmpty { Divider(); Button("Ohne Liga") { setLeague(set.id, "") } } + } + Button("Im Finder zeigen") { + if let p = set.sourcePath { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: p)]) } + }.disabled(set.sourcePath == nil) + Button("Löschen", role: .destructive) { remove(set.id) } + } + } + + private func setLeague(_ id: UUID, _ league: String) { + if let i = state.codeLibrary.sets.firstIndex(where: { $0.id == id }) { state.codeLibrary.sets[i].league = league } + } + // MARK: Players of the selected team @ViewBuilder @@ -83,6 +159,8 @@ struct CodesWindow: View { VStack(alignment: .leading, spacing: 6) { HStack { TextField("Teamname", text: $state.codeLibrary.sets[i].name).font(.headline).textFieldStyle(.roundedBorder) + TextField("Liga", text: $state.codeLibrary.sets[i].league).textFieldStyle(.roundedBorder).frame(width: 150) + .help("Liga, unter der das Team einsortiert wird (z. B. 1. Bundesliga)") Button("TXT nachladen …") { state.importCodeFiles(into: state.codeLibrary.sets[i].id) } .help("Neue Spieler aus einer TXT hinzufügen – vorhandene bleiben unverändert") } @@ -176,8 +254,9 @@ struct CodesWindow: View { } private func remove(_ id: UUID) { - state.codeLibrary.sets.removeAll { $0.id == id } - if selectedTeam == id { selectedTeam = state.codeLibrary.sets.first?.id } + // leave the detail view (index bindings) first, then remove – avoids "Index out of range" + if selectedTeam == id { selectedTeam = nil } + DispatchQueue.main.async { state.codeLibrary.sets.removeAll { $0.id == id } } } private func export(_ set: CodeSet) { diff --git a/Sources/Lichtkasten/Views/JerseySetupView.swift b/Sources/Lichtkasten/Views/JerseySetupView.swift index 3ae644f..067179b 100644 --- a/Sources/Lichtkasten/Views/JerseySetupView.swift +++ b/Sources/Lichtkasten/Views/JerseySetupView.swift @@ -79,8 +79,10 @@ struct JerseySetupView: View { ForEach(state.settings.jersey.teams) { t in teamRow(t.id) } HStack { Menu("Team hinzufügen") { - ForEach(state.codeLibrary.sets) { set in - Button(set.name) { add(set) } + ForEach(state.codeLibrary.grouped, id: \.league) { g in + Menu(g.league.isEmpty ? "Ohne Liga" : g.league) { + ForEach(g.sets) { set in Button(set.name) { add(set) } } + } } if state.codeLibrary.sets.isEmpty { Text("Zuerst Teams in den Code-Ersetzungen anlegen (⌘⇧K)") } } diff --git a/Sources/Lichtkasten/Views/SpieltagView.swift b/Sources/Lichtkasten/Views/SpieltagView.swift index 0d2a140..cf9dea9 100644 --- a/Sources/Lichtkasten/Views/SpieltagView.swift +++ b/Sources/Lichtkasten/Views/SpieltagView.swift @@ -220,8 +220,13 @@ struct SpieltagView: View { Button("Leeres Team") { sel.wrappedValue = newTeam(from: nil); edit.wrappedValue = true } if !state.codeLibrary.sets.isEmpty { Divider() - ForEach(state.codeLibrary.sets) { set in - Button("Aus Code-Team „\(set.name)“") { sel.wrappedValue = newTeam(from: set); edit.wrappedValue = true } + // one submenu per league (1. Bundesliga, 2. Bundesliga …) + ForEach(state.codeLibrary.grouped, id: \.league) { g in + Menu(g.league.isEmpty ? "Ohne Liga" : g.league) { + ForEach(g.sets) { set in + Button("Aus Code-Team „\(set.name)“") { sel.wrappedValue = newTeam(from: set); edit.wrappedValue = true } + } + } } } } label: { Image(systemName: "plus") } @@ -249,7 +254,11 @@ struct SpieltagView: View { row("Spieler-Codes") { Picker("", selection: b.codeSetID) { Text("– keine –").tag(UUID?.none) - ForEach(state.codeLibrary.sets) { set in Text(set.name).tag(UUID?.some(set.id)) } + ForEach(state.codeLibrary.grouped, id: \.league) { g in + Section(g.league.isEmpty ? "Ohne Liga" : g.league) { + ForEach(g.sets) { set in Text(set.name).tag(UUID?.some(set.id)) } + } + } } .labelsHidden() } diff --git a/Sources/LichtkastenCore/Metadata/CodeLibrary.swift b/Sources/LichtkastenCore/Metadata/CodeLibrary.swift index aa4366b..5ec9be3 100644 --- a/Sources/LichtkastenCore/Metadata/CodeLibrary.swift +++ b/Sources/LichtkastenCore/Metadata/CodeLibrary.swift @@ -21,17 +21,20 @@ public struct CodeEntry: Codable, Hashable, Identifiable, Sendable { public struct CodeSet: Codable, Hashable, Identifiable, Sendable { public var id = UUID() public var name: String + /// League / group the team is sorted under ("1. Bundesliga", "2. Bundesliga" …) – empty = no league. + /// Imported from the folder the TXT lies in. + public var league: String = "" public var enabled = true public var entries: [CodeEntry] = [] /// TXT file the team was imported from (for "Reload" / auto reload). public var sourcePath: String? public var sourceModified: Date? - public init(name: String, entries: [CodeEntry] = [], sourcePath: String? = nil) { - self.name = name; self.entries = entries; self.sourcePath = sourcePath + public init(name: String, league: String = "", entries: [CodeEntry] = [], sourcePath: String? = nil) { + self.name = name; self.league = league; self.entries = entries; self.sourcePath = sourcePath } - enum CodingKeys: String, CodingKey { case id, name, enabled, entries, sourcePath, sourceModified } + enum CodingKeys: String, CodingKey { case id, name, league, enabled, entries, sourcePath, sourceModified } /// Tolerant: a missing/new field must never cost the players. public init(from decoder: Decoder) throws { @@ -42,6 +45,13 @@ public struct CodeSet: Codable, Hashable, Identifiable, Sendable { entries = (try? c.decode([CodeEntry].self, forKey: .entries)) ?? [] sourcePath = try? c.decode(String.self, forKey: .sourcePath) sourceModified = try? c.decode(Date.self, forKey: .sourceModified) + // teams from before leagues existed: sorted under the folder their TXT lies in + league = (try? c.decode(String.self, forKey: .league)) ?? sourcePath.map(CodeSet.league(forFile:)) ?? "" + } + + /// League of a TXT = name of its folder ("…/Codes/1. Bundesliga/VfL Wolfsburg.txt" → "1. Bundesliga"). + public static func league(forFile path: String) -> String { + URL(fileURLWithPath: path).deletingLastPathComponent().lastPathComponent } /// Adds only codes that are not in the team yet (existing players stay untouched). @@ -84,7 +94,8 @@ public struct CodeLibrary: Codable, Sendable { /// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes. public var replacements: CodeReplacements { var table: [String: [String]] = [:] - for set in sets where set.enabled { + // same order as shown (league by league) – the upper team wins on duplicate codes + for set in grouped.flatMap(\.sets) where set.enabled { for e in set.entries where table[e.code.lowercased()] == nil { table[e.code.lowercased()] = e.columns } } var r = CodeReplacements(table: table) @@ -122,22 +133,49 @@ public struct CodeLibrary: Codable, Sendable { return String(decoding: data, as: UTF8.self) } - /// Imports a TXT: merges into the team with the same source file (or name), otherwise creates a new team. + /// Leagues in list order (first appearance), teams without league last. + public var leagues: [String] { + var seen: [String] = [] + for s in sets where !seen.contains(s.league) { seen.append(s.league) } + return seen.filter { !$0.isEmpty } + (seen.contains("") ? [""] : []) + } + + /// Teams grouped by league, in list order (for pickers and the code window). + public var grouped: [(league: String, sets: [CodeSet])] { + leagues.map { l in (l, sets.filter { $0.league == l }) } + } + + /// Imports a folder of TXT files: every TXT becomes a team, its league is the folder it lies in – + /// choose the parent folder ("Codes" with "1. Bundesliga", "2. Bundesliga" …) or one league folder. @discardableResult - public mutating func importFile(_ url: URL, into setID: UUID? = nil) throws -> (team: String, added: Int, existing: Int) { + public mutating func importFolder(_ folder: URL) throws -> [(team: String, added: Int, existing: Int)] { + let fm = FileManager.default + guard let e = fm.enumerator(at: folder, includingPropertiesForKeys: nil, + options: [.skipsHiddenFiles, .skipsPackageDescendants], errorHandler: { _, _ in true }) else { return [] } + let txts = e.compactMap { $0 as? URL }.filter { $0.pathExtension.lowercased() == "txt" } + .sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending } + return try txts.map { try importFile($0) } + } + + /// Imports a TXT: merges into the team with the same source file (or name), otherwise creates a new team. + /// The league comes from the folder of the file (unless given). + @discardableResult + public mutating func importFile(_ url: URL, into setID: UUID? = nil, league: String? = nil) throws -> (team: String, added: Int, existing: Int) { let entries = CodeLibrary.parse(try CodeLibrary.readText(url)) let mod = (try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]) as? Date let name = url.deletingPathExtension().lastPathComponent.replacingOccurrences(of: "_", with: " ") let idx = setID.flatMap { id in sets.firstIndex { $0.id == id } } ?? sets.firstIndex { $0.sourcePath == url.path } - ?? sets.firstIndex { $0.name.caseInsensitiveCompare(name) == .orderedSame } + ?? sets.firstIndex { $0.name.caseInsensitiveCompare(name) == .orderedSame + && (league ?? CodeSet.league(forFile: url.path)).caseInsensitiveCompare($0.league) == .orderedSame } if let i = idx { let r = sets[i].merge(entries) if sets[i].sourcePath == nil || setID == nil { sets[i].sourcePath = url.path } sets[i].sourceModified = mod + if sets[i].league.isEmpty { sets[i].league = league ?? CodeSet.league(forFile: url.path) } return (sets[i].name, r.added, r.existing) } - var set = CodeSet(name: name, sourcePath: url.path) + var set = CodeSet(name: name, league: league ?? CodeSet.league(forFile: url.path), sourcePath: url.path) let r = set.merge(entries) set.sourceModified = mod sets.append(set) @@ -159,6 +197,17 @@ public struct CodeLibrary: Codable, Sendable { return added } + /// Moves a team within its league (code window drag & drop) – order = priority on duplicate codes. + public mutating func move(inLeague league: String, from source: IndexSet, to destination: Int) { + let positions = sets.indices.filter { sets[$0].league == league } + let group = positions.map { sets[$0] } + // same semantics as SwiftUI's move(fromOffsets:toOffset:) – Core stays Foundation-only + let moving = source.sorted().map { group[$0] } + var rest = group.enumerated().filter { !source.contains($0.offset) }.map(\.element) + rest.insert(contentsOf: moving, at: max(0, min(rest.count, destination - source.filter { $0 < destination }.count))) + for (p, s) in zip(positions, rest) { sets[p] = s } + } + /// Migration from the old flat code table. public static func migrate(_ old: CodeReplacements) -> CodeLibrary { var lib = CodeLibrary() diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index 661f4af..f9da120 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -424,3 +424,31 @@ final class BugfixTests: XCTestCase { XCTAssertEqual(item.iptc.text["dateCreated"], "2026-11-02 18:31:05+01:00") } } + +final class LeagueTests: XCTestCase { + func testFolderImportSortsTeamsByLeague() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + for (league, team, code) in [("1. Bundesliga", "VfL Wolfsburg", "w10"), ("2. Bundesliga", "Hamburger SV", "h7"), + ("1. Bundesliga", "Bayern München", "b9")] { + let dir = root.appendingPathComponent(league) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try "\(code)\tSpieler \(code)\n".write(to: dir.appendingPathComponent(team + ".txt"), atomically: true, encoding: .utf8) + } + var lib = CodeLibrary() + let r = try lib.importFolder(root) + XCTAssertEqual(r.count, 3) + XCTAssertEqual(lib.leagues, ["1. Bundesliga", "2. Bundesliga"]) + XCTAssertEqual(lib.grouped.first?.sets.map(\.name).sorted(), ["Bayern München", "VfL Wolfsburg"]) + XCTAssertEqual(lib.replacements.lookup("h7"), "Spieler h7") + + lib.move(inLeague: "1. Bundesliga", from: IndexSet(integer: 1), to: 0) + XCTAssertEqual(lib.grouped.first?.sets.first?.name, "VfL Wolfsburg") + } + + func testOldTeamsGetLeagueFromTheirFolder() throws { + let json = #"{"name":"VfL","sourcePath":"/Codes/1. Bundesliga/VfL.txt","entries":[]}"# + let set = try JSONDecoder().decode(CodeSet.self, from: Data(json.utf8)) + XCTAssertEqual(set.league, "1. Bundesliga") + } +}