Files
Part-DB-server/tests/Serializer/PartNormalizerTest.php
Sebastian Almberg b9d940ae33 Enhance KiCad integration: API v2, batch EDA editing, field export control (#1241)
* 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

* 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)

* 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

* 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.

* 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.

* 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.

* Add partdb:kicad:populate command for bulk KiCad path assignment

Console command that populates KiCad footprint/symbol paths on Footprint
and Category entities based on name-to-library mappings. Supports dry-run,
force overwrite, and list modes. Includes 130+ footprint mappings and 30+
category symbol mappings for KiCad 9.x standard libraries.

* Add CSV import support for EDA/KiCad fields

Add user-friendly column aliases (kicad_symbol, kicad_footprint,
kicad_reference, kicad_value, eda_exclude_bom, etc.) to the CSV import
system. Users can now bulk-set KiCad symbols, footprints, and other EDA
metadata via CSV/Excel import without knowing the internal dot notation.

* Add batch EDA field editing from parts table

Users can now select multiple parts in any parts table and batch-edit
their EDA/KiCad fields (symbol, footprint, reference prefix, value,
visibility, exclude from BOM/board/sim). Each field has an "Apply"
checkbox so users control exactly which fields are changed.

* Remove unused counter variable in BatchEdaController

* Fix PHPStan errors in PopulateKicadCommand and BatchEdaController

Add @var type annotations for Doctrine repository findAll() calls so
PHPStan can resolve getEdaInfo() on Footprint/Category entities. Fix
array return type for numeric-string keys and add explicit callback to
array_filter to satisfy strict rules.

* Fix batch EDA edit: required validation and pre-populate shared values

- Add required=false to TriStateCheckboxType fields so HTML5 validation
  doesn't force users to check visibility/BOM/board checkboxes
- Pre-populate form fields when all selected parts share the same EDA
  value, so users can see current state before editing

* Add KiCad API v2, orderdetail export control, EDA status indicator, BOM improvements

- Add KiCad API v2 endpoints (/kicad-api/v2) with volatile field support
  for stock and storage location (shown but not saved to schematic)
- Add kicad_export flag to Orderdetail entity for per-supplier SPN control
  (backward compatible: if no flag set, all SPNs exported as before)
- Add EDA completeness indicator column in parts datatable (bolt icon)
- Add ?minimal=true query param for faster category parts loading
- Improve category descriptions (use comment instead of URL when available)
- Improve BOM importer multi-footprint support: merge entries by Part-DB
  part ID when linked, tracking footprint variants in comments
- Fix KiCost manf/manf# fields always present (not conditional on orderdetails)
- Fix duplicate getEdaInfo() call in shouldPartBeVisible
- Consolidate supplier SPN and KiCost field generation into single loop

* Fix kicad_export column default for SQLite compatibility

Add options default to ORM column definition so schema:update
works correctly on SQLite test databases.

* Make EDA status bolt icon clickable to open EDA settings tab

* Fix EDA bolt link to correctly open EDA tab via data-turbo=false

* Add configurable datasheet URL mode for KiCad API

New setting "Datasheet field links to PDF" in KiCad EDA settings.
When enabled (default), the datasheet field resolves to the actual
PDF attachment URL. When disabled, it links to the Part-DB page
(old behavior). Configurable via settings UI or EDA_KICAD_DATASHEET_AS_PDF env var.

* Fix settings crash when upgrading: make datasheetAsPdf nullable

The settings bundle stores values in the database. When upgrading from
a version without datasheetAsPdf, the stored JSON lacks this key,
causing a TypeError when assigning null to a non-nullable bool.
Making it nullable with a fallback in KiCadHelper fixes the upgrade path.

* Add functional tests for KiCad API v2 and batch EDA controller

- KiCadApiV2ControllerTest: root, categories, parts, volatile fields,
  v1 vs v2 comparison, cache headers, 304 conditional request, auth
- BatchEdaControllerTest: page load, empty redirect, form submission

* Fix test failures: correct ids format and anonymous access assertion

* Improve test coverage for BatchEdaController

Add tests for: applying all EDA fields at once, custom redirect URL,
and verifying unchecked fields are skipped.

* Address PR review: rename to eda_visibility, merge migrations, API versioning

