All files / src/helpers priceHistory.ts

96.56% Statements 281/291
88.61% Branches 109/123
100% Functions 18/18
96.56% Lines 281/291

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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 5841x               1x   1x 1x                                                           1x                       1x 48x 48x 48x   1x                   1x 189x 189x 189x   1x                           1x 31x 31x 31x 23x 23x 8x 8x   1x                         1x 1x 129x 129x 3x 3x 126x 126x   1x                               1x 89x 89x 70x 70x 19x 61x     19x 89x   89x 89x   1x                               1x 72x 72x 72x 72x     72x 72x   1x                         1x 1x 72x 72x     72x 72x     72x 72x   1x                     1x 31x 31x 31x 1x 1x   30x 30x 30x 30x 30x   30x 31x 19x 19x 2x 2x 17x 17x 17x 17x 17x 17x 17x 19x 19x 19x 19x 19x   30x 30x 30x 30x 31x 28x 28x 28x 25x 25x 25x 25x 25x 25x 25x 25x 25x 28x   30x 30x   1x                         1x 42x 42x 42x   42x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x   13x 42x 2x 2x   11x 42x 3x 3x   11x 11x 11x 11x 11x 11x 11x 11x 11x   1x 1x 1x   1x                           1x 32x 32x 32x   32x 1x 1x   32x 32x   32x 31x 42x 42x 31x 31x   1x                                 1x 1x 32x 32x   32x 32x 32x 32x 32x   1x                       1x 1x 2x 2x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                         1x 1x 2x   2x 2x 1x 1x 1x 1x 1x   1x                         1x 1x 99x 2x 2x 97x 97x 97x 99x 99x 99x 99x   1x                     1x 19x 19x 19x 37x 27x 37x 10x 10x 37x 19x 19x   1x                                     1x 1x 7x 7x 2x 2x 5x 5x 5x   5x 7x 12x 12x 12x 19x 19x 18x 18x 18x 19x 12x     12x 12x 2x 2x 10x 10x 5x 5x   1x                                       1x 1x 10x 10x 10x   10x 4x 4x 4x   6x 6x 5x 5x 5x 6x 6x 6x 10x 10x 10x 10x  
/**
 * @group Helpers
 * @groupDescription Records and reads per-product/per-variant price history in
 * IndexedDB. Prices are stored in standardized USD (the `usdPrice` anchor
 * computed at build time) so points stay comparable across time and convert to
 * the user's currency at display time. A new point is appended only when the
 * USD price changes, so re-running a search never adds redundant rows.
 * @source
 */
 
import { getProductIdentityKey } from '@/helpers/productIdentity';
import { getPriceSeries, getPriceSeriesByProduct, putPriceSeries } from '@/utils/idbCache';
 
/** The user settings that gate and bound price-history recording. */
type PriceHistorySettings = Pick<UserSettings, 'priceTracking'>;
 
/** Direction of the most recent price move, from {@link describeTrend}. */
type TrendDirection = 'up' | 'down' | 'flat';
 
/** Summary of the last price move for a series, from {@link describeTrend}. */
interface PriceTrend {
  /** Whether the latest point is higher, lower, or equal to the one before it. */
  direction: TrendDirection;
  /** Signed USD change between the last two points (0 when fewer than two). */
  deltaUsd: number;
  /** Percent change between the last two points (0 when fewer than two, or prior is 0). */
  pctChange: number;
}
 
/** A resolved series to record: its id, identity, labels and current USD price. */
interface SeriesInput {
  id: string;
  productKey: string;
  variantKey?: string;
  variantId?: string;
  supplier: string;
  title: string;
  permalink?: string;
  usd: number;
}
 
/**
 * Whether a value is a usable USD price: a finite, strictly-positive number.
 * Guards against `undefined`, `NaN`, and zero/negative anchors that would make
 * a meaningless history point.
 * @param value - The candidate price.
 * @returns True when the value can be recorded as a price point.
 * @example
 * ```ts
 * isRecordablePrice(19.99); // true
 * isRecordablePrice(0);     // false
 * ```
 * @source
 */
