diff --git a/src/Controller/KiCadApiController.php b/src/Controller/KiCadApiController.php index c28e87a64..70ba77869 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,30 @@ 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): Response + { + $response = new JsonResponse($data); + $response->setEtag(md5(json_encode($data))); + $response->headers->set('Cache-Control', 'private, max-age=' . $maxAge); + $response->isNotModified($request); + + return $response; } } \ No newline at end of file diff --git a/src/Services/EDA/KiCadHelper.php b/src/Services/EDA/KiCadHelper.php index 3a613fe7e..37b94f333 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,23 @@ public function getKiCADPart(Part $part): array } } + //Add stock quantity and storage locations (only count non-expired lots with known quantity) + $totalStock = 0; + $locations = []; + foreach ($part->getPartLots() as $lot) { + $isAvailable = !$lot->isInstockUnknown() && $lot->isExpired() !== true; + if ($isAvailable) { + $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 +417,64 @@ 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 (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 = is_string($urlPath) ? strtolower(pathinfo($urlPath, PATHINFO_EXTENSION)) : null; + } + if ($extension === '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 a66cb8a40..d4c547006 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', + ), ), ); @@ -177,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', @@ -198,27 +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/2/info', 'visible' => 'False', ), 'description' => @@ -231,14 +245,44 @@ 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' => + array ( + 'value' => '0', 'visible' => 'False', ), ), @@ -247,4 +291,31 @@ public function testPartDetailsPart2(): void 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 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']); + } +}