Code-Ordner automatisch einlesen, eigene Kürzel wirklich übernehmen
- neue TXT-Dateien und Liga-Ordner (z. B. „Testspiele“) in den Code-Ordnern werden beim Öffnen des Spieltag-Assistenten, mit „Alle neu laden“, über „+ → Code-Ordner neu einlesen“ und beim automatischen Nachladen zu Teams; Code-Ordner = als Ganzes importierte Ordner bzw. gemeinsamer Ordner der Ligen - geändertes Kürzel (h → hs, hs → h, h → s …) benennt die Codes des Teams um (h10 → hs10) und gilt auch für spätere TXT-Nachladungen; beim Anlegen des Spieltags automatisch, im Assistenten per Knopf/⏎, in der Trikot-Erkennung per ⏎ und im Code-Fenster („Kürzel“ + Umbenennen); Trikot-Teams ziehen mit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
1 parent
50d03fc4d7
commit
7efaa74678
6 files changed
+217
-6
No files matched your search
@@ -247,7 +247,11 @@ final class AppState: ObservableObject {
|
||||
guard let self, self.codeLibrary.autoReload else { return }
|
||||
var lib = self.codeLibrary
|
||||
let n = lib.reloadAll(onlyChanged: true)
|
||||
if n > 0 { self.codeLibrary = lib; self.statusText = "Codes: \(n) neue Einträge nachgeladen" }
|
||||
let teams = lib.importNewFiles()
|
||||
if n > 0 || !teams.isEmpty {
|
||||
self.codeLibrary = lib
|
||||
self.statusText = "Codes: \(n) neue Einträge" + (teams.isEmpty ? "" : ", \(teams.count) neue Teams") + " nachgeladen"
|
||||
}
|
||||
}
|
||||
}
|
||||
cardMonitor.start { [weak self] dcim in
|
||||
@@ -1204,7 +1208,39 @@ final class AppState: ObservableObject {
|
||||
.joined(separator: " · ")
|
||||
}
|
||||
|
||||
/// New TXT files / league folders (e.g. "Testspiele") in the code folders become teams.
|
||||
@discardableResult
|
||||
func importNewCodeFiles(quiet: Bool = false) -> [String] {
|
||||
var lib = codeLibrary
|
||||
let new = lib.importNewFiles()
|
||||
guard !new.isEmpty else { return [] }
|
||||
codeLibrary = lib
|
||||
if !quiet { statusText = "Codes: \(new.count) neue(s) Team(s) eingelesen – " + new.prefix(4).joined(separator: ", ") }
|
||||
return new
|
||||
}
|
||||
|
||||
/// Own short code for a team ("h" → "hs"): renames the codes in the code team (h10 → hs10) and keeps it for
|
||||
/// TXT reloads – so the new prefix really replaces, not only in the jersey recognition.
|
||||
@discardableResult
|
||||
func applyCodePrefix(_ prefix: String, toSet setID: UUID?) -> Int {
|
||||
let p = prefix.trimmingCharacters(in: .whitespaces).lowercased()
|
||||
guard let setID, !p.isEmpty, let i = codeLibrary.sets.firstIndex(where: { $0.id == setID }) else { return 0 }
|
||||
let current = codeLibrary.sets[i].currentPrefix
|
||||
guard !current.isEmpty, current != p else { return 0 }
|
||||
var lib = codeLibrary
|
||||
let n = lib.sets[i].renamePrefix(from: current, to: p)
|
||||
guard n > 0 else { return 0 }
|
||||
codeLibrary = lib
|
||||
// jersey teams of this code team use the new prefix too
|
||||
for j in settings.jersey.teams.indices where settings.jersey.teams[j].codeSetID == setID {
|
||||
settings.jersey.teams[j].prefix = p
|
||||
}
|
||||
statusText = "\(lib.sets[i].name): \(n) Codes von „\(current)…“ auf „\(p)…“ umgestellt"
|
||||
return n
|
||||
}
|
||||
|
||||
func reloadAllCodes() {
|
||||
importNewCodeFiles()
|
||||
let n = codeLibrary.reloadAll()
|
||||
statusText = n == 0 ? "Codes: keine neuen Einträge" : "Codes: \(n) neue Einträge"
|
||||
}
|
||||
@@ -1922,6 +1958,8 @@ final class AppState: ObservableObject {
|
||||
@discardableResult
|
||||
func createSpieltag(_ plan: MatchPlan, options: SpieltagOptions) -> IPTCTemplate? {
|
||||
guard let home = spieltag.team(plan.homeID), let away = spieltag.team(plan.awayID) else { return nil }
|
||||
// a changed short code (h → hs) is applied to the code teams, not only stored as a placeholder
|
||||
for t in [home, away] { applyCodePrefix(t.codePrefix, toSet: t.codeSetID) }
|
||||
let comp = spieltag.competition(plan.competitionID)
|
||||
let base = templates.first { $0.id == plan.baseTemplateID }
|
||||
var m = plan
|
||||
|
||||
@@ -66,7 +66,7 @@ struct CodesWindow: View {
|
||||
Button("Entfernen") { if let id = selectedTeam { remove(id) } }.disabled(selectedTeam == nil)
|
||||
Spacer()
|
||||
Button("Alle neu laden") { state.reloadAllCodes() }
|
||||
.help("Liest die TXT-Dateien erneut – nur neue Spieler kommen hinzu")
|
||||
.help("Liest die TXT-Dateien erneut (nur neue Spieler) und neue TXT/Liga-Ordner wie „Testspiele“ in den Code-Ordnern")
|
||||
}
|
||||
.controlSize(.small)
|
||||
}
|
||||
@@ -161,6 +161,7 @@ struct CodesWindow: View {
|
||||
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)")
|
||||
PrefixField(setID: state.codeLibrary.sets[i].id, current: state.codeLibrary.sets[i].currentPrefix)
|
||||
Button("TXT nachladen …") { state.importCodeFiles(into: state.codeLibrary.sets[i].id) }
|
||||
.help("Neue Spieler aus einer TXT hinzufügen – vorhandene bleiben unverändert")
|
||||
}
|
||||
@@ -267,3 +268,31 @@ struct CodesWindow: View {
|
||||
try? text.write(to: url, atomically: true, encoding: .utf8)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Short code of a team: change it (h → hs) and all its codes are renamed – also for later TXT reloads.
|
||||
struct PrefixField: View {
|
||||
@EnvironmentObject var state: AppState
|
||||
let setID: UUID
|
||||
let current: String
|
||||
@State private var text = ""
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 4) {
|
||||
TextField("Kürzel", text: $text).textFieldStyle(.roundedBorder).frame(width: 54)
|
||||
.onSubmit(apply)
|
||||
Button("Umbenennen", action: apply)
|
||||
.disabled(text.isEmpty || text.lowercased() == current)
|
||||
}
|
||||
.help("Kürzel der Codes (jetzt „\(current)“) – z. B. „hs“ statt „h“: aus h10 wird hs10")
|
||||
.onAppear { text = current }
|
||||
.onChange(of: setID) { _, _ in text = current }
|
||||
.onChange(of: current) { _, c in text = c }
|
||||
}
|
||||
|
||||
private func apply() {
|
||||
if state.applyCodePrefix(text, toSet: setID) == 0 {
|
||||
state.statusText = "Kürzel unverändert (gleich, leer oder nur Buchstaben erlaubt)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,6 +159,8 @@ struct JerseySetupView: View {
|
||||
HStack {
|
||||
Text("Code-Präfix")
|
||||
TextField("w", text: team.prefix).frame(width: 50).textFieldStyle(.roundedBorder)
|
||||
.onSubmit { state.applyCodePrefix(team.wrappedValue.prefix, toSet: team.wrappedValue.codeSetID) }
|
||||
.help("Eigenes Kürzel (z. B. hs statt h) – mit ⏎ werden die Codes des Teams umbenannt")
|
||||
Text(example(team.wrappedValue))
|
||||
.font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
}
|
||||
|
||||
@@ -218,6 +218,9 @@ struct SpieltagView: View {
|
||||
}
|
||||
Menu {
|
||||
Button("Leeres Team") { sel.wrappedValue = newTeam(from: nil); edit.wrappedValue = true }
|
||||
Button("Code-Ordner neu einlesen") {
|
||||
if state.importNewCodeFiles().isEmpty { state.statusText = "Codes: keine neuen Teams gefunden" }
|
||||
}
|
||||
if !state.codeLibrary.sets.isEmpty {
|
||||
Divider()
|
||||
// one submenu per league (1. Bundesliga, 2. Bundesliga …)
|
||||
@@ -262,7 +265,20 @@ struct SpieltagView: View {
|
||||
}
|
||||
.labelsHidden()
|
||||
}
|
||||
row("Präfix") { TextField("w", text: b.codePrefix).textFieldStyle(.roundedBorder).frame(width: 50) }
|
||||
row("Präfix") {
|
||||
HStack(spacing: 6) {
|
||||
TextField("w", text: b.codePrefix).textFieldStyle(.roundedBorder).frame(width: 50)
|
||||
.onSubmit { state.applyCodePrefix(b.wrappedValue.codePrefix, toSet: b.wrappedValue.codeSetID) }
|
||||
if let cur = codeSetPrefix(b.wrappedValue.codeSetID), !b.wrappedValue.codePrefix.isEmpty,
|
||||
cur != b.wrappedValue.codePrefix.lowercased() {
|
||||
Button("Codes \(cur)… → \(b.wrappedValue.codePrefix.lowercased())…") {
|
||||
state.applyCodePrefix(b.wrappedValue.codePrefix, toSet: b.wrappedValue.codeSetID)
|
||||
}
|
||||
.buttonStyle(LKButtonStyle(compact: true))
|
||||
.help("Benennt die Codes des Teams um (z. B. h10 → hs10) – passiert auch beim Anlegen des Spieltags")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row("Heimstadion") { venueFields(b.venue) }
|
||||
HStack(spacing: 14) {
|
||||
@@ -480,6 +496,7 @@ struct SpieltagView: View {
|
||||
// MARK: Data helpers
|
||||
|
||||
private func setup() {
|
||||
state.importNewCodeFiles() // new league / test match folders show up right away
|
||||
let lib = state.spieltag
|
||||
if competitionID == nil { competitionID = lib.lastCompetitionID ?? lib.competitions.first?.id }
|
||||
if baseTemplateID == nil {
|
||||
@@ -504,6 +521,13 @@ struct SpieltagView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Short code the code team uses right now (nil if none).
|
||||
private func codeSetPrefix(_ id: UUID?) -> String? {
|
||||
guard let id, let set = state.codeLibrary.sets.first(where: { $0.id == id }) else { return nil }
|
||||
let p = set.currentPrefix
|
||||
return p.isEmpty ? nil : p
|
||||
}
|
||||
|
||||
private func newTeam(from set: CodeSet?) -> UUID {
|
||||
var t = TeamProfile(name: set.map { prettyName($0.name) } ?? "Neues Team")
|
||||
if let set {
|
||||
|
||||
@@ -29,12 +29,15 @@ public struct CodeSet: Codable, Hashable, Identifiable, Sendable {
|
||||
/// TXT file the team was imported from (for "Reload" / auto reload).
|
||||
public var sourcePath: String?
|
||||
public var sourceModified: Date?
|
||||
/// Own short codes instead of the ones in the TXT, e.g. ["h": "hs"] – applied to every (re)import,
|
||||
/// so reloading the TXT does not bring the old codes back.
|
||||
public var prefixMap: [String: String] = [:]
|
||||
|
||||
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, league, enabled, entries, sourcePath, sourceModified }
|
||||
enum CodingKeys: String, CodingKey { case id, name, league, enabled, entries, sourcePath, sourceModified, prefixMap }
|
||||
|
||||
/// Tolerant: a missing/new field must never cost the players.
|
||||
public init(from decoder: Decoder) throws {
|
||||
@@ -45,6 +48,7 @@ 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)
|
||||
prefixMap = (try? c.decode([String: String].self, forKey: .prefixMap)) ?? [:]
|
||||
// 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:)) ?? ""
|
||||
}
|
||||
@@ -54,12 +58,53 @@ public struct CodeSet: Codable, Hashable, Identifiable, Sendable {
|
||||
URL(fileURLWithPath: path).deletingLastPathComponent().lastPathComponent
|
||||
}
|
||||
|
||||
/// Letters + number of a code ("hs10" → ("hs", "10")), nil for codes of another shape.
|
||||
static func split(_ code: String) -> (prefix: String, rest: String)? {
|
||||
let p = String(code.prefix { !$0.isNumber })
|
||||
let rest = String(code.dropFirst(p.count))
|
||||
guard !p.isEmpty, let first = rest.first, first.isNumber,
|
||||
rest.split(separator: "#", maxSplits: 1).first?.allSatisfy(\.isNumber) == true else { return nil }
|
||||
return (p, rest)
|
||||
}
|
||||
|
||||
/// The code as this team uses it (own short code applied).
|
||||
public func mapped(_ code: String) -> String {
|
||||
guard let (p, rest) = CodeSet.split(code), let to = prefixMap[p.lowercased()] else { return code }
|
||||
return to + rest
|
||||
}
|
||||
|
||||
/// Short code of the team as it is now ("h" for h10, h7 …).
|
||||
public var currentPrefix: String { JerseyLogic.detectPrefix(codes: entries.map(\.code)) }
|
||||
|
||||
/// Changes the team's short code: h10 → hs10, h7 → hs7 … and remembers it for later TXT reloads.
|
||||
/// Returns the number of renamed codes.
|
||||
@discardableResult
|
||||
public mutating func renamePrefix(from old: String, to new: String) -> Int {
|
||||
let from = old.lowercased(), to = new.trimmingCharacters(in: .whitespaces).lowercased()
|
||||
guard !from.isEmpty, !to.isEmpty, from != to, to.allSatisfy(\.isLetter) else { return 0 }
|
||||
let existing = Set(entries.map { $0.code.lowercased() })
|
||||
var n = 0
|
||||
for i in entries.indices {
|
||||
guard let (p, rest) = CodeSet.split(entries[i].code), p.lowercased() == from else { continue }
|
||||
let renamed = to + rest
|
||||
if existing.contains(renamed.lowercased()) { continue } // never two players on one code
|
||||
entries[i].code = renamed
|
||||
n += 1
|
||||
}
|
||||
// codes from the TXT (original prefix) → new prefix; chains h → hs → s stay one step
|
||||
for (k, v) in prefixMap where v == from { prefixMap[k] = to }
|
||||
if prefixMap[from] == nil { prefixMap[from] = to }
|
||||
prefixMap = prefixMap.filter { $0.key != $0.value }
|
||||
return n
|
||||
}
|
||||
|
||||
/// Adds only codes that are not in the team yet (existing players stay untouched).
|
||||
@discardableResult
|
||||
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
|
||||
var known = Set(entries.map { $0.code.lowercased() })
|
||||
var added = 0, existing = 0
|
||||
for e in new {
|
||||
for var e in new {
|
||||
e.code = mapped(e.code)
|
||||
let k = e.code.lowercased()
|
||||
if known.contains(k) { existing += 1; continue }
|
||||
entries.append(e)
|
||||
@@ -76,10 +121,13 @@ public struct CodeLibrary: Codable, Sendable {
|
||||
public var defaultReplacement = ""
|
||||
public var bareCodes = true
|
||||
public var autoReload = false
|
||||
/// Folders imported as a whole ("Codes" with "1. Bundesliga", "Testspiele" …) – new TXT files and
|
||||
/// league folders inside are picked up automatically.
|
||||
public var rootFolders: [String] = []
|
||||
|
||||
public init() {}
|
||||
|
||||
enum CodingKeys: String, CodingKey { case sets, delimiter, defaultReplacement, bareCodes, autoReload }
|
||||
enum CodingKeys: String, CodingKey { case sets, delimiter, defaultReplacement, bareCodes, autoReload, rootFolders }
|
||||
|
||||
/// Tolerant decoding (see CodeSet).
|
||||
public init(from decoder: Decoder) throws {
|
||||
@@ -89,6 +137,7 @@ public struct CodeLibrary: Codable, Sendable {
|
||||
defaultReplacement = (try? c.decode(String.self, forKey: .defaultReplacement)) ?? ""
|
||||
bareCodes = (try? c.decode(Bool.self, forKey: .bareCodes)) ?? true
|
||||
autoReload = (try? c.decode(Bool.self, forKey: .autoReload)) ?? false
|
||||
rootFolders = (try? c.decode([String].self, forKey: .rootFolders)) ?? []
|
||||
}
|
||||
|
||||
/// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes.
|
||||
@@ -154,9 +203,43 @@ public struct CodeLibrary: Codable, Sendable {
|
||||
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 }
|
||||
let path = folder.standardizedFileURL.path
|
||||
if !rootFolders.contains(path) { rootFolders.append(path) }
|
||||
return try txts.map { try importFile($0) }
|
||||
}
|
||||
|
||||
/// Folders to watch for new code files: the imported roots, plus – for libraries from before – the
|
||||
/// common parent of league folders ("Codes/1. Bundesliga/…" + "Codes/2. Bundesliga/…" → "Codes").
|
||||
public var effectiveRoots: [String] {
|
||||
var roots = rootFolders
|
||||
var leaguesPerParent: [String: Set<String>] = [:]
|
||||
for s in sets {
|
||||
guard let p = s.sourcePath else { continue }
|
||||
let league = URL(fileURLWithPath: p).deletingLastPathComponent()
|
||||
leaguesPerParent[league.deletingLastPathComponent().path, default: []].insert(league.path)
|
||||
}
|
||||
for (parent, leagues) in leaguesPerParent where leagues.count >= 2 && !roots.contains(parent) { roots.append(parent) }
|
||||
return roots.filter { FileManager.default.fileExists(atPath: $0) }
|
||||
}
|
||||
|
||||
/// New TXT files / league folders in the watched folders become teams (e.g. a new "Testspiele" folder).
|
||||
/// Known files are left to reloadAll (new players only). Returns the new teams.
|
||||
@discardableResult
|
||||
public mutating func importNewFiles() -> [String] {
|
||||
let known = Set(sets.compactMap { $0.sourcePath.map { URL(fileURLWithPath: $0).standardizedFileURL.path } })
|
||||
var added: [String] = []
|
||||
for root in effectiveRoots {
|
||||
guard let e = FileManager.default.enumerator(at: URL(fileURLWithPath: root), includingPropertiesForKeys: nil,
|
||||
options: [.skipsHiddenFiles, .skipsPackageDescendants],
|
||||
errorHandler: { _, _ in true }) else { continue }
|
||||
let txts = e.compactMap { $0 as? URL }.filter { $0.pathExtension.lowercased() == "txt" }
|
||||
.filter { !known.contains($0.standardizedFileURL.path) }
|
||||
.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
|
||||
for t in txts { if let r = try? importFile(t) { added.append(r.team) } }
|
||||
}
|
||||
return added
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -499,3 +499,38 @@ final class SentLogMoveTests: XCTestCase {
|
||||
XCTAssertFalse(log.wasSent(PhotoItem(primary: old)))
|
||||
}
|
||||
}
|
||||
|
||||
final class CodePrefixTests: XCTestCase {
|
||||
func testRenamePrefixAndKeepItOnReload() {
|
||||
var set = CodeSet(name: "HSV", entries: [CodeEntry(code: "h10", columns: ["Spieler A"]),
|
||||
CodeEntry(code: "h7", columns: ["Spieler B"])])
|
||||
XCTAssertEqual(set.currentPrefix, "h")
|
||||
XCTAssertEqual(set.renamePrefix(from: "h", to: "hs"), 2)
|
||||
XCTAssertEqual(set.entries.map(\.code).sorted(), ["hs10", "hs7"])
|
||||
// reloading the TXT (still h-codes) brings no old codes back, new players get the new prefix
|
||||
let r = set.merge([CodeEntry(code: "h10", columns: ["Spieler A"]), CodeEntry(code: "h23", columns: ["Neu"])])
|
||||
XCTAssertEqual(r.added, 1)
|
||||
XCTAssertTrue(set.entries.contains { $0.code == "hs23" })
|
||||
XCTAssertFalse(set.entries.contains { $0.code.hasPrefix("h") && !$0.code.hasPrefix("hs") })
|
||||
// and on to another short code
|
||||
set.renamePrefix(from: "hs", to: "s")
|
||||
XCTAssertEqual(set.mapped("h5"), "s5")
|
||||
XCTAssertEqual(set.currentPrefix, "s")
|
||||
}
|
||||
|
||||
func testNewLeagueFolderIsPickedUp() throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let bl = root.appendingPathComponent("1. Bundesliga")
|
||||
try FileManager.default.createDirectory(at: bl, withIntermediateDirectories: true)
|
||||
try "w10\tA\n".write(to: bl.appendingPathComponent("VfL.txt"), atomically: true, encoding: .utf8)
|
||||
var lib = CodeLibrary()
|
||||
try lib.importFolder(root)
|
||||
let test = root.appendingPathComponent("Testspiele")
|
||||
try FileManager.default.createDirectory(at: test, withIntermediateDirectories: true)
|
||||
try "e9\tB\n".write(to: test.appendingPathComponent("Everton.txt"), atomically: true, encoding: .utf8)
|
||||
XCTAssertEqual(lib.importNewFiles(), ["Everton"])
|
||||
XCTAssertEqual(lib.sets.last?.league, "Testspiele")
|
||||
XCTAssertTrue(lib.importNewFiles().isEmpty)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user