diff --git a/src/Controller/KiCadApiController.php b/src/Controller/KiCadApiController.php index c28e87a6..2cfa9b0e 100644 --- a/src/Controller/KiCadApiController.php +++ b/src/Controller/KiCadApiController.php @@ -27,6 +27,8 @@ use App\Entity\Parts\Category; use App\Entity\Parts\Part; use App\Services\EDA\KiCadHelper; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; @@ -55,15 +57,16 @@ class KiCadApiController extends AbstractController } #[Route('/categories.json', name: 'kicad_api_categories')] - public function categories(): Response + public function categories(Request $request): Response { $this->denyAccessUnlessGranted('@categories.read'); - return $this->json($this->kiCADHelper->getCategories()); + $data = $this->kiCADHelper->getCategories(); + return $this->createCachedJsonResponse($request, $data, 300); } #[Route('/parts/category/{category}.json', name: 'kicad_api_category')] - public function categoryParts(?Category $category): Response + public function categoryParts(Request $request, ?Category $category): Response { if ($category !== null) { $this->denyAccessUnlessGranted('read', $category); @@ -72,14 +75,35 @@ class KiCadApiController extends AbstractController } $this->denyAccessUnlessGranted('@parts.read'); - return $this->json($this->kiCADHelper->getCategoryParts($category)); + $data = $this->kiCADHelper->getCategoryParts($category); + return $this->createCachedJsonResponse($request, $data, 300); } #[Route('/parts/{part}.json', name: 'kicad_api_part')] - public function partDetails(Part $part): Response + public function partDetails(Request $request, Part $part): Response { $this->denyAccessUnlessGranted('read', $part); - return $this->json($this->kiCADHelper->getKiCADPart($part)); + $data = $this->kiCADHelper->getKiCADPart($part); + return $this->createCachedJsonResponse($request, $data, 60); + } + + /** + * Creates a JSON response with HTTP cache headers (ETag and Cache-Control). + * Returns 304 Not Modified if the client's ETag matches. + */ + private function createCachedJsonResponse(Request $request, array $data, int $maxAge): JsonResponse + { + $etag = '"' . md5(json_encode($data)) . '"'; + + if ($request->headers->get('If-None-Match') === $etag) { + return new JsonResponse(null, Response::HTTP_NOT_MODIFIED); + } + + $response = new JsonResponse($data); + $response->headers->set('Cache-Control', 'private, max-age=' . $maxAge); + $response->headers->set('ETag', $etag); + + return $response; } } \ No newline at end of file diff --git a/src/Services/EDA/KiCadHelper.php b/src/Services/EDA/KiCadHelper.php index 3a613fe7..931427ba 100644 --- a/src/Services/EDA/KiCadHelper.php +++ b/src/Services/EDA/KiCadHelper.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace App\Services\EDA; +use App\Entity\Attachments\Attachment; use App\Entity\Parts\Category; use App\Entity\Parts\Footprint; use App\Entity\Parts\Part; @@ -198,14 +199,18 @@ class KiCadHelper $result["fields"]["value"] = $this->createField($part->getEdaInfo()->getValue() ?? $part->getName(), true); $result["fields"]["keywords"] = $this->createField($part->getTags()); - //Use the part info page as datasheet link. It must be an absolute URL. - $result["fields"]["datasheet"] = $this->createField( - $this->urlGenerator->generate( - 'part_info', - ['id' => $part->getId()], - UrlGeneratorInterface::ABSOLUTE_URL) + //Use the part info page as Part-DB link. It must be an absolute URL. + $partUrl = $this->urlGenerator->generate( + 'part_info', + ['id' => $part->getId()], + UrlGeneratorInterface::ABSOLUTE_URL ); + //Try to find an actual datasheet attachment (by type name, attachment name, or PDF extension) + $datasheetUrl = $this->findDatasheetUrl($part); + $result["fields"]["datasheet"] = $this->createField($datasheetUrl ?? $partUrl); + $result["fields"]["Part-DB URL"] = $this->createField($partUrl); + //Add basic fields $result["fields"]["description"] = $this->createField($part->getDescription()); if ($part->getCategory() !== null) { @@ -289,6 +294,22 @@ class KiCadHelper } } + //Add stock quantity and storage locations + $totalStock = 0; + $locations = []; + foreach ($part->getPartLots() as $lot) { + if (!$lot->isInstockUnknown() && $lot->isExpired() !== true) { + $totalStock += $lot->getAmount(); + } + if ($lot->getAmount() > 0 && $lot->getStorageLocation() !== null) { + $locations[] = $lot->getStorageLocation()->getName(); + } + } + $result['fields']['Stock'] = $this->createField($totalStock); + if ($locations !== []) { + $result['fields']['Storage Location'] = $this->createField(implode(', ', array_unique($locations))); + } + return $result; } @@ -395,4 +416,57 @@ class KiCadHelper 'visible' => $this->boolToKicadBool($visible), ]; } + + /** + * Finds the URL to the actual datasheet file for the given part. + * Searches attachments by type name, attachment name, and file extension. + * @return string|null The datasheet URL, or null if no datasheet was found. + */ + private function findDatasheetUrl(Part $part): ?string + { + $firstPdf = null; + + foreach ($part->getAttachments() as $attachment) { + //Check if the attachment type name contains "datasheet" + $typeName = $attachment->getAttachmentType()?->getName() ?? ''; + if (str_contains(mb_strtolower($typeName), 'datasheet')) { + return $this->getAttachmentUrl($attachment); + } + + //Check if the attachment name contains "datasheet" + $name = mb_strtolower($attachment->getName()); + if (str_contains($name, 'datasheet') || str_contains($name, 'data sheet')) { + return $this->getAttachmentUrl($attachment); + } + + //Track first PDF as fallback + if ($firstPdf === null && $attachment->getExtension() === 'pdf') { + $firstPdf = $attachment; + } + } + + //Use first PDF attachment as fallback + if ($firstPdf !== null) { + return $this->getAttachmentUrl($firstPdf); + } + + return null; + } + + /** + * Returns an absolute URL for viewing the given attachment. + * Prefers the external URL (direct link) over the internal view route. + */ + private function getAttachmentUrl(Attachment $attachment): string + { + if ($attachment->hasExternal()) { + return $attachment->getExternalPath(); + } + + return $this->urlGenerator->generate( + 'attachment_view', + ['id' => $attachment->getId()], + UrlGeneratorInterface::ABSOLUTE_URL + ); + } } \ No newline at end of file diff --git a/tests/Controller/KiCadApiControllerTest.php b/tests/Controller/KiCadApiControllerTest.php index a66cb8a4..cdf4f2b9 100644 --- a/tests/Controller/KiCadApiControllerTest.php +++ b/tests/Controller/KiCadApiControllerTest.php @@ -148,6 +148,11 @@ class KiCadApiControllerTest extends WebTestCase 'value' => 'http://localhost/en/part/1/info', 'visible' => 'False', ), + 'Part-DB URL' => + array( + 'value' => 'http://localhost/en/part/1/info', + 'visible' => 'False', + ), 'description' => array( 'value' => '', @@ -168,6 +173,11 @@ class KiCadApiControllerTest extends WebTestCase 'value' => '1', 'visible' => 'False', ), + 'Stock' => + array( + 'value' => '0', + 'visible' => 'False', + ), ), ); @@ -221,6 +231,11 @@ class KiCadApiControllerTest extends WebTestCase 'value' => 'http://localhost/en/part/1/info', 'visible' => 'False', ), + 'Part-DB URL' => + array ( + 'value' => 'http://localhost/en/part/1/info', + 'visible' => 'False', + ), 'description' => array ( 'value' => '', @@ -241,10 +256,42 @@ class KiCadApiControllerTest extends WebTestCase 'value' => '1', 'visible' => 'False', ), + 'Stock' => + array ( + 'value' => '0', + 'visible' => 'False', + ), ), ); self::assertEquals($expected, $data); } + public function testCategoriesHasCacheHeaders(): void + { + $client = $this->createClientWithCredentials(); + $client->request('GET', self::BASE_URL.'/categories.json'); + + self::assertResponseIsSuccessful(); + $response = $client->getResponse(); + self::assertNotNull($response->headers->get('ETag')); + self::assertStringContainsString('max-age=', $response->headers->get('Cache-Control')); + } + + public function testConditionalRequestReturns304(): void + { + $client = $this->createClientWithCredentials(); + $client->request('GET', self::BASE_URL.'/categories.json'); + + $etag = $client->getResponse()->headers->get('ETag'); + self::assertNotNull($etag); + + //Make a conditional request with the ETag + $client->request('GET', self::BASE_URL.'/categories.json', [], [], [ + 'HTTP_IF_NONE_MATCH' => $etag, + ]); + + self::assertResponseStatusCodeSame(304); + } + } \ No newline at end of file