Changes based on jbtronics' review of PR #1241:

- Rename kicad_export -> eda_visibility (entities, forms, templates,
  translations, tests) with nullable bool for system default support
- Merge two database migrations into one (Version20260211000000)
- Rename createCachedJsonResponse -> createCacheableJsonResponse
- Change bool $apiV2 -> int $apiVersion with version validation
- EDA visibility field only shown for part parameters, not other entities
- PopulateKicadCommand: check alternative names of footprints/categories
- PopulateKicadCommand: support external JSON mapping file (--mapping-file)
- Ship default mappings JSON at contrib/kicad-populate/default_mappings.json
- Add system-wide defaultEdaVisibility setting in KiCadEDASettings
- Add KiCad HTTP Library v2 spec link in controller docs

* Fix duplicate loadMappingFile method causing PHP fatal error

* Add tests for mapping file and alternative name matching, update populate command docs

Add 5 new tests for PopulateKicadCommand covering:
- Custom mapping file overriding defaults
- Invalid JSON mapping file error handling
- Missing mapping file error handling
- Footprint alternative name matching
- Category alternative name matching

Update contrib README to document --mapping-file option,
alternative name matching, and custom JSON mapping format.

* Split out KiCad API v2 into separate PR as requested by maintainer

Remove v2 controller, tests, and volatile field support from this PR.
The v2 API will be submitted as a separate PR for focused discussion.

* Improve test coverage for KiCadHelper and PopulateKicadCommand

KiCadHelper: Add tests for orderdetail eda_visibility filtering,
backward compatibility when no flags set, manufacturer/KiCost fields,
and parameter with empty name skipping.

PopulateKicadCommand: Add tests for mapping file with both footprints
and categories sections, and mapping file with only categories.

* Load populate Kicad default mappings from json file

* Moved kicad:populate documentation to central docs

* Added introduced column to PartTableColumns to make it configurable in the settings

* Use TristateCheckboxes for parameter and orderdetail types

* Fixed translation keys

* Split up default eda visibility for parameters and purchase infos

---------

Co-authored-by: Jan Böhmer <mail@jan-boehmer.de>
2026-03-01 22:10:13 +01:00

180 lines
7.6 KiB
PHP

