All files / src/features/charts PriceHistoryChart.tsx

100% Statements 69/69
100% Branches 36/36
100% Functions 21/21
100% Lines 61/61

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                                        1x             1x 14x   14x 22x       14x   14x 22x 22x               14x     14x 14x   8x   28x 3x   25x 25x   20x 20x         20x   19x 9x       19x 19x 2x 1x     17x     19x           8x 9x 8x   9x       14x 14x 14x   6x   6x 8x 16x 12x     16x       6x 6x       14x   14x 14x 2x             12x 2x                       10x 2x                 8x 2x                 6x             6x 6x                   12x 6x   6x         8x                             14x                  
// src/features/charts/PriceHistoryChart.tsx
import React, { useMemo } from 'react';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { useUserData } from '../../hooks/useUserData';
import { usePriceHistoryQuery } from '../../hooks/queries/usePriceHistoryQuery';
import type { HistoricalPriceDataPoint } from '../../types';
 
type HistoricalData = Record<string, { date: string; price: number }[]>;
type ChartData = { date: string; [itemName: string]: number | string };
 
const COLORS = ['#10B981', '#3B82F6', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899'];
 
/**
 * Chart component displaying historical price trends for watched items.
 *
 * Refactored to use TanStack Query (ADR-0005 Phase 8).
 */
export const PriceHistoryChart: React.FC = () => {
  const { watchedItems, isLoading: isLoadingUserData } = useUserData();
 
  const watchedItemsMap = useMemo(
    () => new Map(watchedItems.map((item) => [item.master_grocery_item_id, item.name])),
    [watchedItems],
  );
 
  const watchedItemIds = useMemo(
    () =>
      watchedItems
        .map((item) => item.master_grocery_item_id)
        .filter((id): id is number => id !== undefined),
    [watchedItems],
  );
 
  const {
    data: rawData = [],
    isLoading,
    error,
  } = usePriceHistoryQuery(watchedItemIds, watchedItemIds.length > 0);
 
  // Process raw data into chart-friendly format
  const historicalData = useMemo<HistoricalData>(() => {
    if (rawData.length === 0) return {};
 
    const processedData = rawData.reduce<HistoricalData>(
      (acc, record: HistoricalPriceDataPoint) => {
        if (!record.master_item_id || record.avg_price_in_cents === null || !record.summary_date)
          return acc;
 
        const itemName = watchedItemsMap.get(record.master_item_id);
        if (!itemName) return acc;
 
        const priceInCents = record.avg_price_in_cents;
        const date = new Date(`${record.summary_date}T00:00:00`).toLocaleDateString('en-US', {
          month: 'short',
          day: 'numeric',
        });
 
        if (priceInCents === 0) return acc;
 
        if (!acc[itemName]) {
          acc[itemName] = [];
        }
 
        // Ensure we only store the LOWEST price for a given day
        const existingEntryIndex = acc[itemName].findIndex((entry) => entry.date === date);
        if (existingEntryIndex > -1) {
          if (priceInCents < acc[itemName][existingEntryIndex].price) {
            acc[itemName][existingEntryIndex].price = priceInCents;
          }
        } else {
          acc[itemName].push({ date, price: priceInCents });
        }
 
        return acc;
      },
      {},
    );
 
    // Filter out items that only have one data point for a meaningful trend line
    return Object.entries(processedData).reduce<HistoricalData>((acc, [key, value]) => {
      if (value.length > 1) {
        acc[key] = value.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
      }
      return acc;
    }, {});
  }, [rawData, watchedItemsMap]);
 
  const chartData = useMemo<ChartData[]>(() => {
    const availableItems = Object.keys(historicalData);
    if (availableItems.length === 0) return [];
 
    const dateMap: Map<string, ChartData> = new Map();
 
    availableItems.forEach((itemName) => {
      historicalData[itemName]?.forEach(({ date, price }) => {
        if (!dateMap.has(date)) {
          dateMap.set(date, { date });
        }
        // Store price in cents
        dateMap.get(date)![itemName] = price;
      });
    });
 
    return Array.from(dateMap.values()).sort(
      (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
    );
  }, [historicalData]);
 
  const availableItems = Object.keys(historicalData);
 
  const renderContent = () => {
    if (isLoading || isLoadingUserData) {
      return (
        <div role="status" className="flex justify-center items-center h-full min-h-50]">
          <LoadingSpinner /> <span className="ml-2">Loading Price History...</span>
        </div>
      );
    }
 
    if (error) {
      return (
        <div
          className="bg-red-100 dark:bg-red-900/50 border border-red-400 dark:border-red-600 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg relative h-full flex items-center justify-center"
          role="alert"
        >
          <p>
            <strong>Error:</strong> {error.message}
          </p>
        </div>
      );
    }
 
    if (watchedItems.length === 0) {
      return (
        <div className="text-center py-8 h-full flex flex-col justify-center">
          <p className="text-gray-500 dark:text-gray-400">
            Add items to your watchlist to see their price trends over time.
          </p>
        </div>
      );
    }
 
    if (availableItems.length === 0) {
      return (
        <div className="text-center py-8 h-full flex flex-col justify-center">
          <p className="text-gray-500 dark:text-gray-400">
            Not enough historical data for your watched items. Process more flyers to build a trend.
          </p>
        </div>
      );
    }
 
    return (
      <ResponsiveContainer>
        <LineChart data={chartData} margin={{ top: 5, right: 20, left: -10, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="rgba(128, 128, 128, 0.2)" />
          <XAxis dataKey="date" tick={{ fill: '#9CA3AF', fontSize: 12 }} />
          <YAxis
            tick={{ fill: '#9CA3AF', fontSize: 12 }}
            tickFormatter={(value: number) => `$${(value / 100).toFixed(2)}`}
            domain={[(a: number) => Math.floor(a * 0.95), (b: number) => Math.ceil(b * 1.05)]}
          />
          <Tooltip
            contentStyle={{
              backgroundColor: 'rgba(31, 41, 55, 0.9)',
              border: '1px solid #4B5563',
              borderRadius: '0.5rem',
            }}
            labelStyle={{ color: '#F9FAFB' }}
            formatter={(value: number | undefined) => {
              if (typeof value === 'number') {
                return [`$${(value / 100).toFixed(2)}`];
              }
              return [null];
            }}
          />
          <Legend wrapperStyle={{ fontSize: '12px' }} />
          {availableItems.map((item, index) => (
            <Line
              key={item}
              type="monotone"
              dataKey={item}
              stroke={COLORS[index % COLORS.length]}
              strokeWidth={2}
              dot={{ r: 4 }}
              connectNulls
            />
          ))}
        </LineChart>
      </ResponsiveContainer>
    );
  };
 
  return (
    <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
      <h3 className="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
        Historical Price Trends
      </h3>
      <div style={{ width: '100%', height: 300 }}>{renderContent()}</div>
    </div>
  );
};