Handle gaps in chart data when the product disappeared from the store then appeared again.

This commit was merged in pull request #40.
This commit is contained in:
2026-01-12 09:03:14 +01:00
parent 45343c9121
commit b7ebf7374a
2 changed files with 23 additions and 14 deletions

View File

@@ -30,26 +30,34 @@ final class ProductController extends BaseController
if (null === $product) { if (null === $product) {
throw $this->createNotFoundException('Product not found'); throw $this->createNotFoundException('Product not found');
} }
$priceList = $product->price()->pluck('price'); $priceList = $product->price()->pluck('price', 'created_at')->mapWithKeys(fn($price, $createdAt) => [explode(' ', $createdAt)[0] => $price])->toArray();
$stockList = $product->stock()->pluck('stock'); $stockList = $product->stock()->pluck('stock', 'created_at')->mapWithKeys(fn($stock, $createdAt) => [explode(' ', $createdAt)[0] => $stock])->toArray();
$priceDates = $product->price()->pluck('created_at')->map(fn($date) => $date->format('Y-m-d'))->toArray();
$stockDates = $product->stock()->pluck('created_at')->map(fn($date) => $date->format('Y-m-d'))->toArray();
return $this->render('product.html.twig', [ return $this->render('product.html.twig', [
'product' => $product, 'product' => $product,
'price_list' => $this->prepareChartData($priceDates, $priceList), 'price_list' => $this->prepareChartData($priceList),
'stock_list' => $this->prepareChartData($stockDates, $stockList), 'stock_list' => $this->prepareChartData($stockList),
'price_dates' => implode("','", $priceDates), 'price_dates' => implode("','", $this->dateRange(array_key_first($priceList), array_key_last($priceList))),
]); ]);
} }
private function prepareChartData($set1, $set2): string private function prepareChartData($set1): string
{ {
$data = []; $dates = $this->dateRange(array_key_first($set1), array_key_last($set1));
foreach ($set1 as $key => $value) { $data = array_map(fn($date) => ['x' => $date, 'y' => $set1[$date] ?? null], $dates);
$data[] = ['x' => $value, 'y' => $set2[$key]];
}
$stringData = json_encode($data); $stringData = json_encode($data);
return str_replace(['"x"', '"y"'], ['x', 'y'], $stringData); return str_replace(['"x"', '"y"'], ['x', 'y'], $stringData);
} }
private function dateRange($dateStart, $dateEnd): array
{
$from = new \DateTime($dateStart);
$to = new \DateTime($dateEnd);
$range = [];
for ($date = clone $from; $date < $to; $date->modify('+1 day')) {
$range[] = $date->format('Y-m-d');
}
return $range;
}
} }

View File

@@ -83,6 +83,7 @@
] ]
}, },
options: { options: {
spanGaps: false,
responsive: true, responsive: true,
animation: false, animation: false,
scales: { scales: {