function isRecordablePrice(value: unknown): value is number {
  return typeof value === 'number' && Number.isFinite(value) && value > 0;
}
 
/**
 * Round a USD amount to 2 decimals so equality checks (dedup) aren't defeated
 * by floating-point noise.
 * @param usd - The amount to round.
 * @returns The amount rounded to 2 decimal places.
 * @example
 * ```ts
 * round2(19.990000001); // 19.99
 * ```
 * @source
 */
function round2(usd: number): number {
  return Number(usd.toFixed(2));
}
 
/**
 * Normalize the configured max-points cap to a non-negative integer. The
 * numeric settings inputs persist their value as a string, so this coerces via
 * `Number()` (not `parseInt`, which would swallow trailing junk). Any invalid
 * or non-positive value falls back to `0` (unlimited).
 * @param maxPoints - The raw `priceTracking.maxDataPoints` setting (number or string).
 * @returns A safe cap: `0` means unlimited, otherwise the integer count to keep.
 * @example
 * ```ts
 * normalizeMaxPoints(undefined); // 0
 * normalizeMaxPoints("3");       // 3
 * normalizeMaxPoints(3.7);       // 3
 * ```
 * @source
 */
function normalizeMaxPoints(maxPoints: unknown): number {
  const value = Number(maxPoints);
  if (!Number.isFinite(value) || value <= 0) {
    return 0;
  }
  return Math.floor(value);
}
 
/**
 * Derive the product's stable identity key — shared by its base series and
 * every variant series. Prefers the stamped `cacheKey`, falling back to the
 * URL then the title so scraped products without a stamped key still track.
 * @category Helpers
 * @param product - The product to key.
 * @returns The identity key, or `undefined` when neither an identity nor a
 *   supplier is available to key against.
 * @example
 * ```ts
 * productSeriesKey({ cacheKey: "889460", supplier: "Carolina", … }); // "3f9c2a…"
 * ```
 * @source
 */
export function productSeriesKey(product: Product): string | undefined {
  const identity = product.cacheKey ?? product.url ?? product.title;
  if (identity == null || String(identity).length === 0 || !product.supplier) {
    return undefined;
  }
  return getProductIdentityKey(String(identity), product.supplier);
}
 
/**
 * The variant's own supplier id, but only when it is genuinely per-variant.
 * `ProductBuilder.build()` fills unset variant fields from the parent, so a
 * variant that had no id of its own inherits the parent's — which equals its
 * `cacheKey` (the parent identity). We treat an id that matches that parent
 * identity as inherited and ignore it; anything else is the variant's real id
 * (e.g. Wix's per-selection `item.id`).
 * @param product - The parent product (source of the fallback parent identity).
 * @param variant - The variant to inspect.
 * @returns The variant's own id, or `undefined` when absent or inherited.
 * @example
 * ```ts
 * genuineVariantId(product, { id: "d5de5c76", cacheKey: "96a50af4" }); // "d5de5c76"
 * genuineVariantId(product, { id: "96a50af4", cacheKey: "96a50af4" }); // undefined
 * ```
 * @source
 */
function genuineVariantId(product: Product, variant: Variant): string | undefined {
  if (variant.id == null) {
    return undefined;
  }
  const id = String(variant.id);
  if (id.length === 0) {
    return undefined;
  }
  const parentIdentity = String(
    variant.cacheKey ?? product.cacheKey ?? product.url ?? product.title ?? '',
  );
  return id === parentIdentity ? undefined : id;
}
 
