Column

97

24

48

16

6

1

Row

Row

Row

Row

---
title: "Painel de Sífilis Gestacional e Congênita"
output: 
  flexdashboard::flex_dashboard:
    fig_height: 6
    fig_width: 10
    orientation: rows
    vertical_layout: fill
    theme: cosmo
    social: menu
    source_code: embed

---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
library(plotly)
library(lubridate)
library(readr)
library(janitor)
library(rio)
library(htmltools)
library(htmltools)
library(dplyr)
library(DT)

# Leitura da planilha

setwd("//srv-fs/NVEPI_Norte/NVEPI - DIRAPS/2 VIGILÂNCIA EPIDEMIOLÓGICA/AGRAVO - SÍFILIS/SG") 

dados <- import("planilha_tratamento_sifilis_avancada.xlsx",
                sheet = "desfecho_gestacao")
summary(dados)

## Corrigir data de nascimento

# Converter para número
dados$DN...4 <- as.numeric(dados$DN...4)

# Converter para data com origem do Excel
dados$DN...4 <- as.Date(dados$DN...4, origin = "1899-12-30")

# Calcular idade
dados <- dados %>%
  mutate(
    idade = as.integer(floor((Sys.Date() - DN...4) / 365.25))  
  )
# Faixa etária
dados <- dados %>% mutate(
  faixa_etaria = case_when(
    is.na(idade) ~ "Idade desconhecida",
    idade < 10 ~ "<10 anos",
    idade >= 10 & idade <= 14 ~ "10-14 anos",
    idade >= 15 & idade <= 19 ~ "15-19 anos",
    idade >= 20 & idade <= 24 ~ "20-24 anos",
    idade >= 25 & idade <= 29 ~ "25-29 anos",
    idade >= 30 & idade <= 34 ~ "30-34 anos",
    idade >= 35 & idade <= 39 ~ "35-39 anos",
    idade >= 40 ~ "40+ anos"
  )
)

# Corrigir NA em desfecho_rn
dados <- dados %>% mutate(DESFECHO_RN = ifelse(is.na(DESFECHO_RN), "Sem informação", DESFECHO_RN))

# Selecionar até a coluna desejada
dados <- dados[9:105, ]

# Indicadores
total_gestantes <- nrow(dados)
criancas_expostas <- sum(dados$DESFECHO_RN== "Criança exposta a sífilis", na.rm = TRUE)
sifilis_congenita <- sum(dados$DESFECHO_RN == "Sífilis congênita", na.rm = TRUE)
sem_informacao <- sum(dados$DESFECHO_RN == "Sem informação", na.rm = TRUE)
natimorto <- sum(dados$DESFECHO_RN == "Natimorto" , na.rm = TRUE)
aborto <- sum(dados$DESFECHO_RN == "Aborto" , na.rm = TRUE)

### Preparacao dados tratamento 30 dias antes 
df_tratamento30 <- dados %>%
  mutate(TRATAMENTO_30_ANTES = ifelse(is.na(TRATAMENTO_30_ANTES) , "Sem informação", TRATAMENTO_30_ANTES)) %>%
  count(TRATAMENTO_30_ANTES)

# Categorizar os valores STATUS VDRL
df_vdrl <- dados %>%
  filter(!is.na(STATUS_VDRL)) %>%
  mutate(
    status_vdrl_categoria = case_when(
      grepl("Finalizado", STATUS_VDRL, ignore.case = TRUE) ~ "Finalizado",
      suppressWarnings(as.numeric(STATUS_VDRL) < 0) ~ "Atrasado",
      suppressWarnings(as.numeric(STATUS_VDRL) > 0) ~ "Aguardando próximo",
      TRUE ~ "Outro"
    )
  ) %>%
  count(status_vdrl_categoria)


