All files / server comparison-query-builder.ts

76.74% Statements 66/86
68.08% Branches 32/47
100% Functions 17/17
75.9% Lines 63/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333                                                                                                      116x             680x 132x               5x 5x                     5x   5x 10x         10x   2x 2x 2x 2x 2x                                 8x 8x   8x           8x 8x     8x     10x               5x                     11x     11x   11x                                               86x 86x 86x   86x               79x   3x   4x 4x 4x 4x 4x                                                   11x 75x 75x   75x 75x           75x 75x               75x                                   5x 5x             10x   5x   10x           10x     10x                 5x 10x       10x         5x                                 6x   74x 74x     65x 65x   65x 21x     44x        
/**
 * Comparison Query Builder
 * Handles period-over-period comparison queries with compareDateRange
 *
 * Responsibilities:
 * - Normalize compareDateRange date formats (relative strings, explicit arrays)
 * - Expand comparison queries into multiple period sub-queries
 * - Merge results with period metadata for client-side visualization
 * - Calculate period alignment (day-of-period index) for overlay charts
 */
 
import type {
  SemanticQuery,
  TimeDimension,
  QueryResult,
  TimeGranularity,
  PeriodComparisonMetadata
} from './types'
import { DateTimeBuilder } from './builders/date-time-builder'
import type { DatabaseAdapter } from './adapters/base-adapter'
 
/**
 * Normalized period range with start/end dates and metadata
 */
export interface NormalizedPeriod {
  /** Start date of the period */
  start: Date
  /** End date of the period */
  end: Date
  /** Human-readable label for the period */
  label: string
  /** Index in the comparison (0 = first/current, 1 = second/prior, etc.) */
  index: number
}
 
/**
 * Extended result row with period metadata for alignment
 */
export interface ComparisonResultRow extends Record<string, unknown> {
  /** Period label (e.g., "2024-01-01 - 2024-01-31") */
  __period: string
  /** Period index (0 = current, 1 = prior, etc.) */
  __periodIndex: number
  /** Day-of-period index for alignment in overlay mode */
  __periodDayIndex: number
}
 
export class ComparisonQueryBuilder {
  private dateTimeBuilder: DateTimeBuilder
 
  constructor(databaseAdapter: DatabaseAdapter) {
    this.dateTimeBuilder = new DateTimeBuilder(databaseAdapter)
  }
 
  /**
   * Check if a query contains compareDateRange
   */
  hasComparison(query: SemanticQuery): boolean {
    return query.timeDimensions?.some(td =>
      td.compareDateRange && td.compareDateRange.length >= 2
    ) ?? false
  }
 
  /**
   * Get the time dimension with compareDateRange
   */
  getComparisonTimeDimension(query: SemanticQuery): TimeDimension | undefined {
    return query.timeDimensions?.find(td =>
      td.compareDateRange && td.compareDateRange.length >= 2
    )
  }
 
  /**
   * Normalize compareDateRange entries to concrete date ranges
   * Handles both relative strings ('last 30 days') and explicit arrays (['2024-01-01', '2024-01-31'])
   */
  normalizePeriods(
    compareDateRange: (string | [string, string])[]
  ): NormalizedPeriod[] {
    const periods: NormalizedPeriod[] = []
 
    for (let i = 0; i < compareDateRange.length; i++) {
      const range = compareDateRange[i]
      let start: Date
      let end: Date
      let label: string
 
      if (typeof range === 'string') {
        // Relative date string (e.g., 'last 30 days', 'this week')
        const parsed = this.dateTimeBuilder.parseRelativeDateRange(range)
        if (parsed) {
          start = parsed.start
          end = parsed.end
          label = range
        } else E{
          // Try to parse as absolute date
          const dateObj = new Date(range)
          if (!isNaN(dateObj.getTime())) {
            start = new Date(dateObj)
            start.setUTCHours(0, 0, 0, 0)
            end = new Date(dateObj)
            end.setUTCHours(23, 59, 59, 999)
            label = range
          } else {
            // Skip invalid range
            continue
          }
        }
      } else {
        // Explicit array format ['2024-01-01', '2024-01-31']
        start = new Date(range[0])
        end = new Date(range[1])
 
        Iif (isNaN(start.getTime()) || isNaN(end.getTime())) {
          // Skip invalid range
          continue
        }
 
        // For date-only strings, treat end date as end-of-day
        Eif (/^\d{4}-\d{2}-\d{2}$/.test(range[1])) {
          end.setUTCHours(23, 59, 59, 999)
        }
 
        label = `${range[0]} - ${range[1]}`
      }
 
      periods.push({
        start,
        end,
        label,
        index: i
      })
    }
 
    return periods
  }
 
  /**
   * Create sub-query for a specific period
   * Replaces compareDateRange with a concrete dateRange for that period
   */
  createPeriodQuery(
    query: SemanticQuery,
    period: NormalizedPeriod
  ): SemanticQuery {
    return {
      ...query,
      timeDimensions: query.timeDimensions?.map(td => {
        Eif (td.compareDateRange) {
          // Replace compareDateRange with concrete dateRange for this period
          return {
            ...td,
            dateRange: [
              period.start.toISOString(),
              period.end.toISOString()
            ],
            // Remove compareDateRange to prevent recursion
            compareDateRange: undefined
          }
        }
        return td
      })
    }
  }
 
