DiagnostikApps/HADS-D/app.R
2026-09-22 18:35:43 +02:00

730 lines
27 KiB
R

# Präambel ####
PFAD_DOWNLOAD_SKRIPT = "../API/get_data_hadsd.R" # liefert beim Sourcen: daten_hadsd
PFAD_PSEUDONYM_SKRIPT = "../get_pseudo.R" # liefert beim Sourcen: pseudo
AKZENT_FARBE = "#8B2635"
HADSD_DISCLAIMER = paste0(
"Diese Auswertung ist ein Hilfsmittel fuer klinisches Fachpersonal und ersetzt ",
"keine klinische Diagnose. Die Interpretation obliegt der behandelnden Person."
)
# Verlauf gruen -> dunkelrot entspricht den 4 Antwortstufen 0-3.
HADSD_BADGE_FARBEN = c(
"0" = "#4CAF50",
"1" = "#F48FB1",
"2" = "#EF5350",
"3" = "#B71C1C"
)
HADSD_BADGE_TEXT_FARBEN = c(
"0" = "white",
"1" = "#333333",
"2" = "white",
"3" = "white"
)
library(shiny)
library(dplyr)
library(ggplot2)
library(haven)
library(officer)
library(DBI)
library(RSQLite)
# Infrastruktur ####
APP_VERZEICHNIS = normalizePath(getwd())
absPath = function(pfad) {
if (grepl("^([A-Za-z]:[/\\\\]|/)", pfad)) return(pfad)
file.path(APP_VERZEICHNIS, pfad)
}
PFAD_DOWNLOAD_SKRIPT = normalizePath(absPath(PFAD_DOWNLOAD_SKRIPT), mustWork = FALSE)
PFAD_PSEUDONYM_SKRIPT = normalizePath(absPath(PFAD_PSEUDONYM_SKRIPT), mustWork = FALSE)
# Helper ####
# Item -> Subskala-Zuordnung und Recode-Tabelle, verifiziert gegen
# "HADS-D_Hospital Anxiety and Depression Scale.pdf" (S. 1-4) und
# gegengeprueft mit "HADS-D_Auswertungshinweise.pdf" (S. 6-7).
# Die Choice-Texte sind in Druckreihenfolge (choice1 -> choice4) uebernommen,
# NICHT nach Wortlaut/Sympathie einer Option neu abgeleitet.
# Item 6 ist bewusst NICHT invertiert: die Druckreihenfolge der Antworten ist
# dort bereits "am wenigsten gluecklich zuerst", anders als bei den uebrigen
# Depressions-Items.
HADSD_ITEMS = list(
hadsd_01 = list(skala = "Angst", werte = c(
"meistens" = 3, "oft" = 2, "von Zeit zu Zeit/gelegentlich" = 1, "ueberhaupt nicht" = 0
)),
hadsd_02 = list(skala = "Depression", werte = c(
"ganz genau so" = 0, "nicht ganz so sehr" = 1, "nur noch ein wenig" = 2, "kaum oder gar nicht" = 3
)),
hadsd_03 = list(skala = "Angst", werte = c(
"ja, sehr stark" = 3, "ja, aber nicht allzu stark" = 2,
"etwas, aber es macht mir keine Sorgen" = 1, "ueberhaupt nicht" = 0
)),
hadsd_04 = list(skala = "Depression", werte = c(
"ja, so viel wie immer" = 0, "nicht mehr ganz so viel" = 1,
"inzwischen viel weniger" = 2, "ueberhaupt nicht" = 3
)),
hadsd_05 = list(skala = "Angst", werte = c(
"einen Grossteil der Zeit" = 3, "verhaeltnismaessig oft" = 2,
"von Zeit zu Zeit, aber nicht allzu oft" = 1, "nur gelegentlich/nie" = 0
)),
hadsd_06 = list(skala = "Depression", werte = c(
"ueberhaupt nicht" = 3, "selten" = 2, "manchmal" = 1, "meistens" = 0
)),
hadsd_07 = list(skala = "Angst", werte = c(
"ja, natuerlich" = 0, "gewoehnlich schon" = 1, "nicht oft" = 2, "ueberhaupt nicht" = 3
)),
hadsd_08 = list(skala = "Depression", werte = c(
"fast immer" = 3, "sehr oft" = 2, "manchmal" = 1, "ueberhaupt nicht" = 0
)),
hadsd_09 = list(skala = "Angst", werte = c(
"ueberhaupt nicht" = 0, "gelegentlich" = 1, "ziemlich oft" = 2, "sehr oft" = 3
)),
hadsd_10 = list(skala = "Depression", werte = c(
"ja, stimmt genau" = 3, "ich kuemmere mich nicht so sehr darum, wie ich sollte" = 2,
"moeglicherweise kuemmere ich mich zu wenig darum" = 1,
"ich kuemmere mich so viel darum wie immer" = 0
)),
hadsd_11 = list(skala = "Angst", werte = c(
"ja, tatsaechlich sehr" = 3, "ziemlich" = 2, "nicht sehr" = 1, "ueberhaupt nicht" = 0
)),
hadsd_12 = list(skala = "Depression", werte = c(
"ja, sehr" = 0, "eher weniger als frueher" = 1, "viel weniger als frueher" = 2,
"kaum bis gar nicht" = 3
)),
hadsd_13 = list(skala = "Angst", werte = c(
"ja, tatsaechlich sehr oft" = 3, "ziemlich oft" = 2, "nicht sehr oft" = 1, "ueberhaupt nicht" = 0
)),
hadsd_14 = list(skala = "Depression", werte = c(
"oft" = 0, "manchmal" = 1, "eher selten" = 2, "sehr selten" = 3
))
)
HADSD_ANGST_NR = c(1, 3, 5, 7, 9, 11, 13)
HADSD_DEPRESSION_NR = c(2, 4, 6, 8, 10, 12, 14)
HADSD_CUTOFF_ANGST = 10
HADSD_CUTOFF_DEPRESSION = 8
# Ob formr bei mc-Items (Typ "mc", nicht "mc_button") den Choice-TEXT direkt
# oder eine haven-labelled (dbl+lbl) Spalte mit Zahlenwert+Label exportiert,
# ist fuer diese formr-Installation nicht gegen echte Exportdaten verifiziert.
# Beide Faelle werden hier robust abgedeckt.
hadsd_choice_text = function(spalte) {
if (haven::is.labelled(spalte)) return(as.character(haven::as_factor(spalte)))
as.character(spalte)
}
# Vereinheitlicht Umlaute fuer robuste Lookup-Vergleiche, damit ein Encoding-
# Versatz zwischen xlsx-Choice-Text und Quelltext nicht zu einem stillen
# Nicht-Zuordnen fuehrt. Gross-/Kleinschreibung bleibt unveraendert erhalten
# (Vergleich bleibt case-sensitiv, wie in der Auswertungsvorgabe gefordert).
hadsd_normalisiere = function(text) {
text = gsub("ä", "ae", text); text = gsub("ö", "oe", text); text = gsub("ü", "ue", text)
text = gsub("Ä", "Ae", text); text = gsub("Ö", "Oe", text); text = gsub("Ü", "Ue", text)
text = gsub("ß", "ss", text)
trimws(text)
}
# Rekodiert ein einzelnes HADS-D-Item. Bei nicht zuordenbarem Text (NA, leerer
# String, unerwarteter Text) wird das Item als fehlend markiert (zuordenbar =
# FALSE), NIE stillschweigend als 0 gewertet.
hadsd_recode_item = function(item_key, rohwert) {
text_roh = hadsd_choice_text(rohwert)
text_roh = if (length(text_roh) == 0) NA_character_ else text_roh[1]
if (is.na(text_roh) || trimws(text_roh) == "") {
return(list(text = NA_character_, wert = NA_integer_, zuordenbar = FALSE))
}
text_norm = hadsd_normalisiere(text_roh)
werte_tab = HADSD_ITEMS[[item_key]]$werte
namen_norm = hadsd_normalisiere(names(werte_tab))
pos = match(text_norm, namen_norm)
if (is.na(pos)) {
return(list(text = trimws(text_roh), wert = NA_integer_, zuordenbar = FALSE))
}
list(text = trimws(text_roh), wert = as.integer(werte_tab[[pos]]), zuordenbar = TRUE)
}
# Entfernt formr-Markdown-Reste aus dem Itemtext: fuehrende Nummerierung
# (z.B. "1. " oder "01) ") und Fettschrift-Sternchen ("**Text**"), die im
# label-Attribut vorkommen koennen.
hadsd_item_label = function(label_attr) {
if (is.null(label_attr) || length(label_attr) == 0 || is.na(label_attr[1])) {
return(NA_character_)
}
txt = trimws(as.character(label_attr[1]))
txt = sub("^\\d+[.)]\\s*", "", txt)
txt = gsub("\\*\\*", "", txt)
trimws(txt)
}
# Summenscore je Subskala. Fehlt eines der 7 Items, wird NICHT summiert,
# sondern die/das fehlende(n) Itemnummer(n) werden zurueckgegeben.
hadsd_subskala_score = function(item_ergebnisse, item_nummern) {
werte = sapply(item_nummern, function(nr) item_ergebnisse[[sprintf("hadsd_%02d", nr)]]$wert)
fehlende_items = item_nummern[is.na(werte)]
if (length(fehlende_items) > 0) {
return(list(score = NA_integer_, auswertbar = FALSE, fehlende_items = fehlende_items))
}
list(score = as.integer(sum(werte)), auswertbar = TRUE, fehlende_items = integer(0))
}
# Binaeres Cutoff-Schema (Herrmann, Buss & Snaith, 1995), pro Subskala
# UNABHAENGIG angewendet. Die Quelle formuliert dies als einen Satz
# "Angst > 10 und Depression > 8 -> psychisch auffaellig"; das "und" wird hier
# als Aufzaehlung zweier getrennter, je Subskala unabhaengig geltender Cutoffs
# interpretiert (Standard-HADS-Auswertungslogik), NICHT als gemeinsame
# Bedingung, die beide Subskalen gleichzeitig ueberschreiten muesste. Diese
# Interpretation ist plausibel, aber nicht wortwoertlich als "unabhaengig" in
# der Quelle markiert - bei einem ersten Testfall mit nur einer auffaelligen
# Subskala kurz gegen die Original-PDF verifizieren. Kein dreistufiges Schema.
hadsd_klassifikation = function(score, cutoff) {
if (is.na(score)) return(NA_character_)
if (score > cutoff) "auffaellig" else "im Normbereich"
}
make_gauge_hadsd = function(score, cutoff, max_wert, titel) {
ggplot() +
geom_rect(aes(xmin = 0, xmax = cutoff, ymin = 0, ymax = 1),
fill = "#E8F5E9", color = NA) +
geom_rect(aes(xmin = cutoff, xmax = max_wert, ymin = 0, ymax = 1),
fill = "#FFEBEE", color = NA) +
geom_rect(aes(xmin = 0, xmax = max_wert, ymin = 0, ymax = 1),
fill = NA, color = "#9E9E9E", linewidth = 0.6) +
geom_vline(xintercept = cutoff, color = "#E65100", linetype = "dashed", linewidth = 1) +
geom_segment(aes(x = score, xend = score, y = -0.25, yend = 1.25),
color = AKZENT_FARBE, linewidth = 2.5) +
geom_label(aes(x = score, y = 1.6, label = paste0("Score: ", score)),
fill = AKZENT_FARBE, color = "white", fontface = "bold",
linewidth = 0, size = 4) +
annotate("text", x = cutoff, y = -0.55, label = paste0("Cutoff: ", cutoff),
color = "#E65100", size = 3.2, hjust = 0.5) +
scale_x_continuous(limits = c(-1, max_wert + 1), breaks = sort(unique(c(0, cutoff, max_wert)))) +
scale_y_continuous(limits = c(-0.8, 2.0)) +
theme_minimal(base_size = 12) +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank(),
axis.title.y = element_blank(),
plot.margin = margin(t = 5, r = 10, b = 5, l = 10)
) +
labs(x = paste0(titel, " (0-", max_wert, ")"), y = NULL)
}
# UI ####
app_css = "
body { font-family: 'Segoe UI', Arial, sans-serif; background: #f5f5f5; }
.container-fluid { max-width: 1100px; }
.app-header {
background: #8B2635; color: white; padding: 18px 24px 14px;
margin-bottom: 20px; border-radius: 0 0 6px 6px;
}
.app-header h2 { margin: 0; font-size: 1.5rem; font-weight: 600; }
.app-header p { margin: 4px 0 0; opacity: 0.85; font-size: 0.9rem; }
.input-panel {
background: white; border-radius: 6px; padding: 16px 20px;
margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,.12);
display: flex; align-items: flex-end; gap: 12px; flex-wrap: wrap;
}
.input-panel .form-group { margin-bottom: 0; }
.input-panel label { font-weight: 600; color: #333; }
.btn-laden {
background: #8B2635 !important; color: white !important;
border: none !important; border-radius: 4px !important;
padding: 8px 20px !important; font-weight: 600 !important; cursor: pointer;
}
.btn-laden:hover { background: #6d1e29 !important; }
.alert-fehler {
background: #FFEBEE; border-left: 5px solid #C62828;
padding: 12px 16px; border-radius: 4px; color: #B71C1C;
margin-bottom: 12px; font-weight: 500;
}
.alert-warnung {
background: #FFF3E0; border-left: 5px solid #E65100;
padding: 10px 16px; border-radius: 4px; color: #BF360C;
margin-bottom: 12px; font-size: 0.93em; font-weight: 500;
}
.abschnitt-karte {
background: white; border-radius: 6px; padding: 20px 24px;
margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,.12);
}
.abschnitt-titel {
color: #8B2635; font-size: 1.15rem; font-weight: 700;
border-bottom: 2px solid #8B2635; padding-bottom: 8px; margin-bottom: 14px;
}
.skalen-reihe { display: flex; gap: 16px; flex-wrap: wrap; }
.skalen-reihe .abschnitt-karte { flex: 1; min-width: 320px; }
.meta-block { margin-bottom: 10px; color: #555; font-size: 0.95em; }
.meta-block strong { color: #222; }
.score-zahl { font-size: 2.2rem; font-weight: 800; color: #8B2635; }
.cutoff-info { font-size: 0.88em; color: #555; margin-top: 4px; }
.nicht-auswertbar { font-size: 1.2rem; font-weight: 700; color: #B71C1C; }
.item-zeile {
display: flex; align-items: flex-start; gap: 10px;
padding: 7px 0; border-bottom: 1px solid #F0F0F0;
}
.item-nr { font-weight: 600; color: #8B2635; min-width: 26px; flex-shrink: 0; }
.item-text { flex: 1; color: #333; font-size: 0.92em; }
.item-skala {
font-size: 0.72em; font-weight: 700; text-transform: uppercase;
color: #888; min-width: 78px; flex-shrink: 0; padding-top: 2px;
}
.stufe-badge {
border-radius: 4px; padding: 2px 9px; font-weight: 700;
font-size: 0.82em; white-space: nowrap; display: inline-block; flex-shrink: 0;
}
.stufe-badge-0 { background: #4CAF50; color: white; }
.stufe-badge-1 { background: #F48FB1; color: #333333; }
.stufe-badge-2 { background: #EF5350; color: white; }
.stufe-badge-3 { background: #B71C1C; color: white; }
.stufe-badge-fehlend { background: #FEECEB; color: #B71C1C; }
"
app_css = gsub("#8B2635", AKZENT_FARBE, app_css, fixed = TRUE)
ui = fluidPage(
tags$head(
tags$meta(charset = "UTF-8"),
tags$style(HTML(app_css))
),
div(class = "app-header",
tags$h2("HADS-D - Hospital Anxiety and Depression Scale"),
tags$p("Deutsche Version | getrennte Auswertung der Subskalen Angst und Depression")
),
div(class = "container-fluid",
div(class = "input-panel",
div(style = "min-width: 360px; white-space: nowrap;",
textInput("pseudonym",
label = tagList(
"Pseudonym",
tags$span(style = "font-weight: normal; font-style: italic; font-size: 0.78em; color: #888; margin-left: 4px; white-space: nowrap;",
"optional, hat Vorrang vor Chiffre")
),
placeholder = "optional", width = "340px")
),
div(style = "min-width: 200px;",
textInput("chiffre", label = "Patientenchiffre",
placeholder = "z.B. P000123", width = "100%")
),
actionButton("btn_suchen", "Auswerten", class = "btn btn-primary btn-laden"),
div(style = "margin-left: auto;",
downloadButton("download_word", "Word-Export (.docx)")
)
),
uiOutput("fehler_ui"),
uiOutput("warnung_ui"),
uiOutput("ergebnis_ui")
)
)
# Word-Export ####
erstelle_hadsd_docx = function(erg) {
doc = read_docx()
fp_titel = fp_text(color = AKZENT_FARBE, bold = TRUE, font.size = 18)
fp_abschnitt = fp_text(color = AKZENT_FARBE, bold = TRUE, font.size = 13)
fp_label = fp_text(bold = TRUE, font.size = 11)
fp_normal = fp_text(font.size = 11)
fp_auffaellig = fp_text(bold = TRUE, font.size = 12, color = "#C62828")
fp_normbereich = fp_text(bold = TRUE, font.size = 12, color = "#2E7D32")
fp_fehlend = fp_text(bold = TRUE, font.size = 12, color = "#B71C1C")
fp_warnung = fp_text(font.size = 10, italic = TRUE, color = "#BF360C")
fp_disclaimer = fp_text(font.size = 9, italic = TRUE, color = "#777777")
doc = body_add_fpar(doc, fpar(ftext("HADS-D - Einzelauswertung", fp_titel)))
doc = body_add_fpar(doc, fpar(
ftext("Chiffre: ", fp_label), ftext(erg$chiffre, fp_normal),
ftext(" Ausfuelldatum: ", fp_label), ftext(erg$ausfuelldatum, fp_normal)
))
if (!is.null(erg$info_mehrere)) {
doc = body_add_fpar(doc, fpar(ftext(erg$info_mehrere, fp_warnung)))
}
doc = body_add_par(doc, "", style = "Normal")
fuege_subskala_hinzu = function(doc, titel, subskala, cutoff) {
doc = body_add_fpar(doc, fpar(ftext(titel, fp_abschnitt)))
if (!isTRUE(subskala$auswertbar)) {
doc = body_add_fpar(doc, fpar(ftext(
paste0("nicht auswertbar (Item(s) ", paste(subskala$fehlende_items, collapse = ", "),
" fehlen)"), fp_fehlend
)))
} else {
fp_score = if (identical(subskala$klassifikation, "auffaellig")) fp_auffaellig else fp_normbereich
doc = body_add_fpar(doc, fpar(
ftext(paste0("Summenscore: ", subskala$score, " / 21 (Cutoff: > ", cutoff, ") "), fp_label),
ftext(subskala$klassifikation, fp_score)
))
}
doc = body_add_par(doc, "", style = "Normal")
doc
}
doc = fuege_subskala_hinzu(doc, "Angst", erg$angst, HADSD_CUTOFF_ANGST)
doc = fuege_subskala_hinzu(doc, "Depression", erg$depression, HADSD_CUTOFF_DEPRESSION)
doc = body_add_fpar(doc, fpar(ftext("HADS-D Einzelitems", fp_abschnitt)))
for (nr in 1:14) {
it = erg$items[[sprintf("hadsd_%02d", nr)]]
stufe_key = if (isTRUE(it$zuordenbar)) as.character(it$wert) else NA_character_
antwort_txt = if (isTRUE(it$zuordenbar)) it$text else "nicht zuordenbar"
fp_badge = if (!is.na(stufe_key) && stufe_key %in% names(HADSD_BADGE_FARBEN)) {
fp_text(
color = HADSD_BADGE_TEXT_FARBEN[[stufe_key]], bold = TRUE,
shading.color = HADSD_BADGE_FARBEN[[stufe_key]], font.size = 10
)
} else {
fp_text(color = "#B71C1C", bold = TRUE, shading.color = "#FEECEB", font.size = 10)
}
doc = body_add_fpar(doc, fpar(
ftext(paste0(nr, ". [", it$skala, "] ", it$text_frage, " "), fp_normal),
ftext(paste0(" ", antwort_txt, " "), fp_badge)
))
}
doc = body_add_par(doc, "", style = "Normal")
doc = body_add_fpar(doc, fpar(ftext(HADSD_DISCLAIMER, fp_disclaimer)))
doc
}
# Server ####
server = function(input, output, session) {
observe({
query = parseQueryString(session$clientData$url_search)
if (!is.null(query$pseudonym) && nchar(trimws(query$pseudonym)) > 0) {
updateTextInput(session, "pseudonym", value = trimws(query$pseudonym))
}
})
observe({
query = parseQueryString(session$clientData$url_search)
if (!is.null(query$chiffre) && nchar(trimws(query$chiffre)) > 0) {
updateTextInput(session, "chiffre", value = toupper(trimws(query$chiffre)))
}
})
# Skripte werden NICHT beim App-Start gesourct, nur beim Klick.
ergebnis_r = eventReactive(input$btn_suchen, {
chiffre = toupper(trimws(input$chiffre))
if (nchar(trimws(input$pseudonym)) == 0 && nchar(chiffre) == 0) {
return(list(typ = "leere_eingabe", meldung = "Bitte Chiffre oder Pseudonym eingeben."))
}
if (nchar(trimws(input$pseudonym)) == 0 && !grepl("^[A-Z][0-9]{6}$", chiffre)) {
return(list(typ = "format_fehler", meldung = paste0(
"Ungueltige Chiffre '", chiffre, "'. Erwartet: ein Grossbuchstabe + 6 Ziffern (z.B. P000123)."
)))
}
if (!file.exists(PFAD_DOWNLOAD_SKRIPT)) {
return(list(typ = "pfad_fehler", meldung = paste0(
"Download-Skript nicht gefunden:\n", PFAD_DOWNLOAD_SKRIPT
)))
}
if (!file.exists(PFAD_PSEUDONYM_SKRIPT)) {
return(list(typ = "pfad_fehler", meldung = paste0(
"Pseudonym-Skript nicht gefunden:\n", PFAD_PSEUDONYM_SKRIPT
)))
}
ok = tryCatch({
source(PFAD_DOWNLOAD_SKRIPT, local = FALSE)
list(ok = TRUE)
}, error = function(e) list(ok = FALSE, msg = e$message))
if (!ok$ok) return(list(typ = "skript_fehler", meldung = paste0(
"Fehler im Download-Skript: ", ok$msg
)))
db_ordner = local({
ordner = dirname(normalizePath(PFAD_PSEUDONYM_SKRIPT, mustWork = FALSE))
gefunden = NULL
for (i in 1:5) {
if (file.exists(file.path(ordner, "pseudonyme.db"))) { gefunden = ordner; break }
elternteil = dirname(ordner)
if (elternteil == ordner) break
ordner = elternteil
}
gefunden
})
if (is.null(db_ordner)) {
return(list(typ = "db_fehler", meldung = paste0(
"pseudonyme.db nicht gefunden (bis 5 Ebenen oberhalb von ",
dirname(normalizePath(PFAD_PSEUDONYM_SKRIPT, mustWork = FALSE)), " gesucht)."
)))
}
alter_wd = getwd()
on.exit(setwd(alter_wd), add = TRUE)
setwd(db_ordner)
ok = tryCatch({
source(PFAD_PSEUDONYM_SKRIPT, local = FALSE)
list(ok = TRUE)
}, error = function(e) list(ok = FALSE, msg = e$message))
if (!ok$ok) return(list(typ = "skript_fehler", meldung = paste0(
"Fehler im Pseudonym-Skript: ", ok$msg
)))
if (!exists("daten_hadsd", envir = .GlobalEnv) ||
!is.data.frame(get("daten_hadsd", envir = .GlobalEnv))) {
return(list(typ = "daten_fehler", meldung = paste0(
"Objekt 'daten_hadsd' nach dem Sourcen nicht gefunden oder kein Dataframe. ",
"Bitte Download-Skript pruefen."
)))
}
if (!exists("pseudo", envir = .GlobalEnv) ||
!is.data.frame(get("pseudo", envir = .GlobalEnv))) {
return(list(typ = "daten_fehler", meldung = paste0(
"Objekt 'pseudo' nach dem Sourcen nicht gefunden oder kein Dataframe. ",
"Bitte Pseudonym-Skript pruefen."
)))
}
daten_hadsd = get("daten_hadsd", envir = .GlobalEnv)
pseudo = get("pseudo", envir = .GlobalEnv)
if (nchar(trimws(input$pseudonym)) > 0) {
pw_treffer = pseudo[pseudo$pseudonym == trimws(input$pseudonym), ]
if (nrow(pw_treffer) > 0) chiffre = toupper(trimws(pw_treffer$chiffre[1]))
}
treffer_ps = pseudo[toupper(trimws(as.character(pseudo$chiffre))) == chiffre, ]
if (nrow(treffer_ps) == 0) {
return(list(typ = "chiffre_nicht_gefunden", meldung = paste0(
"Chiffre '", chiffre, "' wurde in der Pseudonym-Datenbank nicht gefunden."
)))
}
alle_session_ids = unique(treffer_ps$pseudonym)
if (nchar(trimws(input$pseudonym)) > 0) alle_session_ids = trimws(input$pseudonym)
treffer_dat = daten_hadsd[daten_hadsd$session %in% alle_session_ids, , drop = FALSE]
if (nrow(treffer_dat) == 0) {
return(list(typ = "session_nicht_gefunden", meldung = paste0(
"Kein HADS-D-Datensatz fuer Chiffre '", chiffre, "' gefunden. (",
length(alle_session_ids), " Pseudonym(e) geprueft)"
)))
}
info_mehrere = NULL
if (nrow(treffer_dat) > 1) {
n = nrow(treffer_dat)
treffer_dat = treffer_dat[order(treffer_dat$created, decreasing = TRUE), ]
datum_neu = tryCatch(
format(as.POSIXct(treffer_dat$created[1]), "%d.%m.%Y %H:%M"),
error = function(e) "unbekanntes Datum"
)
info_mehrere = paste0(
"Mehrere Ausfuellungen gefunden (", n, " Eintraege). ",
"Angezeigt wird die neueste vom ", datum_neu, "."
)
treffer_dat = treffer_dat[1, , drop = FALSE]
}
zeile = treffer_dat[1, , drop = FALSE]
ausfuelldatum = tryCatch(
format(as.POSIXct(zeile[["created"]][1]), "%d.%m.%Y"),
error = function(e) format(Sys.Date(), "%d.%m.%Y")
)
items = lapply(1:14, function(nr) {
var = sprintf("hadsd_%02d", nr)
erg_item = hadsd_recode_item(var, zeile[[var]])
c(erg_item, list(
nr = nr,
skala = HADSD_ITEMS[[var]]$skala,
text_frage = if (!is.null(daten_hadsd[[var]])) {
txt = hadsd_item_label(attr(daten_hadsd[[var]], "label"))
if (is.na(txt)) paste0("Item ", nr) else txt
} else paste0("Item ", nr)
))
})
names(items) = sprintf("hadsd_%02d", 1:14)
angst = hadsd_subskala_score(items, HADSD_ANGST_NR)
angst$klassifikation = hadsd_klassifikation(angst$score, HADSD_CUTOFF_ANGST)
depression = hadsd_subskala_score(items, HADSD_DEPRESSION_NR)
depression$klassifikation = hadsd_klassifikation(depression$score, HADSD_CUTOFF_DEPRESSION)
list(
typ = "ok",
chiffre = chiffre,
ausfuelldatum = ausfuelldatum,
info_mehrere = info_mehrere,
items = items,
angst = angst,
depression = depression
)
})
output$fehler_ui = renderUI({
req(input$btn_suchen)
d = ergebnis_r()
if (!identical(d$typ, "ok")) div(class = "alert-fehler", d$meldung)
})
output$warnung_ui = renderUI({
req(input$btn_suchen)
d = ergebnis_r()
if (!identical(d$typ, "ok") || is.null(d$info_mehrere)) return(NULL)
div(class = "alert-warnung", d$info_mehrere)
})
output$ergebnis_ui = renderUI({
req(input$btn_suchen)
d = ergebnis_r()
if (!identical(d$typ, "ok")) return(NULL)
subskala_karte = function(titel, subskala, cutoff, gauge_id) {
div(class = "abschnitt-karte",
div(class = "abschnitt-titel", titel),
if (!isTRUE(subskala$auswertbar)) {
div(class = "nicht-auswertbar", paste0(
"nicht auswertbar (Item(s) ", paste(subskala$fehlende_items, collapse = ", "), " fehlen)"
))
} else {
tagList(
div(class = "score-zahl", paste0(subskala$score, " / 21")),
div(class = "cutoff-info",
if (identical(subskala$klassifikation, "auffaellig")) {
tags$span(style = "color:#B71C1C; font-weight:600;",
paste0(subskala$score, " > ", cutoff, ": auffaellig"))
} else {
tags$span(style = "color:#2E7D32; font-weight:600;",
paste0(subskala$score, " <= ", cutoff, ": im Normbereich"))
}
),
plotOutput(gauge_id, height = "150px")
)
}
)
}
item_liste = function(item_nummern, titel) {
div(class = "abschnitt-karte",
div(class = "abschnitt-titel", titel),
lapply(item_nummern, function(nr) {
it = d$items[[sprintf("hadsd_%02d", nr)]]
stufe_key = if (isTRUE(it$zuordenbar)) as.character(it$wert) else NA_character_
badge_klasse = if (!is.na(stufe_key)) {
paste0("stufe-badge stufe-badge-", stufe_key)
} else {
"stufe-badge stufe-badge-fehlend"
}
antwort_txt = if (isTRUE(it$zuordenbar)) it$text else "nicht zuordenbar"
div(class = "item-zeile",
div(class = "item-nr", paste0(nr, ".")),
div(class = "item-skala", it$skala),
div(class = "item-text", it$text_frage),
span(class = badge_klasse, antwort_txt)
)
})
)
}
tagList(
div(class = "meta-block",
tags$strong("Chiffre: "), d$chiffre,
tags$span(" | ", style = "color:#ccc;"),
tags$strong("Ausfuelldatum: "), d$ausfuelldatum
),
div(class = "skalen-reihe",
subskala_karte("Angst", d$angst, HADSD_CUTOFF_ANGST, "gauge_angst"),
subskala_karte("Depression", d$depression, HADSD_CUTOFF_DEPRESSION, "gauge_depression")
),
item_liste(HADSD_ANGST_NR, "Angst-Items"),
item_liste(HADSD_DEPRESSION_NR, "Depression-Items"),
div(class = "disclaimer-block",
style = "font-size: 0.82em; color: #777; font-style: italic; margin-top: 4px;",
HADSD_DISCLAIMER
)
)
})
output$gauge_angst = renderPlot({
d = ergebnis_r()
req(identical(d$typ, "ok"), isTRUE(d$angst$auswertbar))
make_gauge_hadsd(d$angst$score, HADSD_CUTOFF_ANGST, 21, "Angst")
}, bg = "transparent")
output$gauge_depression = renderPlot({
d = ergebnis_r()
req(identical(d$typ, "ok"), isTRUE(d$depression$auswertbar))
make_gauge_hadsd(d$depression$score, HADSD_CUTOFF_DEPRESSION, 21, "Depression")
}, bg = "transparent")
output$download_word = downloadHandler(
filename = function() {
d = tryCatch(ergebnis_r(), error = function(e) NULL)
chiffre_esc = if (is.list(d) && identical(d$typ, "ok") && nchar(d$chiffre) > 0) {
gsub("[^A-Za-z0-9_-]", "_", d$chiffre)
} else {
"export"
}
ausfuelldatum_fn = tryCatch(
format(as.Date(d$ausfuelldatum, "%d.%m.%Y"), "%Y%m%d"),
error = function(e) format(Sys.Date(), "%Y%m%d")
)
if (is.na(ausfuelldatum_fn) || length(ausfuelldatum_fn) == 0) {
ausfuelldatum_fn = format(Sys.Date(), "%Y%m%d")
}
paste0("HADSD_", chiffre_esc, "_", ausfuelldatum_fn, ".docx")
},
content = function(file) {
d = tryCatch(ergebnis_r(), error = function(e) NULL)
daten_ok = is.list(d) && identical(d$typ, "ok")
if (!daten_ok) {
doc = read_docx()
doc = body_add_par(doc,
"Kein Datensatz geladen. Bitte zuerst Chiffre oder Pseudonym eingeben und 'Auswerten' klicken.",
style = "Normal")
print(doc, target = file)
return()
}
doc = tryCatch(
erstelle_hadsd_docx(d),
error = function(e) {
err_doc = read_docx()
body_add_par(err_doc,
paste0("Fehler beim Erstellen des Word-Dokuments: ", e$message),
style = "Normal")
}
)
print(doc, target = file)
}
)
}
# Start ####
shinyApp(ui, server)