library(shiny)
## Warning: package 'shiny' was built under R version 4.4.2
library(readxl)
## Warning: package 'readxl' was built under R version 4.4.2
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.2
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(DT)
## 
## Attaching package: 'DT'
## The following objects are masked from 'package:shiny':
## 
##     dataTableOutput, renderDataTable
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(rsconnect)
## Warning: package 'rsconnect' was built under R version 4.4.2
## 
## Attaching package: 'rsconnect'
## The following object is masked from 'package:shiny':
## 
##     serverInfo
# Load dataset
file_path <- "C:/Users/Losone Kaba/Desktop/ShinyApp_Work/data/Case Information 2022.xlsx1.xlsx"
equipment_data <- read_excel(file_path, sheet = "Equipment List Houston")
work_orders <- read_excel(file_path, sheet = "Work Orders")
notifications <- read_excel(file_path, sheet = "Notifications")

# Convert date columns to Date format for calculations
notifications <- notifications %>%
    mutate(Malfunction_start = as.Date(`Malfunction start`),
           Malfunction_end = as.Date(`Malfunction end`)) %>%
    arrange(Malfunction_start)

# UI for the Shiny app
ui <- fluidPage(
    titlePanel("Johan Company Maintenance Dashboard"),
    
    sidebarLayout(
        sidebarPanel(
            selectInput("priority", "Filter by Work Order Priority:", 
                        choices = unique(work_orders$Priority), 
                        selected = unique(work_orders$Priority)[1]),
            selectInput("equipment_type", "Filter by Equipment Type:", 
                        choices = unique(equipment_data$`Technical identification no.`), 
                        selected = unique(equipment_data$`Technical identification no.`)[1])
        ),
        
        mainPanel(
            tabsetPanel(
                tabPanel("Equipment List", DTOutput("equipment_table")),
                tabPanel("Work Orders", DTOutput("work_orders_table")),
                tabPanel("Notifications", DTOutput("notifications_table")),
                tabPanel("Work Order Priority Analysis", plotOutput("priority_plot")),
                tabPanel("KPI Dashboard", 
                         h3("Reliability KPIs"),
                         verbatimTextOutput("mtbf_value"),
                         verbatimTextOutput("mttr_value"),
                         plotOutput("mtbf_trend"),
                         plotOutput("failure_causes"))
            )
        )
    )
)

# Server logic
server <- function(input, output) {
    
    # Equipment Table
    output$equipment_table <- renderDT({
        datatable(equipment_data)
    })
    
    # Work Orders Table (Filtered by Priority)
    output$work_orders_table <- renderDT({
        work_orders %>% filter(Priority == input$priority) %>% datatable()
    })
    
    # Notifications Table
    output$notifications_table <- renderDT({
        datatable(notifications)
    })
    
  # Work Order Priority Plot
    output$priority_plot <- renderPlot({
        ggplot(work_orders, aes(x = factor(Priority))) +
            geom_bar(fill = "blue") +
            labs(title = "Work Order Priority Distribution", x = "Priority", y = "Count") +
            theme_minimal()
    })
    
    # Calculate Mean Time Between Failures (MTBF)
    output$mtbf_value <- renderText({
        mtbf <- notifications %>%
            mutate(Time_Between_Failures = difftime(Malfunction_start, lag(Malfunction_end), units = "days")) %>%
            summarise(Avg_MTBF = mean(Time_Between_Failures, na.rm = TRUE)) %>%
            pull(Avg_MTBF)
        
        paste("Mean Time Between Failures (MTBF):", round(mtbf, 2), "days")
    })

    # Calculate Mean Time to Repair (MTTR)
    output$mttr_value <- renderText({
        mttr <- notifications %>%
            mutate(Repair_Time = difftime(Malfunction_end, Malfunction_start, units = "hours")) %>%
            summarise(Avg_MTTR = mean(Repair_Time, na.rm = TRUE)) %>%
            pull(Avg_MTTR)
        
        paste("Mean Time to Repair (MTTR):", round(mttr, 2), "hours")
    })

    # Trend Analysis: MTBF Over Time
    output$mtbf_trend <- renderPlot({
        notifications %>%
            mutate(Year = year(Malfunction_start)) %>%
            group_by(Year) %>%
            summarise(Avg_MTBF = mean(difftime(Malfunction_start, lag(Malfunction_end), units = "days"), na.rm = TRUE)) %>%
            ggplot(aes(x = Year, y = Avg_MTBF)) +
            geom_line(color = "blue", size = 1) +
            geom_point(color = "red", size = 3) +
            labs(title = "MTBF Trend Over Time", x = "Year", y = "MTBF (days)") +
            theme_minimal()
    })

    # Failure Cause Visualization
    output$failure_causes <- renderPlot({
        notifications %>%
            count(`Code Group`) %>%
            ggplot(aes(x = reorder(`Code Group`, -n), y = n, fill = `Code Group`)) +
            geom_bar(stat = "identity") +
            labs(title = "Top Failure Causes", x = "Failure Cause", y = "Count") +
            coord_flip() +
            theme_minimal()
    })
}


# Run the app
shinyApp(ui, server)
Shiny applications not supported in static R Markdown documents