From cc77007b49dad57dcb42dec79586056f66b499f3 Mon Sep 17 00:00:00 2001 From: Sebastian Almberg <83243306+Sebbeben@users.noreply.github.com> Date: Sun, 8 Feb 2026 09:57:10 +0100 Subject: [PATCH 01/27] Add stock quantity, datasheet URL, and HTTP caching to KiCad API - Add Stock field showing total available quantity across all part lots - Add Storage Location field when parts have stored locations - Resolve actual datasheet PDF from attachments (by type name, attachment name, or first PDF) instead of always linking to Part-DB page - Keep Part-DB page URL as separate "Part-DB URL" field - Add ETag and Cache-Control headers to all KiCad API endpoints - Support conditional requests (If-None-Match) returning 304 - Categories/part lists cached 5 min, part details cached 1 min --- src/Controller/KiCadApiController.php | 36 +++++++-- src/Services/EDA/KiCadHelper.php | 86 +++++++++++++++++++-- tests/Controller/KiCadApiControllerTest.php | 47 +++++++++++ 3 files changed, 157 insertions(+), 12 deletions(-) diff --git a/src/Controller/KiCadApiController.php b/src/Controller/KiCadApiController.php index c28e87a64..2cfa9b0e3 100644 --- a/src/Controller/KiCadApiController.php +++ b/src/Controller/KiCadApiController.php @@ -27,6 +27,8 @@ 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 @@ public function root(): Response } #[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 @@ public function categoryParts(?Category $category): Response } $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 3a613fe7e..931427bad 100644 --- a/src/Services/EDA/KiCadHelper.php +++ b/src/Services/EDA/KiCadHelper.php @@ -23,6 +23,7 @@ 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 @@ public function getKiCADPart(Part $part): array $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 @@ public function getKiCADPart(Part $part): array } } + //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 @@ private function createField(string|int|float $value, bool $visible = false): ar '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 9d33512a8..8877cf74e 100644 --- a/tests/Controller/KiCadApiControllerTest.php +++ b/tests/Controller/KiCadApiControllerTest.php @@ -148,6 +148,11 @@ public function testPartDetailsPart1(): void '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 @@ public function testPartDetailsPart1(): void 'value' => '1', 'visible' => 'False', ), + 'Stock' => + array( + 'value' => '0', + 'visible' => 'False', + ), ), ); @@ -221,6 +231,11 @@ public function testPartDetailsPart2(): void '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 @@ public function testPartDetailsPart2(): void '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 From 6422fa62d10c2fac59a24d143c83d3a872fc9b16 Mon Sep 17 00:00:00 2001 From: Sebastian Almberg <83243306+Sebbeben@users.noreply.github.com> Date: Sun, 8 Feb 2026 10:37:37 +0100 Subject: [PATCH 02/27] Add KiCadHelper unit tests and fix PDF detection for external URLs - Add comprehensive KiCadHelperTest with 14 test cases covering: - Stock quantity calculation (zero, single lot, multiple lots) - Stock exclusion of expired and unknown-quantity lots - Storage location display (present, absent, multiple) - Datasheet URL resolution by type name, attachment name, PDF extension - Datasheet fallback to Part-DB URL when no match - "Data sheet" (with space) name variant matching - Fix PDF extension detection for external attachments (getExtension() returns null for external-only attachments, now also parses URL path) --- src/Services/EDA/KiCadHelper.php | 13 +- tests/Services/EDA/KiCadHelperTest.php | 362 +++++++++++++++++++++++++ 2 files changed, 372 insertions(+), 3 deletions(-) create mode 100644 tests/Services/EDA/KiCadHelperTest.php diff --git a/src/Services/EDA/KiCadHelper.php b/src/Services/EDA/KiCadHelper.php index 931427bad..48af42194 100644 --- a/src/Services/EDA/KiCadHelper.php +++ b/src/Services/EDA/KiCadHelper.php @@ -439,9 +439,16 @@ private function findDatasheetUrl(Part $part): ?string return $this->getAttachmentUrl($attachment); } - //Track first PDF as fallback - if ($firstPdf === null && $attachment->getExtension() === 'pdf') { - $firstPdf = $attachment; + //Track first PDF as fallback (check internal extension or external URL path) + if ($firstPdf === null) { + $extension = $attachment->getExtension(); + if ($extension === null && $attachment->hasExternal()) { + $urlPath = parse_url($attachment->getExternalPath(), PHP_URL_PATH) ?? ''; + $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION)); + } + if ($extension === 'pdf') { + $firstPdf = $attachment; + } } } diff --git a/tests/Services/EDA/KiCadHelperTest.php b/tests/Services/EDA/KiCadHelperTest.php new file mode 100644 index 000000000..a2dbe68a9 --- /dev/null +++ b/tests/Services/EDA/KiCadHelperTest.php @@ -0,0 +1,362 @@ +. + */ + +declare(strict_types=1); + +namespace App\Tests\Services\EDA; + +use App\Entity\Attachments\AttachmentType; +use App\Entity\Attachments\PartAttachment; +use App\Entity\Parts\Category; +use App\Entity\Parts\Part; +use App\Entity\Parts\PartLot; +use App\Entity\Parts\StorageLocation; +use App\Services\EDA\KiCadHelper; +use Doctrine\ORM\EntityManagerInterface; +use PHPUnit\Framework\Attributes\Group; +use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; + +#[Group('DB')] +class KiCadHelperTest extends KernelTestCase +{ + private KiCadHelper $helper; + private EntityManagerInterface $em; + + protected function setUp(): void + { + self::bootKernel(); + $this->helper = self::getContainer()->get(KiCadHelper::class); + $this->em = self::getContainer()->get(EntityManagerInterface::class); + } + + /** + * Part 1 (from fixtures) has no stock lots. Stock should be 0. + */ + public function testPartWithoutStockHasZeroStock(): void + { + $part = $this->em->find(Part::class, 1); + $result = $this->helper->getKiCADPart($part); + + self::assertArrayHasKey('Stock', $result['fields']); + self::assertSame('0', $result['fields']['Stock']['value']); + } + + /** + * Part 3 (from fixtures) has a lot with amount=1.0 in StorageLocation 1. + */ + public function testPartWithStockShowsCorrectQuantity(): void + { + $part = $this->em->find(Part::class, 3); + $result = $this->helper->getKiCADPart($part); + + self::assertArrayHasKey('Stock', $result['fields']); + self::assertSame('1', $result['fields']['Stock']['value']); + } + + /** + * Part 3 has a lot with amount > 0 in StorageLocation "Node 1". + */ + public function testPartWithStorageLocationShowsLocation(): void + { + $part = $this->em->find(Part::class, 3); + $result = $this->helper->getKiCADPart($part); + + self::assertArrayHasKey('Storage Location', $result['fields']); + self::assertSame('Node 1', $result['fields']['Storage Location']['value']); + } + + /** + * Part 1 has no stock lots, so no storage location should be shown. + */ + public function testPartWithoutStorageLocationOmitsField(): void + { + $part = $this->em->find(Part::class, 1); + $result = $this->helper->getKiCADPart($part); + + self::assertArrayNotHasKey('Storage Location', $result['fields']); + } + + /** + * All parts should have a "Part-DB URL" field pointing to the part info page. + */ + public function testPartDbUrlFieldIsPresent(): void + { + $part = $this->em->find(Part::class, 1); + $result = $this->helper->getKiCADPart($part); + + self::assertArrayHasKey('Part-DB URL', $result['fields']); + self::assertStringContainsString('/part/1/info', $result['fields']['Part-DB URL']['value']); + } + + /** + * Part 1 has no attachments, so the datasheet should fall back to the Part-DB page URL. + */ + public function testDatasheetFallbackToPartUrlWhenNoAttachments(): void + { + $part = $this->em->find(Part::class, 1); + $result = $this->helper->getKiCADPart($part); + + // With no attachments, datasheet should equal Part-DB URL + self::assertSame( + $result['fields']['Part-DB URL']['value'], + $result['fields']['datasheet']['value'] + ); + } + + /** + * Part 3 has attachments but none named "datasheet" and none are PDFs, + * so the datasheet should fall back to the Part-DB page URL. + */ + public function testDatasheetFallbackWhenNoMatchingAttachments(): void + { + $part = $this->em->find(Part::class, 3); + $result = $this->helper->getKiCADPart($part); + + // "TestAttachment" (url: www.foo.bar) and "Test2" (internal: invalid) don't match datasheet patterns + self::assertSame( + $result['fields']['Part-DB URL']['value'], + $result['fields']['datasheet']['value'] + ); + } + + /** + * Test that an attachment with type name containing "Datasheet" is found. + */ + public function testDatasheetFoundByAttachmentTypeName(): void + { + $category = $this->em->find(Category::class, 1); + + // Create an attachment type named "Datasheets" + $datasheetType = new AttachmentType(); + $datasheetType->setName('Datasheets'); + $this->em->persist($datasheetType); + + // Create a part with a datasheet attachment + $part = new Part(); + $part->setName('Part with Datasheet Type'); + $part->setCategory($category); + + $attachment = new PartAttachment(); + $attachment->setName('Component Spec'); + $attachment->setURL('https://example.com/spec.pdf'); + $attachment->setAttachmentType($datasheetType); + $part->addAttachment($attachment); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + self::assertSame('https://example.com/spec.pdf', $result['fields']['datasheet']['value']); + } + + /** + * Test that an attachment named "Datasheet" is found (regardless of type). + */ + public function testDatasheetFoundByAttachmentName(): void + { + $category = $this->em->find(Category::class, 1); + $attachmentType = $this->em->find(AttachmentType::class, 1); + + $part = new Part(); + $part->setName('Part with Named Datasheet'); + $part->setCategory($category); + + $attachment = new PartAttachment(); + $attachment->setName('Datasheet BC547'); + $attachment->setURL('https://example.com/bc547-datasheet.pdf'); + $attachment->setAttachmentType($attachmentType); + $part->addAttachment($attachment); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + self::assertSame('https://example.com/bc547-datasheet.pdf', $result['fields']['datasheet']['value']); + } + + /** + * Test that a PDF attachment is used as fallback when no "datasheet" match exists. + */ + public function testDatasheetFallbackToFirstPdfAttachment(): void + { + $category = $this->em->find(Category::class, 1); + $attachmentType = $this->em->find(AttachmentType::class, 1); + + $part = new Part(); + $part->setName('Part with PDF'); + $part->setCategory($category); + + // Non-PDF attachment first + $attachment1 = new PartAttachment(); + $attachment1->setName('Photo'); + $attachment1->setURL('https://example.com/photo.jpg'); + $attachment1->setAttachmentType($attachmentType); + $part->addAttachment($attachment1); + + // PDF attachment second + $attachment2 = new PartAttachment(); + $attachment2->setName('Specifications'); + $attachment2->setURL('https://example.com/specs.pdf'); + $attachment2->setAttachmentType($attachmentType); + $part->addAttachment($attachment2); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + // Should find the .pdf file as fallback + self::assertSame('https://example.com/specs.pdf', $result['fields']['datasheet']['value']); + } + + /** + * Test that a "data sheet" variant (with space) is also matched by name. + */ + public function testDatasheetMatchesDataSheetWithSpace(): void + { + $category = $this->em->find(Category::class, 1); + $attachmentType = $this->em->find(AttachmentType::class, 1); + + $part = new Part(); + $part->setName('Part with Data Sheet'); + $part->setCategory($category); + + $attachment = new PartAttachment(); + $attachment->setName('Data Sheet v1.2'); + $attachment->setURL('https://example.com/data-sheet.pdf'); + $attachment->setAttachmentType($attachmentType); + $part->addAttachment($attachment); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + self::assertSame('https://example.com/data-sheet.pdf', $result['fields']['datasheet']['value']); + } + + /** + * Test stock calculation excludes expired lots. + */ + public function testStockExcludesExpiredLots(): void + { + $category = $this->em->find(Category::class, 1); + + $part = new Part(); + $part->setName('Part with Expired Stock'); + $part->setCategory($category); + + // Active lot + $lot1 = new PartLot(); + $lot1->setAmount(10.0); + $part->addPartLot($lot1); + + // Expired lot + $lot2 = new PartLot(); + $lot2->setAmount(5.0); + $lot2->setExpirationDate(new \DateTimeImmutable('-1 day')); + $part->addPartLot($lot2); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + // Only the active lot should be counted + self::assertSame('10', $result['fields']['Stock']['value']); + } + + /** + * Test stock calculation excludes lots with unknown stock. + */ + public function testStockExcludesUnknownLots(): void + { + $category = $this->em->find(Category::class, 1); + + $part = new Part(); + $part->setName('Part with Unknown Stock'); + $part->setCategory($category); + + // Known lot + $lot1 = new PartLot(); + $lot1->setAmount(7.0); + $part->addPartLot($lot1); + + // Unknown lot + $lot2 = new PartLot(); + $lot2->setInstockUnknown(true); + $part->addPartLot($lot2); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + self::assertSame('7', $result['fields']['Stock']['value']); + } + + /** + * Test stock sums across multiple lots. + */ + public function testStockSumsMultipleLots(): void + { + $category = $this->em->find(Category::class, 1); + $location1 = $this->em->find(StorageLocation::class, 1); + $location2 = $this->em->find(StorageLocation::class, 2); + + $part = new Part(); + $part->setName('Part in Multiple Locations'); + $part->setCategory($category); + + $lot1 = new PartLot(); + $lot1->setAmount(15.0); + $lot1->setStorageLocation($location1); + $part->addPartLot($lot1); + + $lot2 = new PartLot(); + $lot2->setAmount(25.0); + $lot2->setStorageLocation($location2); + $part->addPartLot($lot2); + + $this->em->persist($part); + $this->em->flush(); + + $result = $this->helper->getKiCADPart($part); + + self::assertSame('40', $result['fields']['Stock']['value']); + self::assertArrayHasKey('Storage Location', $result['fields']); + // Both locations should be listed + self::assertStringContainsString('Node 1', $result['fields']['Storage Location']['value']); + self::assertStringContainsString('Node 2', $result['fields']['Storage Location']['value']); + } + + /** + * Test that the Stock field visibility is "False" (not visible in schematic by default). + */ + public function testStockFieldIsNotVisible(): void + { + $part = $this->em->find(Part::class, 1); + $result = $this->helper->getKiCADPart($part); + + self::assertSame('False', $result['fields']['Stock']['visible']); + } +} From 5a19a56a45e35f0cf5cab4e3ddd771b695e0b8e4 Mon Sep 17 00:00:00 2001 From: Sebastian Almberg <83243306+Sebbeben@users.noreply.github.com> Date: Sun, 8 Feb 2026 10:46:53 +0100 Subject: [PATCH 03/27] Fix 304 response body, parse_url safety, and location/stock consistency - Use empty Response instead of JsonResponse(null) for 304 Not Modified to avoid sending "null" as response body - Guard parse_url() result with is_string() since it can return false for malformed URLs - Move storage location tracking inside the availability check so expired and unknown-quantity lots don't contribute locations --- src/Controller/KiCadApiController.php | 2 +- src/Services/EDA/KiCadHelper.php | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Controller/KiCadApiController.php b/src/Controller/KiCadApiController.php index 2cfa9b0e3..a5d5eecdb 100644 --- a/src/Controller/KiCadApiController.php +++ b/src/Controller/KiCadApiController.php @@ -97,7 +97,7 @@ private function createCachedJsonResponse(Request $request, array $data, int $ma $etag = '"' . md5(json_encode($data)) . '"'; if ($request->headers->get('If-None-Match') === $etag) { - return new JsonResponse(null, Response::HTTP_NOT_MODIFIED); + return new Response('', Response::HTTP_NOT_MODIFIED); } $response = new JsonResponse($data); diff --git a/src/Services/EDA/KiCadHelper.php b/src/Services/EDA/KiCadHelper.php index 48af42194..37b94f333 100644 --- a/src/Services/EDA/KiCadHelper.php +++ b/src/Services/EDA/KiCadHelper.php @@ -294,15 +294,16 @@ public function getKiCADPart(Part $part): array } } - //Add stock quantity and storage locations + //Add stock quantity and storage locations (only count non-expired lots with known quantity) $totalStock = 0; $locations = []; foreach ($part->getPartLots() as $lot) { - if (!$lot->isInstockUnknown() && $lot->isExpired() !== true) { + $isAvailable = !$lot->isInstockUnknown() && $lot->isExpired() !== true; + if ($isAvailable) { $totalStock += $lot->getAmount(); - } - if ($lot->getAmount() > 0 && $lot->getStorageLocation() !== null) { - $locations[] = $lot->getStorageLocation()->getName(); + if ($lot->getAmount() > 0 && $lot->getStorageLocation() !== null) { + $locations[] = $lot->getStorageLocation()->getName(); + } } } $result['fields']['Stock'] = $this->createField($totalStock); @@ -443,8 +444,8 @@ private function findDatasheetUrl(Part $part): ?string if ($firstPdf === null) { $extension = $attachment->getExtension(); if ($extension === null && $attachment->hasExternal()) { - $urlPath = parse_url($attachment->getExternalPath(), PHP_URL_PATH) ?? ''; - $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION)); + $urlPath = parse_url($attachment->getExternalPath(), PHP_URL_PATH); + $extension = is_string($urlPath) ? strtolower(pathinfo($urlPath, PATHINFO_EXTENSION)) : null; } if ($extension === 'pdf') { $firstPdf = $attachment; From 9ec6e3db700834952b2889ab6dd4470ba5119928 Mon Sep 17 00:00:00 2001 From: Sebastian Almberg <83243306+Sebbeben@users.noreply.github.com> Date: Sun, 8 Feb 2026 11:09:54 +0100 Subject: [PATCH 04/27] Fix testPartDetailsPart2 to actually test Part 2 The test was requesting /parts/1.json instead of /parts/2.json and had Part 1's expected data. Now tests Part 2 which inherits EDA info from its category and footprint, verifying the inheritance behavior. --- tests/Controller/KiCadApiControllerTest.php | 52 +++++++++++++++------ 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/tests/Controller/KiCadApiControllerTest.php b/tests/Controller/KiCadApiControllerTest.php index 8877cf74e..26a470327 100644 --- a/tests/Controller/KiCadApiControllerTest.php +++ b/tests/Controller/KiCadApiControllerTest.php @@ -187,20 +187,19 @@ public function testPartDetailsPart1(): void public function testPartDetailsPart2(): void { $client = $this->createClientWithCredentials(); - $client->request('GET', self::BASE_URL.'/parts/1.json'); + $client->request('GET', self::BASE_URL.'/parts/2.json'); - //Response should still be successful, but the result should be empty self::assertResponseIsSuccessful(); $content = $client->getResponse()->getContent(); self::assertJson($content); $data = json_decode($content, true); - //For part 2 things info should be taken from the category and footprint + //For part 2, EDA info should be inherited from category and footprint (no part-level overrides) $expected = array ( - 'id' => '1', - 'name' => 'Part 1', - 'symbolIdStr' => 'Part:1', + 'id' => '2', + 'name' => 'Part 2', + 'symbolIdStr' => 'Category:1', 'exclude_from_bom' => 'False', 'exclude_from_board' => 'True', 'exclude_from_sim' => 'False', @@ -208,32 +207,32 @@ public function testPartDetailsPart2(): void array ( 'footprint' => array ( - 'value' => 'Part:1', + 'value' => 'Footprint:1', 'visible' => 'False', ), 'reference' => array ( - 'value' => 'P', + 'value' => 'C', 'visible' => 'True', ), 'value' => array ( - 'value' => 'Part 1', + 'value' => 'Part 2', 'visible' => 'True', ), 'keywords' => array ( - 'value' => '', + 'value' => 'test, Test, Part2', 'visible' => 'False', ), 'datasheet' => array ( - 'value' => 'http://localhost/en/part/1/info', + 'value' => 'http://localhost/en/part/2/info', 'visible' => 'False', ), 'Part-DB URL' => array ( - 'value' => 'http://localhost/en/part/1/info', + 'value' => 'http://localhost/en/part/2/info', 'visible' => 'False', ), 'description' => @@ -246,14 +245,39 @@ public function testPartDetailsPart2(): void 'value' => 'Node 1', 'visible' => 'False', ), + 'Manufacturer' => + array ( + 'value' => 'Node 1', + 'visible' => 'False', + ), 'Manufacturing Status' => array ( - 'value' => '', + 'value' => 'Active', + 'visible' => 'False', + ), + 'Part-DB Footprint' => + array ( + 'value' => 'Node 1', + 'visible' => 'False', + ), + 'Mass' => + array ( + 'value' => '100.2 g', 'visible' => 'False', ), 'Part-DB ID' => array ( - 'value' => '1', + 'value' => '2', + 'visible' => 'False', + ), + 'Part-DB IPN' => + array ( + 'value' => 'IPN123', + 'visible' => 'False', + ), + 'manf' => + array ( + 'value' => 'Node 1', 'visible' => 'False', ), 'Stock' => From 44c5d9d727f832533f6ed5e97fc6e6957a85d9c2 Mon Sep 17 00:00:00 2001 From: Sebastian Almberg <83243306+Sebbeben@users.noreply.github.com> Date: Sun, 8 Feb 2026 15:35:49 +0100 Subject: [PATCH 05/27] Use Symfony's built-in ETag handling for HTTP caching Replace manual If-None-Match comparison with Response::setEtag() and Response::isNotModified(), which properly handles ETag quoting, weak vs strong comparison, and 304 response cleanup. Fixes PHPStan return type error and CI test failures. --- src/Controller/KiCadApiController.php | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/Controller/KiCadApiController.php b/src/Controller/KiCadApiController.php index a5d5eecdb..70ba77869 100644 --- a/src/Controller/KiCadApiController.php +++ b/src/Controller/KiCadApiController.php @@ -92,17 +92,12 @@ public function partDetails(Request $request, Part $part): Response * 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 + private function createCachedJsonResponse(Request $request, array $data, int $maxAge): Response { - $etag = '"' . md5(json_encode($data)) . '"'; - - if ($request->headers->get('If-None-Match') === $etag) { - return new Response('', Response::HTTP_NOT_MODIFIED); - } - $response = new JsonResponse($data); + $response->setEtag(md5(json_encode($data))); $response->headers->set('Cache-Control', 'private, max-age=' . $maxAge); - $response->headers->set('ETag', $etag); + $response->isNotModified($request); return $response; } From 9178154986c8af4152cd4e59a2328b002e9f4a18 Mon Sep 17 00:00:00 2001 From: Sebastian Almberg <83243306+Sebbeben@users.noreply.github.com> Date: Sun, 8 Feb 2026 21:46:28 +0100 Subject: [PATCH 06/27] Add configurable KiCad field export for part parameters Add a kicad_export checkbox to parameters, allowing users to control which specifications appear as fields in the KiCad HTTP library API. Parameters with kicad_export enabled are included using their formatted value, without overwriting hardcoded fields like description or Stock. --- migrations/Version20260208190000.php | 47 +++++++++++ src/Entity/Parameters/AbstractParameter.php | 22 +++++ src/Form/ParameterType.php | 6 ++ src/Services/EDA/KiCadHelper.php | 11 +++ .../parts/edit/_specifications.html.twig | 1 + .../parts/edit/edit_form_styles.html.twig | 1 + tests/Services/EDA/KiCadHelperTest.php | 80 +++++++++++++++++++ translations/messages.en.xlf | 6 ++ 8 files changed, 174 insertions(+) create mode 100644 migrations/Version20260208190000.php diff --git a/migrations/Version20260208190000.php b/migrations/Version20260208190000.php new file mode 100644 index 000000000..3ff1a80d4 --- /dev/null +++ b/migrations/Version20260208190000.php @@ -0,0 +1,47 @@ +addSql('ALTER TABLE parameters ADD kicad_export TINYINT(1) NOT NULL DEFAULT 0'); + } + + public function mySQLDown(Schema $schema): void + { + $this->addSql('ALTER TABLE parameters DROP COLUMN kicad_export'); + } + + public function sqLiteUp(Schema $schema): void + { + $this->addSql('ALTER TABLE parameters ADD COLUMN kicad_export BOOLEAN NOT NULL DEFAULT 0'); + } + + public function sqLiteDown(Schema $schema): void + { + // SQLite does not support DROP COLUMN in older versions; recreate table if needed + $this->addSql('ALTER TABLE parameters DROP COLUMN kicad_export'); + } + + public function postgreSQLUp(Schema $schema): void + { + $this->addSql('ALTER TABLE parameters ADD kicad_export BOOLEAN NOT NULL DEFAULT FALSE'); + } + + public function postgreSQLDown(Schema $schema): void + { + $this->addSql('ALTER TABLE parameters DROP COLUMN kicad_export'); + } +} diff --git a/src/Entity/Parameters/AbstractParameter.php b/src/Entity/Parameters/AbstractParameter.php index d84e68adf..2762657af 100644 --- a/src/Entity/Parameters/AbstractParameter.php +++ b/src/Entity/Parameters/AbstractParameter.php @@ -172,6 +172,13 @@ abstract class AbstractParameter extends AbstractNamedDBElement implements Uniqu #[Assert\Length(max: 255)] protected string $group = ''; + /** + * @var bool Whether this parameter should be exported as a KiCad field in the EDA HTTP library API + */ + #[Groups(['full', 'parameter:read', 'parameter:write', 'import'])] + #[ORM\Column(type: Types::BOOLEAN)] + protected bool $kicad_export = false; + /** * Mapping is done in subclasses. * @@ -471,6 +478,21 @@ public function getElementClass(): string return static::ALLOWED_ELEMENT_CLASS; } + public function isKicadExport(): bool + { + return $this->kicad_export; + } + + /** + * @return $this + */ + public function setKicadExport(bool $kicad_export): self + { + $this->kicad_export = $kicad_export; + + return $this; + } + public function getComparableFields(): array { return ['name' => $this->name, 'group' => $this->group, 'element' => $this->element?->getId()]; diff --git a/src/Form/ParameterType.php b/src/Form/ParameterType.php index 4c2174ae9..3a773f4e3 100644 --- a/src/Form/ParameterType.php +++ b/src/Form/ParameterType.php @@ -55,6 +55,7 @@ use App\Entity\Parts\MeasurementUnit; use App\Form\Type\ExponentialNumberType; use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; @@ -147,6 +148,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void 'class' => 'form-control-sm', ], ]); + + $builder->add('kicad_export', CheckboxType::class, [ + 'label' => false, + 'required' => false, + ]); } public function finishView(FormView $view, FormInterface $form, array $options): void diff --git a/src/Services/EDA/KiCadHelper.php b/src/Services/EDA/KiCadHelper.php index 37b94f333..1617e8860 100644 --- a/src/Services/EDA/KiCadHelper.php +++ b/src/Services/EDA/KiCadHelper.php @@ -311,6 +311,17 @@ public function getKiCADPart(Part $part): array $result['fields']['Storage Location'] = $this->createField(implode(', ', array_unique($locations))); } + //Add parameters marked for KiCad export + foreach ($part->getParameters() as $parameter) { + if ($parameter->isKicadExport() && $parameter->getName() !== '') { + $fieldName = $parameter->getName(); + //Don't overwrite hardcoded fields + if (!isset($result['fields'][$fieldName])) { + $result['fields'][$fieldName] = $this->createField($parameter->getFormattedValue()); + } + } + } + return $result; } diff --git a/templates/parts/edit/_specifications.html.twig b/templates/parts/edit/_specifications.html.twig index 25b001339..3226e2c05 100644 --- a/templates/parts/edit/_specifications.html.twig +++ b/templates/parts/edit/_specifications.html.twig @@ -14,6 +14,7 @@ {% trans %}specifications.unit{% endtrans %} {% trans %}specifications.text{% endtrans %} {% trans %}specifications.group{% endtrans %} + diff --git a/templates/parts/edit/edit_form_styles.html.twig b/templates/parts/edit/edit_form_styles.html.twig index 844c8700a..5376f7541 100644 --- a/templates/parts/edit/edit_form_styles.html.twig +++ b/templates/parts/edit/edit_form_styles.html.twig @@ -79,6 +79,7 @@ {{ form_widget(form.unit, {"attr": {"data-pages--parameters-autocomplete-target": "unit", "data-pages--latex-preview-target": "input"}}) }}{{ form_errors(form.unit) }} {{ form_widget(form.value_text) }}{{ form_errors(form.value_text) }} {{ form_widget(form.group) }}{{ form_errors(form.group) }} + {{ form_widget(form.kicad_export) }}