Skip to content

Commit

Permalink
Merge pull request #1 from AudreiPavanello/New_features_added
Browse files Browse the repository at this point in the history
Add new features
  • Loading branch information
AudreiPavanello authored Oct 31, 2024
2 parents 58f6a9d + b4d091c commit eb36f69
Show file tree
Hide file tree
Showing 6 changed files with 428 additions and 132 deletions.
24 changes: 24 additions & 0 deletions R/constants.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# System and location definitions
info_systems <- c(
"Sistema de Informações sobre Mortalidade (SIM-DO)" = "SIM-DO",
"Sistema de Informações sobre Nascidos Vivos (SINASC)" = "SINASC",
"Sistema de Informações Hospitalares (SIH-RD)" = "SIH-RD",
"Sistema de Informações Ambulatoriais (SIA-PA)" = "SIA-PA"
)

estados <- c(
"Acre" = "AC", "Alagoas" = "AL", "Amapá" = "AP", "Amazonas" = "AM",
"Bahia" = "BA", "Ceará" = "CE", "Distrito Federal" = "DF",
"Espírito Santo" = "ES", "Goiás" = "GO", "Maranhão" = "MA",
"Mato Grosso" = "MT", "Mato Grosso do Sul" = "MS", "Minas Gerais" = "MG",
"Pará" = "PA", "Paraíba" = "PB", "Paraná" = "PR", "Pernambuco" = "PE",
"Piauí" = "PI", "Rio de Janeiro" = "RJ", "Rio Grande do Norte" = "RN",
"Rio Grande do Sul" = "RS", "Rondônia" = "RO", "Roraima" = "RR",
"Santa Catarina" = "SC", "São Paulo" = "SP", "Sergipe" = "SE",
"Tocantins" = "TO"
)

meses <- setNames(1:12, c(
"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho",
"Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
))
65 changes: 65 additions & 0 deletions R/dictionaries.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Data dictionaries
dicionario_sim <- data.frame(
Variavel = c("DTOBITO", "CAUSABAS", "IDADE", "SEXO", "RACACOR", "ESC", "LOCOCOR", "CODMUNRES", "CAUSABAS_O", "COMUNINF"),
Descricao = c(
"Data do óbito",
"Causa básica do óbito (CID-10)",
"Idade do falecido",
"Sexo do falecido",
"Raça/cor do falecido",
"Escolaridade",
"Local de ocorrência do óbito",
"Código do município de residência",
"Causa básica original",
"Código da unidade notificadora"
)
)

dicionario_sinasc <- data.frame(
Variavel = c("DTNASC", "SEXO", "PESO", "GESTACAO", "CONSULTAS", "RACACOR", "ESCMAE", "IDADEMAE", "CODMUNRES", "LOCNASC", "APGAR1"),
Descricao = c(
"Data de nascimento",
"Sexo do recém-nascido",
"Peso ao nascer (em gramas)",
"Duração da gestação em semanas",
"Número de consultas de pré-natal",
"Raça/cor do recém-nascido",
"Escolaridade da mãe",
"Idade da mãe",
"Código do município de residência",
"Local do nascimento",
"Índice de Apgar no 1º minuto"
)
)

dicionario_sih <- data.frame(
Variavel = c("DT_INTER", "PROC_REA", "DIAG_PRINC", "DIAS_PERM", "VAL_TOT", "CEP", "IDADE", "MUNIC_RES", "COMPLEX", "MORTE"),
Descricao = c(
"Data da internação",
"Procedimento realizado",
"Diagnóstico principal (CID-10)",
"Dias de permanência",
"Valor total da internação",
"CEP do paciente",
"Idade do paciente",
"Município de residência",
"Complexidade",
"Indicador de óbito"
)
)

dicionario_sia <- data.frame(
Variavel = c("PA_PROC", "PA_CIDPRI", "PA_SEXO", "PA_IDADE", "PA_RACACOR", "PA_QTDAPR", "PA_VALAPR", "PA_CODUNI", "PA_CBO", "PA_GESTAO"),
Descricao = c(
"Código do procedimento",
"CID principal",
"Sexo do paciente",
"Idade do paciente",
"Raça/cor do paciente",
"Quantidade aprovada",
"Valor aprovado",
"Código da unidade",
"Ocupação do profissional",
"Tipo de gestão"
)
)
196 changes: 196 additions & 0 deletions R/server_modules.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# Server Modules

# Helper function to fetch and process DATASUS data
fetch_datasus_data <- function(year_start, year_end, uf, information_system, month_start = NULL, month_end = NULL) {
# Get data
dados <- microdatasus::fetch_datasus(
year_start = year_start,
year_end = year_end,
month_start = month_start,
month_end = month_end,
uf = uf,
information_system = information_system
)

dados_processados <- dados

return(dados_processados)
}

