Column

M.Utilidad Total

$ 671.11 mill.

M. Margen Global

19.95 %

M.Utilidad Top‑10 Países

Column

M.Utilidad por Año, Trimestre y Continente

M.Utilidad por País y Continente

Column

M.Utilidad por Continente

M.Utilidad por Categoría Producto

M.Utilidad por Tipo Producto

---
title: "Dashboard Appol"
author: "Jorge Gandara & María Escorcia"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    source_code: embed
---

```{r setup, include=FALSE}

#Librerías
library(flexdashboard)
library(readxl)
library(dplyr)
library(stringr)
library(tidyr)
library(ggplot2)
library(plotly)
library(highcharter)
library(DT)
library(janitor)
library(sf)
library(rnaturalearth)
library(scales)

#Ruta al archivo
archivo <- "Appol Datos.xlsx"

# ----- Transformación de datos -----
datos <- read_excel(archivo, sheet = "Tabla Datos") %>%
  select(Periodo, `Tipo Producto`, Region, Ingresos, Gastos) %>%
  mutate(
    codigo_pais = str_sub(Region, 1, 3),
    continente  = str_extract(Region, '(?<= - ).+?(?=/)'),
    pais        = str_extract(Region, '(?<=/).*'),
    trimestre   = str_replace(str_extract(Periodo, 'Q[1-4]'), 'Q', 'T'),
    anio        = as.integer(str_extract(Periodo, '\\d{4}')),
    utilidad    = Ingresos - Gastos,
    m_utilidad  = ifelse(is.finite(utilidad / Ingresos),
                         utilidad / Ingresos, NA_real_)
  )
tabla_productos <- read_excel(archivo, sheet = "Tabla Productos") %>%
  clean_names()

datos <- datos %>%
  left_join(tabla_productos, by = c('Tipo Producto' = 'tipo_producto')) %>%
  clean_names()
```

Column {data-width=250}
-----------------------------------------------------------------------

### **M.Utilidad Total**

```{r}
valueBox(
  sprintf("$ %.2f mill.", sum(datos$utilidad)/1e6),
  caption = "M.Utilidad",
  color = "#EEE8CD", 
  icon = "fa-apple"
)
```


### **M. Margen Global**

```{r}

margen_pct <- sum(datos$utilidad) / sum(datos$ingresos) * 100
valueBox(
  sprintf("%.2f %%", margen_pct),
  caption = "M.Margen",
  color = "#FFF8DC", 
  icon = "fa-apple"
)
```

### M.Utilidad Top‑10 Países

```{r}
top_paises <- datos %>% 
  group_by(pais) %>% 
  summarise(
    m_utilidad = sum(utilidad),
    m_margen   = sum(utilidad) / sum(ingresos)
  ) %>% 
  arrange(desc(m_utilidad)) %>% 
  slice_head(n = 10)

# Guardamos el rango numérico antes de formatear
rango_margen <- range(top_paises$m_margen, na.rm = TRUE)

# Ahora formateamos para la visualización
top_paises <- top_paises %>%
  mutate(
    m_utilidad = dollar(m_utilidad),
    m_margen   = percent(m_margen, accuracy = 0.1)
  )

datatable(
  top_paises,
  rownames = FALSE,
  options  = list(dom = 'tp', pageLength = 10),
  colnames = c("País", "M.Utilidad", "M.Margen")
) %>%
  formatCurrency('m_utilidad', currency = "$", digits = 0) %>% 
  formatPercentage('m_margen', digits = 1) %>%
  formatStyle(
    'm_margen',
    background = styleColorBar(rango_margen, '#FFE4E1'),
    backgroundSize = '100% 80%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  )

```

Column {data-width=450}
-----------------------------------------------------------------------


### M.Utilidad por Año, Trimestre y Continente

```{r}
serie <- datos %>% 
  mutate(periodo = paste(trimestre, anio)) %>% 
  group_by(periodo, continente) %>% 
  summarise(m_utilidad = sum(utilidad), .groups = 'drop') # <- solo sumar utilidad
serie$periodo <- factor(serie$periodo, levels = unique(serie$periodo))

# Graficamos
ggplotly(
  ggplot(serie, aes(x = periodo, y = m_utilidad, color = continente, group = continente)) +
    geom_line(size = 1) + 
    geom_point() +
    scale_y_continuous(labels = dollar_format(prefix = "$ ", suffix = " mill.", scale = 1e-6)) + # <- Formato de dinero en millones
    scale_color_manual(values = c("América" = "#9F79EE", 
                                  "Asia" = "#FFE4E1", 
                                  "Europa" = "#63B8FF",
                                  "África" = "#4876FF", 
                                  "Oceanía" = "#FF3E96")) +
    labs(x = "Trimestre", y = "Suma de Utilidad Total", 
         title = "M. Utilidad Total por Año, Trimestre y Continente") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45, hjust = 1),
          legend.title = element_blank())
)
```

### M.Utilidad por País y Continente

