Build persistent patient library and image viewer
This commit is contained in:
1 parent
d861462e55
commit
48177fc7fb
5 files changed
+437
-112
No files matched your search
@@ -0,0 +1,118 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
import ImageIO
|
||||
|
||||
struct PatientRecord: Codable, Identifiable {
|
||||
let id: UUID
|
||||
var name: String
|
||||
var chartNumber: String
|
||||
var images: [PatientImage] = []
|
||||
}
|
||||
|
||||
struct PatientImage: Codable, Identifiable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let importedAt: Date
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PatientLibrary: ObservableObject {
|
||||
@Published private(set) var patients: [PatientRecord] = []
|
||||
@Published private(set) var loadError: String?
|
||||
|
||||
private let directory: URL
|
||||
private var index: URL { directory.appendingPathComponent("patients.json") }
|
||||
|
||||
init(directory: URL = URL.applicationSupportDirectory.appendingPathComponent("EzDent/Library")) {
|
||||
self.directory = directory
|
||||
do {
|
||||
if FileManager.default.fileExists(atPath: index.path) {
|
||||
patients = try JSONDecoder().decode([PatientRecord].self, from: Data(contentsOf: index))
|
||||
}
|
||||
} catch {
|
||||
loadError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func savePatient(id: UUID?, name: String, chartNumber: String) throws -> UUID {
|
||||
let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let chartNumber = chartNumber.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !name.isEmpty, !chartNumber.isEmpty else { throw LibraryError.missingFields }
|
||||
guard !patients.contains(where: {
|
||||
$0.id != id && $0.chartNumber.caseInsensitiveCompare(chartNumber) == .orderedSame
|
||||
}) else { throw LibraryError.duplicateChart }
|
||||
|
||||
var updated = patients
|
||||
let patientID = id ?? UUID()
|
||||
if let position = updated.firstIndex(where: { $0.id == patientID }) {
|
||||
updated[position].name = name
|
||||
updated[position].chartNumber = chartNumber
|
||||
} else {
|
||||
updated.append(PatientRecord(id: patientID, name: name, chartNumber: chartNumber))
|
||||
}
|
||||
try save(updated)
|
||||
return patientID
|
||||
}
|
||||
|
||||
func importImage(from source: URL, for patientID: UUID) throws -> PatientImage {
|
||||
guard let position = patients.firstIndex(where: { $0.id == patientID }) else {
|
||||
throw LibraryError.patientMissing
|
||||
}
|
||||
try prepareDirectory()
|
||||
let hasAccess = source.startAccessingSecurityScopedResource()
|
||||
defer { if hasAccess { source.stopAccessingSecurityScopedResource() } }
|
||||
|
||||
guard let imageSource = CGImageSourceCreateWithURL(source as CFURL, nil),
|
||||
CGImageSourceGetCount(imageSource) > 0,
|
||||
CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) != nil else {
|
||||
throw LibraryError.unsupportedImage
|
||||
}
|
||||
|
||||
let image = PatientImage(id: UUID(), name: source.lastPathComponent, importedAt: Date())
|
||||
let destination = url(for: image)
|
||||
try FileManager.default.copyItem(at: source, to: destination)
|
||||
do {
|
||||
var updated = patients
|
||||
updated[position].images.insert(image, at: 0)
|
||||
try save(updated)
|
||||
} catch {
|
||||
try? FileManager.default.removeItem(at: destination)
|
||||
throw error
|
||||
}
|
||||
return image
|
||||
}
|
||||
|
||||
func url(for image: PatientImage) -> URL {
|
||||
directory.appendingPathComponent(image.id.uuidString)
|
||||
}
|
||||
|
||||
private func prepareDirectory() throws {
|
||||
guard loadError == nil else { throw LibraryError.indexUnavailable }
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: [.posixPermissions: 0o700]
|
||||
)
|
||||
}
|
||||
|
||||
private func save(_ updated: [PatientRecord]) throws {
|
||||
try prepareDirectory()
|
||||
let sorted = updated.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
|
||||
try JSONEncoder().encode(sorted).write(to: index, options: .atomic)
|
||||
patients = sorted
|
||||
}
|
||||
}
|
||||
|
||||
private enum LibraryError: LocalizedError {
|
||||
case missingFields, duplicateChart, patientMissing, unsupportedImage, indexUnavailable
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingFields: return "Введите имя и номер карты."
|
||||
case .duplicateChart: return "Карточка с таким номером уже существует."
|
||||
case .patientMissing: return "Карточка пациента недоступна."
|
||||
case .unsupportedImage: return "Формат снимка не поддерживается."
|
||||
case .indexUnavailable: return "Индекс библиотеки недоступен."
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user