/**
 * Derive the discriminator that distinguishes a variant from its siblings within
 * a product. Prefers the variant's own id (the most stable, precise identity),
 * then the (post-build, size/grade-bearing) title, the pack size (quantity+uom),
 * and finally the sku. `sku`/inherited `id` are avoided as primary keys because
 * `ProductBuilder.build()` fills them from the parent, so siblings often share
 * them and would collapse into one series.
 * @param product - The parent product.
 * @param variant - The variant to discriminate.
 * @returns The discriminator string, or `undefined` when none is available.
 * @example
 * ```ts
 * variantDiscriminator(product, { id: "d5de5c76", cacheKey: "96a50af4" }); // "d5de5c76"
 * variantDiscriminator(product, { title: "X - 500g" }); // "X - 500g"
 * ```
 * @source
 */
function variantDiscriminator(product: Product, variant: Variant): string | undefined {
  const size = variant.quantity == null ? undefined : `${variant.quantity}${variant.uom ?? ''}`;
  const value = genuineVariantId(product, variant) ?? variant.title ?? size ?? variant.sku;
  if (value == null || String(value).length === 0) {
    return undefined;
  }
  return String(value);
}
 
/**
 * Derive the series id for one of a product's variants: the product key joined
 * with the variant's discriminator (see `variantDiscriminator`).
 * @category Helpers
 * @param product - The parent product (provides the shared product key).
 * @param variant - The variant to key.
 * @returns The variant series id, or `undefined` when the product can't be
 *   keyed or the variant has no discriminator.
 * @example
 * ```ts
 * variantSeriesKey(product, { id: "d5de5c76", cacheKey: "96a50af4" }); // "3f9c2a…::d5de5c76"
 * ```
 * @source
 */
export function variantSeriesKey(product: Product, variant: Variant): string | undefined {
  const productKey = productSeriesKey(product);
  if (productKey === undefined) {
    return undefined;
  }
  const discriminator = variantDiscriminator(product, variant);
  if (discriminator === undefined) {
    return undefined;
  }
  return `${productKey}::${discriminator}`;
}
 
/**
 * Resolve the list of series (base product plus each valid variant) to record
 * for a single product. Entries with a non-recordable USD price are skipped.
 * @param product - The product to resolve series for.
 * @returns The recordable series inputs; empty when the product can't be keyed
 *   or has no recordable price.
 * @example
 * ```ts
 * collectSeriesInputs(product); // [{ id: "3f9c2a…", usd: 19.99, … }, …]
 * ```
 * @source
 */
function collectSeriesInputs(product: Product): SeriesInput[] {
  const productKey = productSeriesKey(product);
  if (productKey === undefined) {
    return [];
  }
 
  const inputs: SeriesInput[] = [];
  // Guard against sibling entries that resolve to the same series id (e.g. two
  // same-size variants): recording both in one pass would append two points to
  // one series and manufacture a fake trend on the very first search.
  const seen = new Set<string>();
 
  // Variants first — they are the granular, per-purchasable-unit price points.
  for (const variant of product.variants ?? []) {
    const id = variantSeriesKey(product, variant);
    if (id === undefined || seen.has(id) || !isRecordablePrice(variant.usdPrice)) {
      continue;
    }
    seen.add(id);
    inputs.push({
      id,
      productKey,
      variantKey: id.slice(productKey.length + 2),
      variantId: genuineVariantId(product, variant),
      supplier: product.supplier,
      title: variant.title ?? product.title,
      permalink: variant.permalink ?? variant.url ?? product.permalink ?? product.url,
      usd: variant.usdPrice,
    });
  }
 
  // Base product: record a standalone series only when its price isn't already
  // captured by a variant. A product's headline price is usually its default
  // (first) variant, which often shares the same id/sku/price — recording both
  // would duplicate that variant's history under the product key.
  if (isRecordablePrice(product.usdPrice)) {
    const baseUsd = round2(product.usdPrice);
    const duplicated = inputs.some((input) => round2(input.usd) === baseUsd);
    if (!duplicated) {
      inputs.push({
        id: productKey,
        productKey,
        supplier: product.supplier,
        title: product.title,
        permalink: product.permalink ?? product.url,
        usd: product.usdPrice,
      });
    }
  }
 
  return inputs;
}
 