```{r}
# Coordenadas de referencia
world <- ne_countries(returnclass = "sf") %>% 
  st_make_valid() %>% 
  select(iso_a3, geometry)

coords <- st_point_on_surface(world) %>% 
  mutate(longitude = st_coordinates(geometry)[,1],
         latitude  = st_coordinates(geometry)[,2]) %>% 
  st_drop_geometry()

map_data <- datos %>% 
  group_by(codigo_pais, pais, continente) %>% 
  summarise(utilidad = sum(utilidad), .groups = 'drop') %>% 
  left_join(coords, by = c("codigo_pais" = "iso_a3")) %>% 
  filter(!is.na(longitude))

# Definir paleta de colores por continente
paleta <- c(
  "América" = "#9F79EE",  # Púrpura para América
  "Asia" = "#FFE4E1",     # Rosa claro para Asia
  "Europa" = "#63B8FF",   # Azul claro para Europa
  "África" = "#4876FF",   # Azul para África
  "Oceanía" = "#FF3E96"   # Rosa para Oceanía
)

# Crear el mapa
hcmap("custom/world", 
      showInLegend = FALSE,
      nullColor = "#E0E0E0") %>% 
  hc_title(text = "Suma de Utilidad Total por País y Continente") %>%
  hc_legend(enabled = TRUE, layout = "horizontal", 
            align = "center", verticalAlign = "top",
            itemStyle = list(fontSize = "12px")) %>% 
  { 
    m <- .
    for(cont in names(paleta)) {
      df <- map_data %>% filter(continente == cont)
      if(nrow(df) > 0) {
        m <- m %>% hc_add_series(
          df,
          type = "mapbubble",
          name = cont,
          color = paleta[[cont]],
          hcaes(lat = latitude, lon = longitude, size = utilidad),
          maxSize = "10%",
          showInLegend = TRUE,
          marker = list(
            fillOpacity = 0.7,
            lineWidth = 1,
            lineColor = "white"
          )
        )
      }
    }
    m
  } %>% 
  hc_colorAxis(enabled = FALSE) %>%
  hc_mapNavigation(enabled = TRUE, buttonOptions = list(verticalAlign = "bottom")) %>%
  hc_tooltip(
    headerFormat = "",
    pointFormat = "<b>{point.pais}</b><br>Utilidad: ${point.utilidad:,.0f}"
  ) %>%
  hc_credits(
    enabled = TRUE,
    text = "© 2023 TechSoft, © 2023 Microsoft Corporation, Datos Appol",
    style = list(fontSize = "10px")
  ) %>%
  hc_chart(backgroundColor = "#FFFFFF")
```

Column {data-width=300}
-----------------------------------------------------------------------

### M.Utilidad por Continente

```{r}
cont <- datos %>% 
  group_by(continente) %>% 
  summarise(utilidad = sum(utilidad), .groups = 'drop')

# Vector de colores por continente
colores_continentes <- c("América" = "#9F79EE", 
                         "Asia" = "#FFE4E1", 
                         "Europa" = "#63B8FF",
                         "África" = "#4876FF", 
                         "Oceanía" = "#FF3E96")

# Extraer los colores en el orden que aparecen los continentes en tus datos
colores_ordenados <- colores_continentes[cont$continente]

plot_ly(
  cont, labels = ~continente, values = ~utilidad,
  type = 'pie', hole = 0.45,
  textinfo = 'label+percent',
  marker = list(colors = colores_ordenados)
) %>% layout(showlegend = TRUE)
```

### M.Utilidad por Categoría Producto

```{r}
cat_prod <- datos %>% 
  group_by(categoria_producto) %>% 
  summarise(utilidad = sum(utilidad), .groups = 'drop') %>% 
  arrange(desc(utilidad))

highchart() %>% 
  hc_add_series(cat_prod, "column", hcaes(x = categoria_producto, y = utilidad),
                colorByPoint = TRUE) %>% 
  hc_colors(c("#FF69B4", "#9370DB")) %>%  # Colores rosa y morado
  hc_yAxis(title = list(text = "Utilidad"),
           labels = list(formatter = JS("function() {return '$' + Highcharts.numberFormat(this.value, 0, '.', ',');}"))) %>% 
  hc_xAxis(title = list(text = NULL)) %>%
  hc_title(text = "Suma de Utilidad Total por Categoría Producto") %>%
  hc_tooltip(pointFormat = "${point.y:,.0f}") %>%
  hc_legend(enabled = FALSE)
```

### M.Utilidad por Tipo Producto

```{r}
tipo_prod <- datos %>% 
  group_by(tipo_producto) %>% 
  summarise(utilidad = sum(utilidad), .groups = 'drop')

hchart(tipo_prod,
       "treemap",
       hcaes(name = tipo_producto, value = utilidad)) %>% 
  hc_colorAxis(stops = color_stops(n = 10, colors = c("#FF69B4", "#9370DB"))) %>%
  hc_title(text = "Utilidad por Tipo Producto") %>%
  hc_tooltip(pointFormatter = JS("function() {
    return '<b>' + this.name + '</b>: $' + Highcharts.numberFormat(this.value, 0) + '<br/>';
  }"))
```