mirror of
https://github.com/jez500/pricebuddy.git
synced 2026-11-24 19:58:13 +01:00
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
46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Insights;
|
|
|
|
use App\Dto\Insights\SeasonalityData;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class SeasonalityCalculator
|
|
{
|
|
private const ENOUGH_DAYS = 300;
|
|
|
|
/**
|
|
* @param Collection<string, float> $series
|
|
*/
|
|
public function calculate(Collection $series): SeasonalityData
|
|
{
|
|
$byMonth = array_fill(1, 12, []);
|
|
|
|
foreach ($series as $date => $price) {
|
|
$month = (int) Carbon::parse($date)->month;
|
|
$byMonth[$month][] = (float) $price;
|
|
}
|
|
|
|
$averages = [];
|
|
foreach ($byMonth as $month => $values) {
|
|
$averages[$month] = count($values) > 0 ? round(array_sum($values) / count($values), 2) : null;
|
|
}
|
|
|
|
$present = array_filter($averages, fn ($v): bool => $v !== null);
|
|
$min = count($present) > 0 ? min($present) : null;
|
|
$cheapest = $min === null
|
|
? []
|
|
: array_keys(array_filter(
|
|
$averages,
|
|
fn ($v): bool => $v !== null && abs($v - $min) < 0.005,
|
|
));
|
|
|
|
$spanDays = $series->isEmpty()
|
|
? 0
|
|
: Carbon::parse($series->keys()->first())->diffInDays(Carbon::parse($series->keys()->last()));
|
|
|
|
return new SeasonalityData($averages, $cheapest, $spanDays >= self::ENOUGH_DAYS);
|
|
}
|
|
}
|