/**
 * Record one series input: create the series on first sight, or append a new
 * point only when the USD price differs from the last recorded one (dedup).
 * When a positive cap is set, the series is trimmed to its newest N points.
 * @param input - The resolved series to record.
 * @param maxPoints - Normalized cap; `0` means unlimited.
 * @param now - Epoch ms timestamp to stamp on a new point.
 * @returns Resolves once any needed write completes.
 * @example
 * ```ts
 * await recordSeries(input, 0, Date.now());
 * ```
 * @source
 */
async function recordSeries(input: SeriesInput, maxPoints: number, now: number): Promise<void> {
  const usd = round2(input.usd);
  const existing = await getPriceSeries(input.id);
 
  if (existing === undefined) {
    await putPriceSeries({
      id: input.id,
      productKey: input.productKey,
      variantKey: input.variantKey,
      variantId: input.variantId,
      supplier: input.supplier,
      title: input.title,
      permalink: input.permalink,
      points: [{ t: now, usd }],
      updatedAt: now,
    });
    return;
  }
 
  const last = existing.points.at(-1);
  if (last?.usd === usd) {
    return;
  }
 
  let points = [...existing.points, { t: now, usd }];
  if (maxPoints > 0 && points.length > maxPoints) {
    points = points.slice(points.length - maxPoints);
  }
 
  await putPriceSeries({
    ...existing,
    // Refresh display fields in case the title/permalink changed since first seen.
    title: input.title,
    permalink: input.permalink,
    points,
    updatedAt: now,
  });
}
 
/** In-flight `recordProductPrices` calls, tracked so they can be flushed before the
 * MV3 popup's JS context is torn down. See {@link flushPendingPriceHistory}. */
const pendingWrites: Set<Promise<void>> = new Set();
 
/**
 * Record the current USD price of each product (and its variants) into the
 * price-history store. A no-op when tracking is disabled. Only writes when a price
 * changes, so repeated searches over cached results add nothing.
 * @category Helpers
 * @param products - The products to record; each may carry variants.
 * @param settings - The user's `priceTracking` settings (`enabled`,
 *   `maxDataPoints`). Tracking is on unless explicitly disabled.
 * @returns Resolves once all series have been processed.
 * @example
 * ```ts
 * void recordProductPrices(finalResults, appContext.userSettings);
 * ```
 * @source
 */
async function doRecordProductPrices(
  products: Product[],
  settings?: PriceHistorySettings,
): Promise<void> {
  if (settings?.priceTracking?.enabled === false) {
    return;
  }
 
  const maxPoints = normalizeMaxPoints(settings?.priceTracking?.maxDataPoints);
  const now = Date.now();
 
  for (const product of products) {
    for (const input of collectSeriesInputs(product)) {
      await recordSeries(input, maxPoints, now);
    }
  }
}
 
/**
 * Record the current USD price of each product (and its variants) into the
 * price-history store. Fire-and-forget: the caller wraps this in `void` from the
 * search flow, but the returned promise is also tracked internally so
 * {@link flushPendingPriceHistory} can wait for it — the MV3 popup can be closed
 * (destroying its JS context) the instant results are shown, before a sequential
 * multi-series write finishes.
 * @category Helpers
 * @param products - The products to record; each may carry variants.
 * @param settings - The user's `priceTracking` settings (`enabled`,
 *   `maxDataPoints`). Tracking is on unless explicitly disabled.
 * @returns Resolves once all series have been processed.
 * @example
 * ```ts
 * void recordProductPrices(finalResults, appContext.userSettings);
 * ```
 * @source
 */
export function recordProductPrices(
  products: Product[],
  settings?: PriceHistorySettings,
): Promise<void> {
  const task = doRecordProductPrices(products, settings);
  pendingWrites.add(task);
  void task.finally(() => pendingWrites.delete(task));
  return task;
}
 
