All files / src/utils statistic.ts

96.5% Statements 276/286
83.13% Branches 69/83
81.81% Functions 18/22
96.5% Lines 276/286

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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 4391x     1x 1x 1x     1x                                   1x               1x 1x                               1x 6x 6x 6x 6x 6x 6x   6x 11x 11x 1x 1x 1x   10x 11x   11x 6x   6x 6x             1x 553x 553x 553x 553x                 1x 3x   2x 2x 4x 4x   4x 4x 2x 2x 2x                   1x 84x 84x 84x 84x 84x 84x         1x         1x   1x 1x 1x 1x 1x   1x 1x 1x   1x         1x 1x 1x 1x 1x 1x 1x 1x                             1x 1x 1x 2x 2x 10x 10x 10x 10x 5x 5x 5x 5x 5x 5x 10x 10x 2x 2x 1x 1x   1x 1x 1x 1x 31x 31x 62x 62x 62x 62x 31x 31x 1x 1x 1x 1x   1x 1x 2x 2x 2x 2x 6x 12x 12x 6x 6x 2x 2x 1x 1x   1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 24x 12x 12x 1x 1x 1x 1x 1x   1x 3x 3x 3x 3x 3x 3x 3x       3x     3x 2x 2x   2x 1x 1x 1x 1x 1x   1x 1x 1x 5x 5x   5x 5x   5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 1x 1x   1x 1x 1x   1x 1x 1x       1x 1x 1x   1x 1x 31x 31x 31x 31x   1x 1x   1x 31x 31x 31x   31x 31x 31x 31x 31x 31x 31x 1x   1x 1x 1x 1x 1x   1x 1x     1x 1x 1x   1x 1x 1x 2x 1x   1x 2x 2x 1x   1x 1x         1x 2x 2x 2x 2x 1x 1x   1x     1x       1x 1x 1x 1x 1x 1x 1x                       1x 16x 16x 16x   1x 4x 4x 4x 4x   1x 2x   1x 5x 5x 3x 2x 5x   1x 2x 2x   1x         2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x  
import { format, getDaysInMonth } from 'date-fns';
 
// Utils
import { getLocalStorage, setLocalStorage } from '@shared/utils';
import { getDefaultTimeRange, parseDay, parseTimeRanges } from './date';
import { isValidChartMode } from './chart';
 
// Types
import {
  ChartKey,
  ChartMode,
  ChartRow,
  ChartType,
  DayMap,
  LineChartRow,
  Metric,
  TransformedData,
} from '@/types/chart';
import {
  StatisticsResponse,
  FormattedStatistic,
  ExtractedStatsData,
  StoredFilterState,
} from '@/types/statistic';
 
// Constants
import {
  CHART_FIELDS,
  EXTRACTED_DEFAULT_STATS,
  EXTRACTED_TOTAL_STATS,
  LABEL_FORMATS,
  TITLE_FORMATS,
  TOTAL_MODES_DEFAULT,
} from '@/constants/chart';
import { DATE_FORMATTER } from '@/constants/date';
import {
  CURRENT_MODE_STORAGE_KEY,
  FILTERS_STORAGE_KEY,
} from '@/constants/stat';
 
/**
 * Build a single row of data for a multi-line chart.
 *
 * @param label - The label to display on the x-axis (e.g. day number or weekday).
 * @param dateStrs - Array of date strings (YYYYMMDD) corresponding to each dataset.
 *                   Each index aligns with one dataset in `dataSets`.
 *                   If a date is missing or invalid, its value is `undefined`.
 * @param dataSets - Array of DayMap objects, where each DayMap represents a month/week of data.
 *                   Keys are date strings (YYYYMMDD), values are daily metrics.
 * @param key - The chart metric key (e.g. ChartKey.LIKE, ChartKey.DISLIKE, ChartKey.SLOT).
 */
export const buildLineRow = (
  label: string,
  dateStrs: (string | undefined)[],
  dataSets: DayMap[],
  key: ChartKey,
): LineChartRow => {
  const row: LineChartRow = { label };
 
  dataSets.forEach((set, idx) => {
    const dateStr = dateStrs[idx];
    if (!dateStr) {
      row[`${idx + 1}`] = null;
      return;
    }
 
    const d = set[dateStr];
    const noDataOrHoliday = !d || d.isHoliday;
 
    row[`${idx + 1}`] = key && !noDataOrHoliday ? (d[key] as number) : null;
  });
 
  return row;
};
/**
 * Extract year and month from a date string in "yyyyMMdd" format.
 *
 * @param dateStr - Date string in the format "yyyyMMdd".
 * @returns An object with numeric year and month.
 */
