Files
pricebuddy/app/Services/Insights/DropEventCalculator.php
Jeremy d1a8f1d009 feat: product insights tab
Add a Product Insights tab backed by a suite of price-analysis calculators and a
redesigned price history chart.

- Insights calculators: listing-history and daily best-price series builders,
  price stats, percentile, deal score, distribution, drop events, store showdown,
  seasonality, availability timeline, and target tracker
- ProductInsights aggregator service composing the calculators
- Price history chart: best-price and target datasets, best-price line honours the
  unit/retail filter, horizontal scroll on mobile
- Rename the History tab to Insights with consistent heading styling
- Feature and unit test coverage, plus review-feedback fixes
2026-06-18 23:13:14 +10:00

51 lines
1.6 KiB
PHP

<?php
namespace App\Services\Insights;
use App\Dto\Insights\DropEventData;
use App\Dto\Insights\ListingHistory;
use Illuminate\Support\Collection;
class DropEventCalculator
{
/**
* @param Collection<int, ListingHistory> $listings
* @return Collection<int, DropEventData>
*/
public function calculate(Collection $listings, float $thresholdPercent = 3, int $limit = 6): Collection
{
$events = collect();
foreach ($listings as $listing) {
$previous = null;
foreach ($listing->history as $date => $price) {
$price = (float) $price;
if ($previous !== null && $previous > 0) {
$percent = (($price - $previous) / $previous) * 100;
if (abs($percent) >= $thresholdPercent) {
$events->push(new DropEventData(
storeName: $listing->storeName,
date: $date,
change: round($price - $previous, 2),
changePercent: round($percent, 1),
isDrop: $price < $previous,
));
// Intentionally advance the baseline only on a notable move, so each
// event's change is measured from the last significant price, not raw
// day-over-day noise.
$previous = $price;
}
} else {
$previous = $price;
}
}
}
return $events->sortByDesc('date')->take($limit)->values();
}
}