/**
 * Force all in-flight {@link recordProductPrices} writes to finish, bypassing nothing
 * (there's no debounce to skip) but giving the caller a promise to await before a
 * point where the popup could otherwise close mid-write — e.g. once a search
 * finishes. Also invoked as a `visibilitychange` backstop below.
 * @category Helpers
 * @returns Resolves once every currently-tracked write has settled.
 * @example
 * ```ts
 * await flushPendingPriceHistory();
 * ```
 * @source
 */
export async function flushPendingPriceHistory(): Promise<void> {
  await Promise.allSettled([...pendingWrites]);
}
 
// The popup's JS context is destroyed the instant it loses focus/closes, taking any
// in-flight price-history write with it. Flushing on `hidden` is a best-effort
// backstop for writes started mid-search, before performSearch's own flush (see
// useSearch.ts) gets a chance to run.
if (typeof document !== 'undefined') {
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
      void flushPendingPriceHistory();
    }
  });
}
 
/**
 * Read all recorded price-history series for a product — its base row plus any
 * variant rows — keyed by series id for direct lookup from the detail UI.
 * @category Helpers
 * @param product - The product whose history to load.
 * @returns A map of series id → {@link PriceHistoryEntry}; empty when the
 *   product can't be keyed or has no recorded history.
 * @example
 * ```ts
 * const byId = await getProductPriceHistory(product);
 * const base = byId.get(productSeriesKey(product) ?? "");
 * ```
 * @source
 */
export async function getProductPriceHistory(
  product: Product,
): Promise<Map<string, PriceHistoryEntry>> {
  const productKey = productSeriesKey(product);
  if (productKey === undefined) {
    return new Map();
  }
  const series = await getPriceSeriesByProduct(productKey);
  return new Map(series.map((entry) => [entry.id, entry]));
}
 
/**
 * Summarize the latest price move for a series from its last two points.
 * Returns a flat, zero-delta trend when there are fewer than two points.
 * @category Helpers
 * @group Formatters
 * @param points - The series points, ascending by time.
 * @returns The direction, signed USD delta, and percent change of the last move.
 * @example
 * ```ts
 * describeTrend([{ t: 1, usd: 20 }, { t: 2, usd: 22 }]);
 * // => { direction: "up", deltaUsd: 2, pctChange: 10 }
 * ```
 * @source
 */
export function describeTrend(points: readonly PricePoint[]): PriceTrend {
  if (points.length < 2) {
    return { direction: 'flat', deltaUsd: 0, pctChange: 0 };
  }
  const last = points[points.length - 1].usd;
  const prev = points[points.length - 2].usd;
  const deltaUsd = round2(last - prev);
  const pctChange = prev !== 0 ? (deltaUsd / prev) * 100 : 0;
  const direction: TrendDirection = deltaUsd > 0 ? 'up' : deltaUsd < 0 ? 'down' : 'flat';
  return { direction, deltaUsd, pctChange };
}
 
/**
 * The most recent point at or before a timestamp, or `undefined` when the
 * series hasn't started by then. Assumes points are ascending by time.
 * @param points - The series points, ascending by time.
 * @param t - The epoch-ms cutoff to look back from.
 * @returns The last point with `t` at or before the cutoff, else `undefined`.
 * @example
 * ```ts
 * lastPointAtOrBefore([{ t: 1, usd: 20 }, { t: 3, usd: 22 }], 2); // { t: 1, usd: 20 }
 * ```
 * @source
 */
function lastPointAtOrBefore(points: readonly PricePoint[], t: number): PricePoint | undefined {
  let result: PricePoint | undefined;
  for (const point of points) {
    if (point.t <= t) {
      result = point;
    } else {
      break;
    }
  }
  return result;
}
 
