Action

Type

Resolved On

Date Range Query Utilities refactoring - - -

Date Range Query Utilities

Overview

The date range calculation pattern for Supabase queries appears 20+ times across monthly.ts, yearly.ts, and weekly.ts. This duplication creates maintenance overhead and increases the risk of inconsistencies.

Problem

The same date range string concatenation pattern is repeated throughout the codebase:

// Pattern appears in monthly.ts, yearly.ts, weekly.ts
.gte("generated_on", year + "-" + month + "-1")
.lt("generated_on", year + (month == 12 ? 1 : 0) + "-" + ((month % 12) + 1) + "-1")

Affected Files

  • src/lib/monthly.ts - ideas(), goal(), backlog(), completedTasks(), todoTasks(), focus(), actions()
  • src/lib/yearly.ts - ideas(), currentMonthIdeas(), previousMonthsIdeas(), backlog()
  • src/lib/weekly.ts - goals()

Solution

Create a dedicated src/lib/date-range.ts utility module with functions to generate date ranges.

Proposed API

// Get start and end dates for a month range
export function getMonthRange(year: number, month: number): {
  start: string;  // "yyyy-MM-dd"
  end: string;    // "yyyy-MM-dd" (first day of next month)
}

// Get start and end dates for a year range
export function getYearRange(year: number): {
  start: string;  // "yyyy-01-01"
  end: string;    // "yyyy-12-31"
}

// Get start and end for previous months within a year
export function getPreviousMonthsRange(year: number, month: number): {
  start: string;  // "yyyy-01-01"
  end: string;    // "yyyy-MM-01" (first day of current month)
}

Usage Example

// Before
const result = await supabase
  .from("Ideas")
  .select("*")
  .gte("generated_on", year + "-" + month + "-1")
  .lt("generated_on", year + (month == 12 ? 1 : 0) + "-" + ((month % 12) + 1) + "-1")

// After
const { start, end } = getMonthRange(year, month);
const result = await supabase
  .from("Ideas")
  .select("*")
  .gte("generated_on", start)
  .lt("generated_on", end)

Benefits

  • Single Source of Truth: Date logic centralized in one location
  • Testability: Date calculations can be unit tested in isolation
  • Readability: Query code becomes cleaner and self-documenting
  • Maintainability: Changes to date format only require updates in one place
  • Consistency: Ensures all queries use the same date format logic

Implementation Notes

  • Consider using date-fns functions already available in the project
  • The utility should handle edge cases like December → January year rollover
  • Could potentially leverage existing src/lib/date.ts functions
  • src/lib/monthly.ts
  • src/lib/yearly.ts
  • src/lib/weekly.ts
  • src/lib/date.ts (potential integration point)