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
60 lines
1.9 KiB
PHP
60 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Insights;
|
|
|
|
use App\Dto\Insights\AvailabilityData;
|
|
use App\Dto\Insights\ListingHistory;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class AvailabilityCalculator
|
|
{
|
|
/**
|
|
* @param Collection<int, ListingHistory> $listings
|
|
* @return Collection<int, AvailabilityData>
|
|
*/
|
|
public function calculate(Collection $listings): Collection
|
|
{
|
|
return $listings
|
|
->map(function (ListingHistory $listing): AvailabilityData {
|
|
$history = $listing->history;
|
|
|
|
if ($history->isEmpty()) {
|
|
return new AvailabilityData($listing->storeName, 0.0, $listing->availability, []);
|
|
}
|
|
|
|
$start = Carbon::parse($history->keys()->first());
|
|
$end = Carbon::parse($history->keys()->last());
|
|
|
|
$segments = [];
|
|
$available = 0;
|
|
$total = 0;
|
|
$current = -1;
|
|
|
|
for ($day = $start->copy(); $day->lte($end); $day->addDay()) {
|
|
$key = $day->toDateString();
|
|
$inStock = $history->has($key) && (float) $history->get($key) > 0;
|
|
$total++;
|
|
if ($inStock) {
|
|
$available++;
|
|
}
|
|
|
|
if ($current < 0 || $segments[$current]['available'] !== $inStock) {
|
|
$segments[] = ['available' => $inStock, 'days' => 1];
|
|
$current++;
|
|
} else {
|
|
$segments[$current]['days']++;
|
|
}
|
|
}
|
|
|
|
return new AvailabilityData(
|
|
storeName: $listing->storeName,
|
|
inStockPercent: $total > 0 ? round($available / $total * 100, 0) : 0.0,
|
|
currentStatus: $listing->availability,
|
|
segments: $segments,
|
|
);
|
|
})
|
|
->values();
|
|
}
|
|
}
|