/**
 * Collapse several price series into one synthetic mean-price series so a
 * group (e.g. all of a product's variants) can be summarized by a single
 * trend. At each recorded timestamp the mean is taken over every series that
 * has started by then (forward-filling each series' last-known price), and
 * consecutive-equal means are deduped so {@link describeTrend}'s last two
 * points reflect an actual move. Empty in ⇒ empty out.
 * @category Helpers
 * @param seriesList - The series to aggregate; each carries ascending points.
 * @returns The mean-price series, ascending by time.
 * @example
 * ```ts
 * buildAggregateSeries([
 *   { points: [{ t: 1, usd: 10 }, { t: 3, usd: 8 }] },
 *   { points: [{ t: 1, usd: 20 }, { t: 3, usd: 18 }] },
 * ]);
 * // => [{ t: 1, usd: 15 }, { t: 3, usd: 13 }]
 * ```
 * @source
 */
export function buildAggregateSeries(seriesList: readonly PriceHistoryEntry[]): PricePoint[] {
  const withPoints = seriesList.filter((series) => series.points.length > 0);
  if (withPoints.length === 0) {
    return [];
  }
  const times = Array.from(
    new Set(withPoints.flatMap((series) => series.points.map((point) => point.t))),
  ).sort((a, b) => a - b);
 
  const aggregate: PricePoint[] = [];
  for (const t of times) {
    let sum = 0;
    let count = 0;
    for (const series of withPoints) {
      const point = lastPointAtOrBefore(series.points, t);
      if (point !== undefined) {
        sum += point.usd;
        count += 1;
      }
    }
    if (count === 0) {
      continue;
    }
    const usd = round2(sum / count);
    if (aggregate.at(-1)?.usd === usd) {
      continue;
    }
    aggregate.push({ t, usd });
  }
  return aggregate;
}
 
/**
 * Resolve the price series a results-table row should graph, shared by the
 * collapsed trend column and the expanded detail panel so the two never diverge.
 * A flattened variant row (identified by its stamped {@link Product.priceSeriesKey})
 * graphs its own variant series; any other row graphs the mean of its displayed
 * variants (see {@link buildAggregateSeries}), falling back to the base product
 * series. Returns `undefined` when there aren't two points to draw a line.
 * @category Helpers
 * @param product - The row's product.
 * @param displayedVariants - The variants shown for this row (already deduped by
 *   `resolveDisplayedVariants`); ignored for a flattened variant row.
 * @param history - Recorded series keyed by series id (from {@link getProductPriceHistory}
 *   or a bulk preload).
 * @returns The points to graph, or `undefined` when there's no drawable trend.
 * @example
 * ```ts
 * const points = resolveRowTrendPoints(product, displayedVariants, history);
 * if (points) render(<PriceSparkline points={points} />);
 * ```
 * @source
 */
export function resolveRowTrendPoints(
  product: Product,
  displayedVariants: readonly Variant[],
  history: ReadonlyMap<string, PriceHistoryEntry>,
): readonly PricePoint[] | undefined {
  if (product.priceSeriesKey !== undefined) {
    const points = history.get(product.priceSeriesKey)?.points;
    return points !== undefined && points.length >= 2 ? points : undefined;
  }
 
  const productKey = productSeriesKey(product);
  const seriesFor = (variant: Variant): PriceHistoryEntry | undefined => {
    const key = variant === product ? productKey : variantSeriesKey(product, variant);
    return key !== undefined ? history.get(key) : undefined;
  };
  const displayedSeries = displayedVariants
    .map(seriesFor)
    .filter((series): series is PriceHistoryEntry => series !== undefined);
  const basePoints = productKey !== undefined ? history.get(productKey)?.points : undefined;
  const aggregate = displayedSeries.length > 0 ? buildAggregateSeries(displayedSeries) : basePoints;
  return aggregate !== undefined && aggregate.length >= 2 ? aggregate : undefined;
}