export const extractDate = (dateStr: string) => {
  const year = parseInt(dateStr.slice(0, 4), 10);
  const month = parseInt(dateStr.slice(4, 6), 10);
  return { year, month };
};
 
/**
 * Get the maximum number of days among all months in the provided datasets.
 *
 * @param dataSets - Array of DayMap objects, where each DayMap represents
 *                   a collection of days in a given month. Keys are date
 *                   strings in the format "yyyyMMdd".
 */
export const getMaxDay = (dataSets: DayMap[]): number => {
  if (!dataSets.length) return 0;
 
  return Math.max(
    ...dataSets.map((d) => {
      const sampleKey = Object.keys(d)[0];
      if (!sampleKey) return 0;
 
      const { year, month } = extractDate(sampleKey);
      return getDaysInMonth(new Date(year, month - 1));
    }),
  );
};
 
/**
 * Format a date into a string based on the chart mode and provided formats.
 *
 * @param day - The date to be formatted.
 * @param mode - The chart mode (e.g., Week, Month, Quarter, Year).
 * @param dataFormats - A map of chart modes to date format strings (e.g., { [ChartMode.Week]: 'EEE' }).
 *                      Supports partial records, so only the needed modes must be defined.
 */
export const getChartDateFormat = (
  day: Date,
  mode: ChartMode,
  dataFormats: Partial<Record<ChartMode, string>>,
): string => {
  return format(day, dataFormats[mode] ?? '');
};
 
// A formatter map for total chart data.
// Each ChartMode gets its own function to transform { start, end } dates
// into human-readable { label, title } strings used in chart labels & tooltips.
export const getTotalDateFormat: Partial<
  Record<
    ChartMode,
    (d: { start: string; end: string }) => { label: string; title: string }
  >
> = {
  // Quarter mode (e.g., "Q1, 2025")
  [ChartMode.Quarter]: ({ start }) => {
    const s = parseDay(start);
    const q = Math.floor(s.getMonth() / 3) + 1;
    return { label: `Q${q}`, title: `Q${q}, ${DATE_FORMATTER.YEAR(s)}` };
  },
  // Week mode (can be a single day or a date range)
  [ChartMode.Week]: ({ start, end }) => {
    const s = parseDay(start);
    const e = parseDay(end);
 
    if (start === end) {
      return {
        label: DATE_FORMATTER.MONTH_DAY(s),
        title: DATE_FORMATTER.FULL(s),
      };
    } else {
      return {
        label: `${DATE_FORMATTER.MONTH_DAY(s)}-${DATE_FORMATTER.DAY(e)}`,
        title: `${DATE_FORMATTER.MONTH_DAY(s)}-${DATE_FORMATTER.DAY_YEAR(e)}`,
      };
    }
  },
};
 
type LineChartBuilder = {
  getData: (
    dataSets: DayMap[],
    isTotal: boolean,
  ) => { label: string; dateStrs: (string | undefined)[] }[];
  getMetricLabel: (index: number, isTotal: boolean) => string;
};
 
/**
 * A collection of line chart builders for each chart mode.
 * Defines how to generate axis labels and metric labels
 * for Week, Month, Quarter, and Year modes.
 */