downloadServer <- function(id) {
moduleServer(id, function(input, output, session) {
# Reactive value to store the downloaded data
data_preview <- reactiveVal(NULL)

# Loading screen
w <- Waiter$new(
id = "preview_table",
html = spin_dots(),
color = transparent(.5)
)

# Preview data action
observeEvent(input$preview, {
w$show()

# Initialize progress only when preview button is clicked
progress <- shiny::Progress$new()
progress$set(message = "Download em andamento", value = 0)

# Initialize progress
progress$set(message = "Baixando dados...", value = 0)

tryCatch({
# Basic parameter validation
validate(
need(input$ano_inicio <= input$ano_fim, "Ano inicial deve ser menor ou igual ao ano final"),
need(input$ano_inicio >= 1996 && input$ano_fim <= 2023, "Anos devem estar entre 1996 e 2023")
)

if(input$sistema %in% c("SIH-RD", "SIA-PA")) {
validate(
need(
!(input$ano_inicio == input$ano_fim && as.numeric(input$mes_inicio) > as.numeric(input$mes_fim)),
"Mês inicial deve ser menor ou igual ao mês final quando no mesmo ano"
)
)
}

# Update progress
progress$set(value = 0.3, message = "Conectando ao DATASUS...")

# Fetch data using microdatasus
if(input$sistema %in% c("SIH-RD", "SIA-PA")) {
dados <- fetch_datasus_data(
year_start = input$ano_inicio,
year_end = input$ano_fim,
month_start = as.numeric(input$mes_inicio),
month_end = as.numeric(input$mes_fim),
uf = input$estado,
information_system = input$sistema
)
} else {
dados <- fetch_datasus_data(
year_start = input$ano_inicio,
year_end = input$ano_fim,
uf = input$estado,
information_system = input$sistema
)
}

# Update progress
progress$set(value = 0.6, message = "Processando dados...")

# Process data according to the information system
dados_processados <- switch(input$sistema,
"SIM-DO" = microdatasus::process_sim(dados),
"SINASC" = microdatasus::process_sinasc(dados),
"SIH-RD" = microdatasus::process_sih(dados),
"SIA-PA" = microdatasus::process_sia(dados)
)

# Update progress
progress$set(value = 0.8, message = "Finalizando...")

# Store the processed data
data_preview(dados_processados)

# Update column selection choices
updateSelectInput(session, "selected_columns",
choices = names(dados_processados),
selected = names(dados_processados)[1:min(5, length(names(dados_processados)))])

# Complete progress
progress$set(value = 1, message = "Concluído!")

}, error = function(e) {
shinyjs::html("error_message", paste("Erro:", e$message))
data_preview(NULL)
progress$set(value = 1, message = "Erro no download!")
})

w$hide()

# Close progress
progress$close()
})

# Preview table output
output$data_loaded <- reactive({
!is.null(data_preview())
})
outputOptions(output, "data_loaded", suspendWhenHidden = FALSE)

output$preview_table <- renderDT({
req(data_preview())
data_to_show <- if (!is.null(input$selected_columns)) {
data_preview()[, input$selected_columns, drop = FALSE]
} else {
data_preview()
}

datatable(
head(data_to_show, 100),
options = list(
pageLength = 10,
scrollX = TRUE
)
)
})

# Download handler
output$download <- downloadHandler(
filename = function() {
ext <- if(input$formato == "xlsx") "xlsx" else "csv"
paste0(
"datasus_", tolower(input$sistema), "_",
input$estado, "_",
input$ano_inicio, "-", input$ano_fim,
".", ext
)
},
content = function(file) {
withProgress(message = 'Preparando arquivo para download...', value = 0, {
req(data_preview())

incProgress(0.3, detail = "Selecionando colunas...")
data_to_export <- if (!is.null(input$selected_columns)) {
data_preview()[, input$selected_columns, drop = FALSE]
} else {
data_preview()
}

incProgress(0.3, detail = "Gravando arquivo...")
if(input$formato == "xlsx") {
write.xlsx(data_to_export, file)
} else {
write.csv(data_to_export, file, row.names = FALSE)
}

incProgress(0.4, detail = "Finalizando...")
})
}
)
})
}

dictionaryServer <- function(id) {
moduleServer(id, function(input, output, session) {
output$dict_table <- renderDT({
dict_data <- switch(input$dict_sistema,
"SIM-DO" = dicionario_sim,
"SINASC" = dicionario_sinasc,
"SIH-RD" = dicionario_sih,
"SIA-PA" = dicionario_sia)

datatable(
dict_data,
options = list(
pageLength = 25,
dom = 't',
scrollY = TRUE
)
)
})
})
}
71 changes: 71 additions & 0 deletions R/ui_modules.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# UI Modules for each tab
downloadTabUI <- function(id) {
ns <- NS(id)

layout_sidebar(
sidebar = sidebar(
title = "Opções de Download",

selectInput(ns("sistema"), "Sistema de Informação:",
choices = info_systems),

selectInput(ns("estado"), "Estado:",
choices = estados),

numericInput(ns("ano_inicio"), "Ano Inicial:",
value = 2023, min = 1996, max = 2023),

numericInput(ns("ano_fim"), "Ano Final:",
value = 2023, min = 1996, max = 2023),

conditionalPanel(
condition = sprintf("input['%s'] == 'SIH-RD' || input['%s'] == 'SIA-PA'",
ns("sistema"), ns("sistema")),
selectInput(ns("mes_inicio"), "Mês Inicial:",
choices = meses,
selected = 1),
selectInput(ns("mes_fim"), "Mês Final:",
choices = meses,
selected = 12)
),

actionButton(ns("preview"), "Visualizar Dados", class = "btn-primary"),

conditionalPanel(
condition = sprintf("output['%s']", ns("data_loaded")),
hr(),
selectInput(ns("selected_columns"), "Selecionar Colunas:",
choices = NULL,
multiple = TRUE)
),

radioButtons(ns("formato"), "Formato do arquivo:",
choices = c("Excel (xlsx)" = "xlsx", "CSV" = "csv"),
selected = "xlsx"),

downloadButton(ns("download"), "Baixar Dados"),

div(id = ns("error_message"), style = "color: red;")
),

card(
card_header("Prévia dos Dados"),
DTOutput(ns("preview_table"))
)
)
}

dictionaryTabUI <- function(id) {
ns <- NS(id)

layout_sidebar(
sidebar = sidebar(
selectInput(ns("dict_sistema"), "Selecione o Sistema:",
choices = info_systems)
),
card(
card_header("Descrição das Variáveis"),
DTOutput(ns("dict_table"))
)
)
}
Loading

0 comments on commit eb36f69

Please sign in to comment.