```

Column {data-width=150}
-----------------------------------------------------------------------
###

```{r}
### Gestante com sífilis 
valueBox(
  value = total_gestantes,
  caption = "Sífilis Gestacional",
  icon = "fa-female",
  color = "purple"
)
```
###
```{r}
### Criança exposta
valueBox(
  value = criancas_expostas,
  caption = "Crianças Expostas",
  icon = "fa-baby",
  color = "orange"
)
```
###
```{r}
### Sem informação 
valueBox(
  value = sem_informacao,
  caption = "Sem Informação dos desfecho da gestação",
  icon = "fa-question",
  color = "gray"
)
```
###
```{r}
### Sífilis congênita 
valueBox(
  value = sifilis_congenita,
  caption = "Sífilis Congênita",
  icon = "fa-exclamation-triangle",
  color = "danger"
)
```
###
```{r}
### Aborto
valueBox(
  value = aborto,
  caption = "Aborto",
  icon = "fa-exclamation-triangle",
  color = "aqua"
)
```
###
```{r}
### Natimorto
valueBox(
  value = natimorto,
  caption = "Natimorto",
  icon = "fa-exclamation-triangle",
  color = "green"
)
```

Row {data-height=400}
-----------------------------------------------------------------------
```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE, fig.width=12, out.width='100%'}
library(plotly)
library(DT)

# Cor de fundo do painel
cor_fundo <- "#F8F9FA"

# 1. Gráfico  Equipes com mais casos
top_equipes <- dados %>%
  filter(!is.na(EQUIPE) & EQUIPE != "") %>%
  count(EQUIPE, name = "Casos") %>%
  slice_max(Casos, n = 8) %>%
  arrange(desc(Casos))

grafico_equipe <- plot_ly(
  data = top_equipes,
  y = ~reorder(EQUIPE, Casos),
  x = ~Casos,
  type = 'bar',
  orientation = 'h',
  text = ~Casos,
  textposition = 'auto',
  marker = list(color = '#40004B'),
  hoverinfo = 'text',
  hovertext = ~paste("<b>", EQUIPE, "</b><br>", Casos, "casos")
) %>%
layout(
  title = list(text = "<b> Equipes com mais casos de sífilis gestacional </b>", font = list(size = 14)),
  xaxis = list(title = "Nº de Casos"),
  yaxis = list(title = ""),
  margin = list(l = 150, r = 20, t = 50, b = 60),
  plot_bgcolor = cor_fundo,
  paper_bgcolor = cor_fundo,
  height = 350
)

# 2. Gráfico de Faixa Etária 
grafico_faixa <- dados %>%
  count(faixa_etaria) %>%
  plot_ly(
    y = ~reorder(faixa_etaria, n),
    x = ~n,
    type = 'bar',
    orientation = 'h',
    text = ~n,
    textposition = 'auto',
    marker = list(color = '#9970AB'),
    hoverinfo = 'text',
    hovertext = ~paste("<b>", faixa_etaria, "</b><br>", n, "casos")
  ) %>%
  layout(
    title = list(text = "<b>Distribuição por Faixa Etária</b>", font = list(size = 14)),
    xaxis = list(title = "Nº de Casos"),
    yaxis = list(title = ""),
    margin = list(l = 150, r = 20, t = 50, b = 60),
    plot_bgcolor = cor_fundo,
    paper_bgcolor = cor_fundo,
    height = 350
  )

# 3. Gráfico de Tratamento 
grafico_tratamento <- dados %>%
  count(TRATAMENTO_GESTA) %>%
  plot_ly(
    y = ~reorder(TRATAMENTO_GESTA, n),
    x = ~n,
    type = 'bar',
    orientation = 'h',
    text = ~n,
    textposition = 'auto',
    marker = list(color = '#762A83'),
    hoverinfo = 'text',
    hovertext = ~paste("<b>", TRATAMENTO_GESTA, "</b><br>", n, "casos")
  ) %>%
  layout(
    title = list(text = "<b>Tratamento das Gestantes</b>", font = list(size = 14)),
    xaxis = list(title = "Nº de Casos"),
    yaxis = list(title = ""),
    margin = list(l = 150, r = 20, t = 50, b = 60),
    plot_bgcolor = cor_fundo,
    paper_bgcolor = cor_fundo,
    height = 350
  )

# Layout final com os 3 gráficos lado a lado ocupando toda a largura
div(
  style = paste0("display: flex; justify-content: space-between; background-color:", cor_fundo, "; padding: 15px; width: 100%;"),
  
  # Gráfico Top 8 Equipes
  div(
    style = "width: 32%; background: white; border-radius: 8px; padding: 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);",
    grafico_equipe
  ),
  
  # Gráfico Faixa Etária
  div(
    style = "width: 32%; background: white; border-radius: 8px; padding: 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);",
    grafico_faixa
  ),
  
  # Gráfico Tratamento
  div(
    style = "width: 32%; background: white; border-radius: 8px; padding: 15px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);",
    grafico_tratamento
  )
)
```
Row {data-height=150}
-----------------------------------------------------------------------
```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE}
library(readxl)
library(DT)