export const LINE_CHART_BUILDERS: Record<ChartMode, LineChartBuilder> = {
  [ChartMode.Week]: {
    getData: (dataSets, isTotal) => {
      const maxWeeks = Math.max(...dataSets.map((d) => Object.keys(d).length));
      return Array.from({ length: maxWeeks }, (_, idx) => {
        const dateStrs = dataSets.map((week) => Object.keys(week).sort()[idx]);
        const firstDate = dateStrs.find(Boolean)!;
        return {
          label: isTotal
            ? `W${idx + 1}`
            : getChartDateFormat(
                parseDay(firstDate),
                ChartMode.Week,
                LABEL_FORMATS,
              ),
          dateStrs,
        };
      });
    },
    getMetricLabel: (i, isTotal) => `${isTotal ? 'M' : 'W'}${i + 1}`,
  },
 
  [ChartMode.Month]: {
    getData: (dataSets) => {
      const maxDays = getMaxDay(dataSets);
      return Array.from({ length: maxDays }, (_, i) => {
        const dayNum = i + 1;
        const dateStrs = dataSets.map((month) => {
          const sample = Object.keys(month)[0];
          if (!sample) return;
          const { year, month: m } = extractDate(sample);
          return `${year}${String(m).padStart(2, '0')}${String(dayNum).padStart(2, '0')}`;
        });
        return { label: String(dayNum), dateStrs };
      });
    },
    getMetricLabel: (i) => `M${i + 1}`,
  },
 
  [ChartMode.Quarter]: {
    getData: (dataSets, isTotal) => {
      const baseDates = Object.keys(
        dataSets.find((q) => Object.keys(q).length > 0) ?? {},
      ).sort();
      return baseDates.map((_, idx) => {
        const dateStrs = dataSets.map((quarter) => {
          const keys = Object.keys(quarter).sort();
          return keys[idx];
        });
        return { label: `${isTotal ? 'Q' : 'M'}${idx + 1}`, dateStrs };
      });
    },
    getMetricLabel: (i, isTotal) => `${isTotal ? 'Y' : 'Q'}${i + 1}`,
  },
 
  [ChartMode.Year]: {
    getData: (dataSets) => {
      return Array.from({ length: 12 }, (_, i) => {
        const month = i + 1;
        const label = getChartDateFormat(
          new Date(1, month - 1, 1),
          ChartMode.Year,
          LABEL_FORMATS,
        );
        const dateStrs = dataSets.map((yearData) =>
          Object.keys(yearData).find((d) => extractDate(d).month === month),
        );
        return { label, dateStrs };
      });
    },
    getMetricLabel: (i) => `Y${i + 1}`,
  },
};
 
export const transformDaysSets = (
  dataSets: DayMap[],
  mode: ChartMode = ChartMode.Week,
  isTotal: boolean,
  timeRange: string,
  key: ChartKey = ChartKey.SLOT,
): TransformedData => {
  if (!dataSets.length) {
    return { type: null, data: [], metrics: [] } as const;
  }
 
  const items = parseTimeRanges(timeRange);
 
  // --- SINGLE (ComposedChart) ---
  if (items.length === 1) {
    const only = dataSets[0]!;
    const dates = Object.keys(only).sort();
 
    if (isTotal) {
      const metrics: Metric[] = [
        { key: ChartKey.SLOT, label: CHART_FIELDS.lunchRegistrations.name },
        { key: ChartKey.LIKE, label: CHART_FIELDS.likes.name },
        { key: ChartKey.DISLIKE, label: CHART_FIELDS.dislikes.name },
      ];
 
      if (mode in getTotalDateFormat) {
        const data: ChartRow[] = dates
          .map((date) => {
            const d = only[date];
            if (!d) return null;
 
            const formatter = getTotalDateFormat[mode];
            if (!formatter || !d.start || !d.end) return null;
 
            const { label, title } = formatter({
              start: d.start,
              end: d.end,
            });
 
            const noData = !d.lunchRegistrations;
            return {
              label,
              title,
              likes: noData ? null : d.likes,
              dislikes: noData ? null : d.dislikes,
              lunchRegistrations: noData ? null : d.lunchRegistrations,
            };
          })
          .filter(Boolean) as ChartRow[];
 
        return { type: ChartType.Composed, data, metrics };
      }
    }
 
    let filledDates = dates;
    if (mode === ChartMode.Month) {
      if (!dates.length) {
        return { type: ChartType.Composed, data: [], metrics: [] };
      }
 
      const sampleKey = dates[0]!;
      const { year, month } = extractDate(sampleKey);
      const daysInMonth = getDaysInMonth(new Date(year, month - 1));
 
      const allDates: string[] = [];
      for (let day = 1; day <= daysInMonth; day++) {
        allDates.push(
          `${year}${String(month).padStart(2, '0')}${String(day).padStart(2, '0')}`,
        );
      }
 
      filledDates = allDates;
    }
 
    const data: ChartRow[] = filledDates.map((date) => {
      const d = only[date];
      const day = parseDay(date);
      const noData = !d || d.isHoliday;
 
      return {
        label: getChartDateFormat(day, mode, LABEL_FORMATS),
        title: getChartDateFormat(day, mode, TITLE_FORMATS),
        likes: noData ? null : d.likes,
        dislikes: noData ? null : d.dislikes,
        lunchRegistrations: noData ? null : d.lunchRegistrations,
      };
    });
 
    const metrics: Metric[] = [
      { key: ChartKey.SLOT, label: CHART_FIELDS.lunchRegistrations.name },
      { key: ChartKey.LIKE, label: CHART_FIELDS.likes.name },
      { key: ChartKey.DISLIKE, label: CHART_FIELDS.dislikes.name },
    ];
 
    return { type: ChartType.Composed, data, metrics };
  }
 
  // --- MULTI (LineChart) ---
  if (items.length > 1) {
    const lineBuilder = LINE_CHART_BUILDERS[mode];
    if (!lineBuilder) return { type: null, data: [], metrics: [] };
 
    const data = lineBuilder
      .getData(dataSets, isTotal)
      .map(({ label, dateStrs }) =>
        buildLineRow(label, dateStrs, dataSets, key),
      );
 
    const metrics: Metric[] = dataSets.map((_, i) => ({
      key: `${i + 1}`,
      label: lineBuilder.getMetricLabel(i, isTotal),
    }));
 
    return { type: ChartType.Line, data, metrics };
  }
 
  return { type: null, data: [], metrics: [] };
};
 