  /**
   * Calculate the day-of-period index for a date
   * Used for aligning data points across periods in overlay mode
   */
  calculatePeriodDayIndex(
    date: Date | string,
    periodStart: Date,
    granularity: TimeGranularity
  ): number {
    const dateObj = typeof date === 'string' ? new Date(date) : date
    const startTime = periodStart.getTime()
    const dateTime = dateObj.getTime()
 
    switch (granularity) {
      case 'second':
        return Math.floor((dateTime - startTime) / 1000)
      case 'minute':
        return Math.floor((dateTime - startTime) / (1000 * 60))
      case 'hour':
        return Math.floor((dateTime - startTime) / (1000 * 60 * 60))
      case 'day':
        return Math.floor((dateTime - startTime) / (1000 * 60 * 60 * 24))
      case 'week':
        return Math.floor((dateTime - startTime) / (1000 * 60 * 60 * 24 * 7))
      case 'month': {
        const startYear = periodStart.getUTCFullYear()
        const startMonth = periodStart.getUTCMonth()
        const dateYear = dateObj.getUTCFullYear()
        const dateMonth = dateObj.getUTCMonth()
        return (dateYear - startYear) * 12 + (dateMonth - startMonth)
      }
      case 'quarter': {
        const startYear = periodStart.getUTCFullYear()
        const startQuarter = Math.floor(periodStart.getUTCMonth() / 3)
        const dateYear = dateObj.getUTCFullYear()
        const dateQuarter = Math.floor(dateObj.getUTCMonth() / 3)
        return (dateYear - startYear) * 4 + (dateQuarter - startQuarter)
      }
      case 'year':
        return dateObj.getUTCFullYear() - periodStart.getUTCFullYear()
      default:
        // Default to days
        return Math.floor((dateTime - startTime) / (1000 * 60 * 60 * 24))
    }
  }
 
  /**
   * Add period metadata to result rows
   */
  addPeriodMetadata(
    data: Record<string, unknown>[],
    period: NormalizedPeriod,
    timeDimensionKey: string,
    granularity: TimeGranularity
  ): ComparisonResultRow[] {
    return data.map(row => {
      const timeDimensionValue = row[timeDimensionKey]
      let periodDayIndex = 0
 
      Eif (timeDimensionValue) {
        const dateValue = typeof timeDimensionValue === 'string'
          ? new Date(timeDimensionValue)
          : timeDimensionValue instanceof Date
            ? timeDimensionValue
            : null
 
        Eif (dateValue && !isNaN(dateValue.getTime())) {
          periodDayIndex = this.calculatePeriodDayIndex(
            dateValue,
            period.start,
            granularity
          )
        }
      }
 
      return {
        ...row,
        __period: period.label,
        __periodIndex: period.index,
        __periodDayIndex: periodDayIndex
      } as ComparisonResultRow
    })
  }
 
  /**
   * Merge results from multiple period queries
   * Adds period metadata and creates combined result with annotation
   */
  mergeComparisonResults(
    periodResults: Array<{ result: QueryResult; period: NormalizedPeriod }>,
    timeDimension: TimeDimension,
    granularity: TimeGranularity
  ): QueryResult {
    const allData: ComparisonResultRow[] = []
    let mergedAnnotation = {
      measures: {} as Record<string, any>,
      dimensions: {} as Record<string, any>,
      segments: {} as Record<string, any>,
      timeDimensions: {} as Record<string, any>
    }
 
    const periods = periodResults.map(pr => pr.period)
 
    for (const { result, period } of periodResults) {
      // Add period metadata to each row
      const rowsWithMetadata = this.addPeriodMetadata(
        result.data,
        period,
        timeDimension.dimension,
        granularity
      )
      allData.push(...rowsWithMetadata)
 
      // Merge annotations (they should be the same across periods)
      mergedAnnotation = {
        measures: { ...mergedAnnotation.measures, ...result.annotation.measures },
        dimensions: { ...mergedAnnotation.dimensions, ...result.annotation.dimensions },
        segments: { ...mergedAnnotation.segments, ...result.annotation.segments },
        timeDimensions: { ...mergedAnnotation.timeDimensions, ...result.annotation.timeDimensions }
      }
    }
 
    // Add period comparison metadata
    const periodMetadata: PeriodComparisonMetadata = {
      ranges: periods.map(p => [
        p.start.toISOString().split('T')[0],
        p.end.toISOString().split('T')[0]
      ] as [string, string]),
      labels: periods.map(p => p.label),
      timeDimension: timeDimension.dimension,
      granularity
    }
 
    return {
      data: allData,
      annotation: {
        ...mergedAnnotation,
        periods: periodMetadata
      }
    }
  }
 
  /**
   * Sort merged results by period index and then by time dimension
   * Ensures consistent ordering for client-side processing
   */
  sortComparisonResults(
    data: ComparisonResultRow[],
    timeDimensionKey: string
  ): ComparisonResultRow[] {
    return [...data].sort((a, b) => {
      // First sort by period index
      const periodDiff = a.__periodIndex - b.__periodIndex
      if (periodDiff !== 0) return periodDiff
 
      // Then sort by time dimension
      const aTime = a[timeDimensionKey]
      const bTime = b[timeDimensionKey]
 
      if (typeof aTime === 'string' && typeof bTime === 'string') {
        return new Date(aTime).getTime() - new Date(bTime).getTime()
      }
 
      return 0
    })
  }
}