# Tabela de vulnerabilidade
tabela_vulnerabilidade <- dados %>%
  mutate(
    CLASSIFICACAO_IVT = case_when(
      CLASSIFICACAO_IVT %in% c("ALTA VULNERABILIDADE", "BAIXA VULNERABILIDADE", "MÉDIA VULNERABILIDADE", "EM ACOMPANHAMENTO") ~ CLASSIFICACAO_IVT,
      TRUE ~ "SEM INFORMAÇÃO"
    )
  ) %>%
  group_by(`Classificação IVT` = CLASSIFICACAO_IVT) %>%
  summarise(
    `Total de casos` = n(),
    `Tratamento adequado` = sum(TRATAMENTO_GESTA == "Tratamento Adequado", na.rm = TRUE),
    `Tratamento inadequado` = sum(TRATAMENTO_GESTA == "Tratamento Inadequado", na.rm = TRUE),
    `Abandono de tratamento` = sum(TRATAMENTO_GESTA == "Abandono de tratamento", na.rm = TRUE),
    .groups = "drop"
  )
  

datatable(
  tabela_vulnerabilidade,
  caption = htmltools::tags$caption(
    style = 'caption-side: top; text-align: center; font-size: 16px; font-weight: bold;',
    "Tabela de Vulnerabilidade - Sífilis Gestacional"
  ),
  filter = 'top',
  options = list(
    pageLength = 5,
    scrollX = TRUE,
    scrollY = "300px",
    dom = 't',
    language = list(
      search = "Pesquisar:",
      paginate = list(previous = 'Anterior', `next` = 'Próximo')
    )
  ),
  class = 'stripe hover cell-border order-column',
  rownames = FALSE
) %>%
  formatStyle(
    names(tabela_vulnerabilidade),
    fontWeight = 'normal',
    textAlign = 'center'
  )
```


Row {data-height=350}
-----------------------------------------------------------------------
```{r, echo=FALSE, results='asis', warning=FALSE, message=FALSE, fig.width=12, out.width='100%'}
library(plotly)
library(dplyr)
library(htmltools)

# 1. Estilo unificado para todos os gráficos
estilo_unificado <- list(
  textinfo = 'label+percent',
  insidetextorientation = 'radial',
  marker = list(line = list(color = '#FFFFFF', width = 1.5)),
  hoverinfo = 'label+percent+name',
  textfont = list(size = 12, color = '#FFFFFF'),
  hoverlabel = list(bgcolor = '#40004B', font = list(color = '#FFFFFF'))
)

# 2. Paleta de cores consistente
paleta_cores <- c(
  '#40004B',  # Roxo escuro (principal)
  '#8E24AA',  # Roxo médio
  '#9970AB',  # Roxo claro
  '#E1BEE7',  # Lavanda
  '#F3E5F5'   # Lavanda claro
)

# 3.Gráficos padronizados
criar_grafico_pizza <- function(dados, titulo) {
  plot_ly(
    dados,
    labels = ~get(names(dados)[1]),
    values = ~n,
    type = 'pie',
    marker = list(
      colors = paleta_cores[1:nrow(dados)],
      line = estilo_unificado$marker$line
    ),
    textposition = 'inside',
    textinfo = estilo_unificado$textinfo,
    insidetextorientation = estilo_unificado$insidetextorientation,
    hoverinfo = estilo_unificado$hoverinfo,
    width = '100%'  # Garante que o gráfico use toda a largura disponível
  ) %>% 
  layout(
    title = list(
      text = paste0('<b>', titulo, '</b>'),
      font = list(size = 14, color = '#40004B'),
      x = 0.5, y = 0.95
    ),
    showlegend = FALSE,
    margin = list(l = 20, r = 20, b = 40, t = 60),
    paper_bgcolor = 'rgba(0,0,0,0)',
    plot_bgcolor = 'rgba(0,0,0,0)',
    autosize = TRUE  # Ajuste automático de tamanho
  )
}

