Connect EzDent to the original EzServer API
This commit is contained in:
1 parent
8d93e526c3
commit
b11a8f62f9
13 files changed
+855
-108
No files matched your search
@@ -1,20 +1,33 @@
|
||||
import EzDentStorage
|
||||
import AppKit
|
||||
import ImageIO
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct PatientWorkspace: View {
|
||||
let server: ServerAPI?
|
||||
@EnvironmentObject private var connection: ServerConnection
|
||||
@State private var serverPatients: [PatientRecord] = []
|
||||
@State private var serverChart: ServerAPI.Chart?
|
||||
@State private var nextPatientPage: Int?
|
||||
@State private var exactChartOnly = false
|
||||
@State private var isSearching = false
|
||||
@State private var searchError: String?
|
||||
@State private var searchRevision = 0
|
||||
@State private var detailError: String?
|
||||
@State private var detailRevision = 0
|
||||
@EnvironmentObject private var library: PatientLibrary
|
||||
@State private var search = ""
|
||||
@State private var patientID: PatientRecord.ID?
|
||||
@State private var imageID: PatientImage.ID?
|
||||
@State private var editor: PatientEditor?
|
||||
@State private var importPatientID: PatientRecord.ID?
|
||||
@State private var importPatient: PatientRecord?
|
||||
@State private var showImporter = false
|
||||
@State private var isImporting = false
|
||||
@State private var errorMessage: String?
|
||||
|
||||
private var filteredPatients: [PatientRecord] {
|
||||
if server != nil { return serverPatients }
|
||||
let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return library.patients.filter {
|
||||
query.isEmpty || $0.name.localizedStandardContains(query)
|
||||
@@ -23,7 +36,8 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
|
||||
private var patient: PatientRecord? {
|
||||
library.patients.first { $0.id == patientID }
|
||||
if server != nil { return serverChart?.patient.id == patientID ? serverChart?.patient : nil }
|
||||
return library.patients.first { $0.id == patientID }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
@@ -43,11 +57,20 @@ struct PatientWorkspace: View {
|
||||
.background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))
|
||||
.padding(12)
|
||||
|
||||
if filteredPatients.isEmpty, !search.isEmpty {
|
||||
if isSearching {
|
||||
ProgressView().controlSize(.small).padding(.bottom, 8)
|
||||
} else if let searchError {
|
||||
Text(searchError).foregroundStyle(.secondary).padding(.horizontal, 12)
|
||||
Button("Повторить поиск") { searchRevision += 1 }
|
||||
} else if filteredPatients.isEmpty, !search.isEmpty {
|
||||
Text("Пациенты не найдены")
|
||||
.foregroundStyle(.secondary)
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
if exactChartOnly {
|
||||
Text("EzServer поддерживает только поиск по точному номеру карты.")
|
||||
.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 12)
|
||||
}
|
||||
List(filteredPatients, selection: $patientID) { record in
|
||||
Label {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
@@ -62,6 +85,14 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
|
||||
if let page = nextPatientPage {
|
||||
Button("Показать ещё") {
|
||||
let query = search
|
||||
Task { await searchServer(query, page: page) }
|
||||
}
|
||||
.disabled(isSearching)
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
Divider()
|
||||
Button { newPatient() } label: {
|
||||
Label("Новый пациент", systemImage: "plus")
|
||||
@@ -69,13 +100,24 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
.controlSize(.large)
|
||||
.padding(12)
|
||||
.disabled(library.loadError != nil)
|
||||
.disabled(server == nil && library.loadError != nil)
|
||||
}
|
||||
.navigationTitle("Пациенты")
|
||||
.navigationTitle(server == nil ? "Пациенты" : "Пациенты EzServer")
|
||||
.navigationSplitViewColumnWidth(min: 220, ideal: 260)
|
||||
} detail: {
|
||||
if let patient {
|
||||
patientDetail(patient)
|
||||
} else if server != nil {
|
||||
if let detailError {
|
||||
emptyState("Карточка недоступна", detail: detailError, icon: "exclamationmark.triangle") {
|
||||
Button("Повторить") { detailRevision += 1 }
|
||||
}
|
||||
} else if patientID != nil {
|
||||
ProgressView("Загрузка карточки…")
|
||||
} else {
|
||||
emptyState("Выберите пациента", detail: "Найдите на EzServer карточку по имени или номеру.",
|
||||
icon: "person.crop.rectangle")
|
||||
}
|
||||
} else if let error = library.loadError {
|
||||
emptyState("Библиотека недоступна", detail: error, icon: "exclamationmark.triangle")
|
||||
} else if library.patients.isEmpty {
|
||||
@@ -88,20 +130,42 @@ struct PatientWorkspace: View {
|
||||
emptyState("Выберите пациента", detail: "Найдите карточку по имени или номеру.", icon: "person.crop.rectangle")
|
||||
}
|
||||
}
|
||||
.toolbar {
|
||||
if server != nil {
|
||||
Button("Локальный режим") { connection.active = nil }
|
||||
.disabled(isImporting || editor != nil)
|
||||
}
|
||||
}
|
||||
.task(id: SearchRequest(query: search, revision: searchRevision)) {
|
||||
await searchServer(search)
|
||||
}
|
||||
.task(id: DetailRequest(patient: patientID, revision: detailRevision)) {
|
||||
await loadServerPatient(patientID)
|
||||
}
|
||||
.onChange(of: patientID) { _ in
|
||||
imageID = patient?.images.first?.id
|
||||
detailError = nil
|
||||
}
|
||||
.sheet(item: $editor) { draft in
|
||||
PatientEditorSheet(draft: draft) { name, chart in
|
||||
let id = try library.savePatient(id: draft.patientID, name: name, chartNumber: chart)
|
||||
search = ""
|
||||
patientID = id
|
||||
if let server {
|
||||
let record = try await server.create(name: name, chartNumber: chart)
|
||||
serverChart = ServerAPI.Chart(patient: record, images: [])
|
||||
serverPatients.insert(record, at: 0)
|
||||
search = record.chartNumber
|
||||
searchRevision += 1
|
||||
patientID = record.id
|
||||
} else {
|
||||
let id = try library.savePatient(id: draft.patientID, name: name, chartNumber: chart)
|
||||
search = ""
|
||||
patientID = id
|
||||
}
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.data, .folder], allowsMultipleSelection: true,
|
||||
onCompletion: { result in
|
||||
guard let patient = importPatientID else { return }
|
||||
importPatientID = nil
|
||||
guard let patient = importPatient else { return }
|
||||
importPatient = nil
|
||||
isImporting = true
|
||||
Task {
|
||||
defer { isImporting = false }
|
||||
@@ -126,10 +190,12 @@ struct PatientWorkspace: View {
|
||||
Text("Карта № \(record.chartNumber)").foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Button { editor = PatientEditor(record) } label: {
|
||||
Label("Править карточку", systemImage: "pencil")
|
||||
if server == nil {
|
||||
Button { editor = PatientEditor(record) } label: {
|
||||
Label("Править карточку", systemImage: "pencil")
|
||||
}
|
||||
}
|
||||
Button { chooseImages(for: record.id) } label: {
|
||||
Button { chooseImages(for: record) } label: {
|
||||
Label("Добавить снимки…", systemImage: "plus")
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
@@ -142,7 +208,8 @@ struct PatientWorkspace: View {
|
||||
Divider()
|
||||
|
||||
if record.images.isEmpty {
|
||||
emptyState("Снимков пока нет", detail: "Выберите изображение или все DICOM-срезы одной серии.",
|
||||
emptyState("Снимков пока нет", detail: server == nil ? "Выберите изображение или все DICOM-срезы одной серии."
|
||||
: "Выберите изображение или 2D-файл DICOM.",
|
||||
icon: "photo.on.rectangle")
|
||||
} else {
|
||||
let selected = record.images.first { $0.id == imageID } ?? record.images[0]
|
||||
@@ -150,8 +217,10 @@ struct PatientWorkspace: View {
|
||||
List(record.images, selection: $imageID) { image in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(image.name).lineLimit(2)
|
||||
Text(image.importedAt.formatted(date: .abbreviated, time: .shortened))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
if image.importedAt != .distantPast {
|
||||
Text(image.importedAt.formatted(date: .abbreviated, time: .shortened))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 5)
|
||||
.tag(image.id)
|
||||
@@ -159,7 +228,9 @@ struct PatientWorkspace: View {
|
||||
.frame(width: 200)
|
||||
Divider()
|
||||
Group {
|
||||
if selected.dicomCount != nil {
|
||||
if let server, let image = serverChart?.images.first(where: { $0.id == selected.id }) {
|
||||
ServerImagePreview(api: server, image: image) { errorMessage = $0 }
|
||||
} else if selected.dicomCount != nil {
|
||||
DICOMViewer(urls: library.dicomURLs(for: selected), name: selected.name)
|
||||
} else {
|
||||
ImageViewer(image: selected, url: library.url(for: selected)) { message in
|
||||
@@ -178,12 +249,13 @@ struct PatientWorkspace: View {
|
||||
editor = PatientEditor(nil)
|
||||
}
|
||||
|
||||
private func chooseImages(for id: UUID) {
|
||||
importPatientID = id
|
||||
private func chooseImages(for patient: PatientRecord) {
|
||||
importPatient = patient
|
||||
showImporter = true
|
||||
}
|
||||
|
||||
private func importImages(_ result: Result<[URL], Error>, for importPatientID: UUID) async {
|
||||
private func importImages(_ result: Result<[URL], Error>, for targetChart: PatientRecord) async {
|
||||
let importPatientID = targetChart.id
|
||||
do {
|
||||
var errors: [String] = []
|
||||
var firstImported: UUID?
|
||||
@@ -197,7 +269,19 @@ struct PatientWorkspace: View {
|
||||
|
||||
for series in files.series {
|
||||
do {
|
||||
let image = try await library.importDICOM(from: series, for: importPatientID)
|
||||
let image: PatientImage
|
||||
if let server {
|
||||
guard series.count == 1 else { throw ServerError.seriesUpload }
|
||||
let source = series[0]
|
||||
let frames = try await Task.detached(priority: .userInitiated) {
|
||||
try DICOMVolume(urls: [source]).size.z
|
||||
}.value
|
||||
guard frames == 1 else { throw ServerError.seriesUpload }
|
||||
let uploaded = try await server.upload(source, chart: targetChart.chartNumber, dicom: true)
|
||||
image = uploaded.record
|
||||
} else {
|
||||
image = try await library.importDICOM(from: series, for: importPatientID)
|
||||
}
|
||||
firstImported = firstImported ?? image.id
|
||||
} catch {
|
||||
errors.append("\(series[0].lastPathComponent) — \(error.localizedDescription)")
|
||||
@@ -205,14 +289,33 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
for url in files.images {
|
||||
do {
|
||||
let image = try library.importImage(from: url, for: importPatientID)
|
||||
let image: PatientImage
|
||||
if let server {
|
||||
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
|
||||
CGImageSourceGetCount(source) > 0,
|
||||
CGImageSourceCopyPropertiesAtIndex(source, 0, nil) != nil else {
|
||||
throw ServerError.invalidFile
|
||||
}
|
||||
let uploaded = try await server.upload(url, chart: targetChart.chartNumber, dicom: false)
|
||||
image = uploaded.record
|
||||
} else {
|
||||
image = try library.importImage(from: url, for: importPatientID)
|
||||
}
|
||||
firstImported = firstImported ?? image.id
|
||||
} catch {
|
||||
errors.append("\(url.lastPathComponent) — \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
if patientID == importPatientID, let firstImported {
|
||||
imageID = firstImported
|
||||
if let server {
|
||||
do {
|
||||
let updated = try await server.chartImages(for: targetChart)
|
||||
if patientID == importPatientID { serverChart = updated }
|
||||
} catch {
|
||||
errors.append("Обновление списка снимков — \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
if patientID == importPatientID { imageID = firstImported }
|
||||
}
|
||||
if files.images.isEmpty, files.series.isEmpty {
|
||||
errors.append("В выбранных папках нет поддерживаемых снимков.")
|
||||
@@ -223,6 +326,62 @@ struct PatientWorkspace: View {
|
||||
}
|
||||
}
|
||||
|
||||
private struct SearchRequest: Equatable {
|
||||
let query: String
|
||||
let revision: Int
|
||||
}
|
||||
|
||||
private struct DetailRequest: Equatable {
|
||||
let patient: UUID?
|
||||
let revision: Int
|
||||
}
|
||||
|
||||
private func searchServer(_ query: String, page: Int = 0) async {
|
||||
guard let server, search == query, page == 0 || !isSearching else { return }
|
||||
let revision = searchRevision
|
||||
if page == 0 {
|
||||
nextPatientPage = nil
|
||||
exactChartOnly = false
|
||||
}
|
||||
isSearching = true
|
||||
searchError = nil
|
||||
do {
|
||||
if page == 0 { try await Task.sleep(for: .milliseconds(250)) }
|
||||
let listing = try await server.search(query, page: page)
|
||||
try Task.checkCancellation()
|
||||
guard search == query, revision == searchRevision else { return }
|
||||
let existing = page == 0 ? Set<UUID>() : Set(serverPatients.map(\.id))
|
||||
let newPatients = listing.patients.filter { !existing.contains($0.id) }
|
||||
if page == 0 {
|
||||
serverPatients = newPatients
|
||||
} else {
|
||||
serverPatients += newPatients
|
||||
}
|
||||
nextPatientPage = listing.hasNextPage && !newPatients.isEmpty ? page + 1 : nil
|
||||
exactChartOnly = listing.exactChartOnly
|
||||
} catch {
|
||||
guard !Task.isCancelled, search == query, revision == searchRevision else { return }
|
||||
searchError = error.localizedDescription
|
||||
}
|
||||
isSearching = false
|
||||
}
|
||||
|
||||
private func loadServerPatient(_ id: UUID?) async {
|
||||
guard let server, let id, serverChart?.patient.id != id,
|
||||
let summary = serverPatients.first(where: { $0.id == id }) else { return }
|
||||
do {
|
||||
let chart = try await server.chart(summary.chartNumber)
|
||||
try Task.checkCancellation()
|
||||
guard patientID == id else { return }
|
||||
serverChart = chart
|
||||
imageID = chart.patient.images.first?.id
|
||||
detailError = nil
|
||||
} catch {
|
||||
guard !Task.isCancelled, patientID == id else { return }
|
||||
detailError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func emptyState(
|
||||
_ title: String, detail: String, icon: String,
|
||||
@ViewBuilder action: () -> some View = { EmptyView() }
|
||||
@@ -309,9 +468,10 @@ private struct PatientEditorSheet: View {
|
||||
@State private var chartNumber: String
|
||||
@State private var error: String?
|
||||
let isNew: Bool
|
||||
let save: (String, String) throws -> Void
|
||||
@State private var isSaving = false
|
||||
let save: (String, String) async throws -> Void
|
||||
|
||||
init(draft: PatientEditor, save: @escaping (String, String) throws -> Void) {
|
||||
init(draft: PatientEditor, save: @escaping (String, String) async throws -> Void) {
|
||||
_name = State(initialValue: draft.name)
|
||||
_chartNumber = State(initialValue: draft.chartNumber)
|
||||
isNew = draft.patientID == nil
|
||||
@@ -328,17 +488,21 @@ private struct PatientEditorSheet: View {
|
||||
if let error { Text(error).foregroundStyle(.red) }
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Отмена") { dismiss() }.keyboardShortcut(.cancelAction)
|
||||
Button("Отмена") { dismiss() }.keyboardShortcut(.cancelAction).disabled(isSaving)
|
||||
Button("Сохранить") {
|
||||
do {
|
||||
try save(name, chartNumber)
|
||||
dismiss()
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
isSaving = true
|
||||
Task {
|
||||
defer { isSaving = false }
|
||||
do {
|
||||
try await save(name, chartNumber)
|
||||
dismiss()
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
.disabled(isSaving || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
|| chartNumber.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -346,3 +510,44 @@ private struct PatientEditorSheet: View {
|
||||
.frame(width: 440)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ServerImagePreview: View {
|
||||
let api: ServerAPI
|
||||
let image: ServerAPI.ServerImage
|
||||
let reportError: (String) -> Void
|
||||
|
||||
@State private var originals: ServerOriginals?
|
||||
@State private var error: String?
|
||||
@State private var retry = 0
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let originals {
|
||||
if originals.isDICOM {
|
||||
DICOMViewer(urls: originals.urls, name: image.record.name)
|
||||
} else {
|
||||
ImageViewer(image: image.record, url: originals.urls[0], reportError: reportError)
|
||||
}
|
||||
} else if let error {
|
||||
VStack(spacing: 12) {
|
||||
Text(error)
|
||||
Button("Повторить загрузку") { retry += 1 }
|
||||
}
|
||||
} else {
|
||||
ProgressView("Загрузка оригиналов с EzServer…")
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.task(id: retry) {
|
||||
error = nil
|
||||
do {
|
||||
let downloaded = try await api.download(image)
|
||||
try Task.checkCancellation()
|
||||
originals = downloaded
|
||||
} catch {
|
||||
guard !Task.isCancelled else { return }
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user