export const formattedStatsResponse = <T extends ChartMode>(
  type: T,
  data: StatisticsResponse[],
): FormattedStatistic<T> => {
  if (!data?.length) {
    return [];
  }
 
  const defaultExtractor = EXTRACTED_DEFAULT_STATS[type] as (
    d: StatisticsResponse,
  ) => ExtractedStatsData<T>;
  const totalExtractor = EXTRACTED_TOTAL_STATS[type] as (
    d: StatisticsResponse,
  ) => ExtractedStatsData<T>;
 
  return data.map((d) => ({
    id: d.id,
    stats: d.stats,
    defaultData: defaultExtractor(d),
    totalData: totalExtractor(d),
  }));
};
 
/**
 * Formats a numeric value for display in statistics.
 *
 * - Returns "0" if the value is `null`, `undefined`, or `NaN`.
 * - Otherwise, rounds the number to the nearest integer
 *   and applies locale-based thousands separators (e.g., "1,234").
 *
 * @param value The number to format.
 * @returns A string with the formatted number.
 */
export const formatResult = (value?: number) => {
  if (value == null || isNaN(value)) return '0';
  return Math.round(value).toLocaleString();
};
 
export const loadStoredFilterState = (): StoredFilterState =>
  getLocalStorage<StoredFilterState>(
    FILTERS_STORAGE_KEY,
    {},
  ) as StoredFilterState;
 
export const persistStoredFilterState = (state: StoredFilterState) =>
  setLocalStorage(FILTERS_STORAGE_KEY, state);
 
export const loadCurrentMode = (): ChartMode => {
  const stored = getLocalStorage(CURRENT_MODE_STORAGE_KEY, ChartMode.Week);
  return typeof stored === 'string' && isValidChartMode(stored)
    ? stored
    : ChartMode.Week;
};
 
export const persistCurrentMode = (mode: ChartMode) => {
  setLocalStorage(CURRENT_MODE_STORAGE_KEY, mode);
};
 
export const getInitialFilter = (): {
  mode: ChartMode;
  timeRange: string;
  totalMode: ChartMode;
  comparisonKey: ChartKey;
} => {
  const filters = loadStoredFilterState();
  const currentMode = loadCurrentMode();
  const currentFilter = filters[currentMode];
 
  return {
    mode: currentMode,
    timeRange: currentFilter?.timeRange ?? getDefaultTimeRange(currentMode),
    totalMode: currentFilter?.totalMode ?? TOTAL_MODES_DEFAULT[currentMode],
    comparisonKey: currentFilter?.comparisonKey ?? ChartKey.SLOT,
  };
};