# 4. Preparação dos dados 
if(!exists("df_vdrl_corrigido")) {
  df_vdrl_corrigido <- dados %>%
    mutate(
      status_vdrl_categoria = case_when(
        grepl("Finalizado", STATUS_VDRL, ignore.case = TRUE) ~ "Finalizado",
        suppressWarnings(as.numeric(STATUS_VDRL) < 0) ~ "Atrasado",
        suppressWarnings(as.numeric(STATUS_VDRL) > 0) ~ "Aguardando próximo",
        TRUE ~ "Sem informação"
      )
    ) %>%
    count(status_vdrl_categoria)
}

if(!exists("df_tratamento30")) {
  df_tratamento30 <- dados %>%
    mutate(TRATAMENTO_30_ANTES = ifelse(is.na(TRATAMENTO_30_ANTES), "Sem informação", TRATAMENTO_30_ANTES)) %>%
    count(TRATAMENTO_30_ANTES)
}

# 5. Criar os gráficos
g1 <- criar_grafico_pizza(
  dados %>% count(TRATAMENTO_DIAGNOSTICO),
  "Tratamento no diagnóstico"
)

g2 <- criar_grafico_pizza(
  df_tratamento30,
  "Tratamento 30 dias antes"
)

g3 <- criar_grafico_pizza(
  df_vdrl_corrigido,
  "Status VDRL"
)

g4 <- criar_grafico_pizza(
  dados %>% count(TRATAMENTO_PARCEIRO),
  "Tratamento do parceiro"
)

# 6. Layout dos gráficos
div(
  class = "row",
  style = "margin: 0; width: 100%;",
  
  div(
    class = "col-md-6 col-lg-3",
    style = "padding: 5px; height: 350px;",
    g1
  ),
  div(
    class = "col-md-6 col-lg-3",
    style = "padding: 5px; height: 350px;",
    g2
  ),
  div(
    class = "col-md-6 col-lg-3",
    style = "padding: 5px; height: 350px;",
    g3
  ),
  div(
    class = "col-md-6 col-lg-3",
    style = "padding: 5px; height: 350px;",
    g4
  )
)
```

Row {data-height=400}
-----------------------------------------------------------------------
```{r, fig.width=12, out.width='100%'}
# Tabela de casos por GSAP 
tabela_gsap <- dados %>%
  mutate(
    GSAP = ifelse(is.na(GSAP) | GSAP == "", "SEM INFORMAÇÃO", GSAP)
  ) %>%
  group_by(GSAP) %>%
  summarise(
    `Total de Casos` = n(),
    `Sífilis Congênita` = sum(DESFECHO_RN == "Sífilis congênita", na.rm = TRUE),
    `Criança Exposta` = sum(DESFECHO_RN == "Criança exposta a sífilis", na.rm = TRUE),
    `Parceiro Tratado` = sum(TRATAMENTO_PARCEIRO == "Sim", na.rm = TRUE),
    .groups = "drop"
  ) %>%
  arrange(desc(`Total de Casos`))

# Tabela DT com filtro específico para GSAP
tabela_dt_gsap <- datatable(
  tabela_gsap,
  extensions = c('Responsive', 'Buttons'),
  options = list(
    pageLength = 10,
    scrollY = "400px",
    dom = 'Blfrtip',
    buttons = list('copy', 'print', list(
      extend = 'collection',
      buttons = c('csv', 'excel', 'pdf'),
      text = 'Exportar'
    )),
    initComplete = JS(
      "function(settings, json) {",
      "  $('div.dt-search').html('<label style=\"color:#40004B;\">Pesquisar GSAP:<input type=\"text\" id=\"gsapSearch\" placeholder=\"Digite o GSAP\" /></label>');",
      "  $('#gsapSearch').keyup(function() {",
      "    settings.oInstance.api().column(0).search(this.value).draw();",
      "  });",
      "}"
    ),
    columnDefs = list(
      list(width = '200px', targets = 0),
      list(className = 'dt-center', targets = 1:3)
    )
  ),
  class = 'cell-border stripe hover',
  rownames = FALSE,
  caption = htmltools::tags$caption(
    style = 'caption-side: top; text-align: center; color: #40004B; font-size: 16px; font-weight: bold;',
    'Tabela: Casos de sífilis gestacional por GSAP')
) %>%
  formatStyle(columns = names(tabela_gsap), fontSize = '14px')

tabela_dt_gsap
```