<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2023 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Tests\Serializer;
use App\Entity\Parts\Part;
use App\Entity\Parts\PartLot;
use App\Entity\PriceInformations\Orderdetail;
use App\Entity\PriceInformations\Pricedetail;
use App\Serializer\PartNormalizer;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class PartNormalizerTest extends WebTestCase
{
/** @var PartNormalizer */
protected DenormalizerInterface&NormalizerInterface $service;
protected function setUp(): void
{
//Get a service instance.
self::bootKernel();
$this->service = self::getContainer()->get(PartNormalizer::class);
//We need to inject the serializer into the normalizer, as we use it directly
$serializer = self::getContainer()->get('serializer');
$this->service->setNormalizer($serializer);
$this->service->setDenormalizer($serializer);
}
public function testSupportsNormalization(): void
{
//Normalizer must only support Part objects (and child classes)
$this->assertFalse($this->service->supportsNormalization(new \stdClass()));
//Part serialization should only work with csv
$this->assertFalse($this->service->supportsNormalization(new Part()));
$this->assertTrue($this->service->supportsNormalization(new Part(), 'csv'));
}
public function testNormalize(): void
{
$part = new Part();
$part->setName('Test Part');
$partLot1 = new PartLot();
$partLot1->setAmount(1);
$partLot2 = new PartLot();
$partLot2->setAmount(5);
$part->addPartLot($partLot1);
$part->addPartLot($partLot2);
//Check that type field is not present in CSV export
$data = $this->service->normalize($part, 'csv', ['groups' => ['simple']]);
$this->assertSame('Test Part', $data['name']);
$this->assertArrayNotHasKey('type', $data);
}
public function testSupportsDenormalization(): void
{
//Normalizer must only support Part type with array as input
$this->assertFalse($this->service->supportsDenormalization(new \stdClass(), Part::class));
$this->assertFalse($this->service->supportsDenormalization('string', Part::class));
$this->assertFalse($this->service->supportsDenormalization(['a' => 'b'], \stdClass::class));
//Only support denormalization, if CSV import
$this->assertFalse($this->service->supportsDenormalization(['a' => 'b'], Part::class));
$this->assertTrue($this->service->supportsDenormalization(['a' => 'b'], Part::class, null, ['partdb_import' => true]));
}
public function testDenormalize(): void
{
$input = [
'name' => 'Test Part',
'description' => 'Test Description',
'notes' => 'Test Note', //Test key normalization
'ipn' => 'Test IPN',
'mpn' => 'Test MPN',
'instock' => '5',
'storage_location' => 'Test Storage Location',
'supplier' => 'Test Supplier',
'price' => '5.5',
'supplier_part_number' => 'TEST123'
];
$part = $this->service->denormalize($input, Part::class, 'json', ['groups' => ['import'], 'create_unknown_datastructures' => true]);
$this->assertInstanceOf(Part::class, $part);
$this->assertSame('Test Part', $part->getName());
$this->assertSame('Test Description', $part->getDescription());
$this->assertSame('Test Note', $part->getComment());
$this->assertSame('Test IPN', $part->getIpn());
$this->assertSame('Test MPN', $part->getManufacturerProductNumber());
//Check that a new PartLot was created
$this->assertCount(1, $part->getPartLots());
/** @var PartLot $partLot */
$partLot = $part->getPartLots()->first();
$this->assertEqualsWithDelta(5.0, $partLot->getAmount(), PHP_FLOAT_EPSILON);
$this->assertNotNull($partLot->getStorageLocation());
$this->assertSame('Test Storage Location', $partLot->getStorageLocation()->getName());
//Check that a new orderdetail was created
$this->assertCount(1, $part->getOrderdetails());
/** @var Orderdetail $orderDetail */
$orderDetail = $part->getOrderdetails()->first();
$this->assertNotNull($orderDetail->getSupplier());
$this->assertSame('Test Supplier', $orderDetail->getSupplier()->getName());
$this->assertSame('TEST123', $orderDetail->getSupplierPartNr());
//Check that a pricedetail was created
$this->assertCount(1, $orderDetail->getPricedetails());
/** @var Pricedetail $priceDetail */
$priceDetail = $orderDetail->getPricedetails()->first();
$this->assertSame("5.50000", (string) $priceDetail->getPrice());
//Must be in base currency
$this->assertNull($priceDetail->getCurrency());
//Must be for 1 part and 1 minimum order quantity
$this->assertEqualsWithDelta(1.0, $priceDetail->getPriceRelatedQuantity(), PHP_FLOAT_EPSILON);
$this->assertEqualsWithDelta(1.0, $priceDetail->getMinDiscountQuantity(), PHP_FLOAT_EPSILON);
}
public function testDenormalizeEdaFields(): void
{
$input = [
'name' => 'EDA Test Part',
'kicad_symbol' => 'Device:R',
'kicad_footprint' => 'Resistor_SMD:R_0805_2012Metric',
'kicad_reference' => 'R',
'kicad_value' => '10k',
'eda_exclude_bom' => 'true',
'eda_exclude_board' => 'false',
];
$part = $this->service->denormalize($input, Part::class, 'json', ['groups' => ['import'], 'partdb_import' => true]);
$this->assertInstanceOf(Part::class, $part);
$this->assertSame('EDA Test Part', $part->getName());
$edaInfo = $part->getEdaInfo();
$this->assertSame('Device:R', $edaInfo->getKicadSymbol());
$this->assertSame('Resistor_SMD:R_0805_2012Metric', $edaInfo->getKicadFootprint());
$this->assertSame('R', $edaInfo->getReferencePrefix());
$this->assertSame('10k', $edaInfo->getValue());
$this->assertTrue($edaInfo->getExcludeFromBom());
$this->assertFalse($edaInfo->getExcludeFromBoard());
}
public function testDenormalizeEdaFieldsEmptyValuesIgnored(): void
{
$input = [
'name' => 'Part Without EDA',
'kicad_symbol' => '',
'kicad_footprint' => '',
];
$part = $this->service->denormalize($input, Part::class, 'json', ['groups' => ['import'], 'partdb_import' => true]);
$edaInfo = $part->getEdaInfo();
$this->assertNull($edaInfo->getKicadSymbol());
$this->assertNull($edaInfo->getKicadFootprint());
}
}