---
title: "Automated Supabase Data Report"
author: "Your Name" # Daniel
date: "`r format(Sys.Date(), '%B %d, %Y')`" # today's date
output: pdf_document
---
`{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
library(DBI)
library(RPostgres)
library(dplyr)
library(ggplot2)
library(httr)       # For API requests
library(jsonlite)   # For JSON parsing
library(lubridate)  # For date handling
## Fetch secrets
supabase_url <- Sys.getenv("SUPABASE_URL")
supabase_key <- Sys.getenv("SUPABASE_KEY")
`
## Automated Database Report
This report is automatically generated from our Supabase PostgreSQL database.
`{r fetch-data}
# Function to fetch data from Supabase using REST API
fetch_supabase_data <- function(url, api_key, table_name, query_params = NULL) {
  # Build the API endpoint
  endpoint <- paste0(url, "/rest/v1/", table_name)
  # Prepare headers
  headers <- c(
    "apikey" = api_key,
    "Authorization" = paste("Bearer", api_key),
    "Content-Type" = "application/json",
    "Prefer" = "return=representation"
  )
  # Build query parameters
  if (is.null(query_params)) {
    # Default: get data from last 7 days
    query_params <- list(
      # Using Supabase's PostgREST syntax
      `created_at` = paste0("gte.", format(Sys.Date() - 7, "%Y-%m-%d"))
    )
  }
  tryCatch({
    # Make the GET request
    response <- GET(
      url = endpoint,
      add_headers(.headers = headers),
      query = query_params
    )
    # Check for successful response
    if (http_status(response)$category == "Success") {
      # Parse the JSON response
      data <- fromJSON(content(response, "text", encoding = "UTF-8"), flatten = TRUE)
      # Log success
      write("SUCCESS", "query_status.txt")
      # Convert to data frame if it isn't already
      if (!is.data.frame(data)) {
        if (length(data) == 0) {
          # Return empty data frame with expected columns
          data <- data.frame(
            id = integer(0),
            value = numeric(0),
            created_at = character(0),
            description = character(0)
          )
        } else {
          data <- as.data.frame(data)
        }
      }
      return(data)
    } else {
      # Log error
      error_msg <- paste("API Error:", http_status(response)$message, 
                        "-", content(response, "text", encoding = "UTF-8"))
      write(error_msg, "error_log.txt")
      write("FAILED", "query_status.txt")
      stop(error_msg)
    }
  }, error = function(e) {
    # Log connection errors
    write(paste("ERROR:", e$message), "error_log.txt")
    write("FAILED", "query_status.txt")
    stop(paste("Supabase API request failed:", e$message))
  })
}
# Fetch data from Supabase - replace "your_table_name" with your actual table
data <- fetch_supabase_data(
  url = supabase_url,
  api_key = supabase_key,
  table_name = "your_table_name"
)
`
`{r analyze, eval=file.exists("query_status.txt") && readLines("query_status.txt")[1] == "SUCCESS"}
# Data analysis code runs only if query was successful
# Check if we have data
if(nrow(data) == 0) {
  cat("No data available for the selected period.")
} else {
  # Convert date strings to proper date objects if needed
  if("created_at" %in% colnames(data) && !inherits(data$created_at, "Date")) {
    data$created_at <- as_datetime(data$created_at)
  }
  # Summary statistics
  summary_stats <- data %>%
    summarize(
      count = n(),
      avg_value = mean(value, na.rm = TRUE),
      max_value = max(value, na.rm = TRUE),
      min_value = min(value, na.rm = TRUE)
    )
  knitr::kable(summary_stats, caption = "Summary Statistics")
  # Create a visualization
  ggplot(data, aes(x = created_at, y = value)) +
    geom_line() +
    geom_point() +
    theme_minimal() +
    labs(title = "Weekly Trend", x = "Date", y = "Value")
}
`
## Conclusion
Report generated automatically at `r Sys.time()`.