Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions migrations/Version20260903120000.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use App\Migration\AbstractMultiPlatformMigration;
use Doctrine\DBAL\Schema\Schema;

final class Version20260903120000 extends AbstractMultiPlatformMigration
{
public function getDescription(): string
{
return 'Add nullable color column to part_custom_states table (semantic Bootstrap color used to render the state as a badge)';
}

public function mySQLUp(Schema $schema): void
{
$this->addSql('ALTER TABLE part_custom_states ADD color VARCHAR(20) DEFAULT NULL');
}

public function mySQLDown(Schema $schema): void
{
$this->addSql('ALTER TABLE part_custom_states DROP COLUMN color');
}

public function sqLiteUp(Schema $schema): void
{
$this->addSql('ALTER TABLE part_custom_states ADD COLUMN color VARCHAR(20) DEFAULT NULL');
}

public function sqLiteDown(Schema $schema): void
{
$this->addSql('ALTER TABLE part_custom_states DROP COLUMN color');
}

public function postgreSQLUp(Schema $schema): void
{
$this->addSql('ALTER TABLE part_custom_states ADD color VARCHAR(20) DEFAULT NULL');
}

public function postgreSQLDown(Schema $schema): void
{
$this->addSql('ALTER TABLE part_custom_states DROP COLUMN color');
}
}
17 changes: 17 additions & 0 deletions src/DataTables/Helpers/PartDataTableHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use App\Entity\ProjectSystem\Project;
use App\Entity\Attachments\Attachment;
use App\Entity\Parts\Part;
use App\Entity\Parts\PartCustomState;
use App\Services\Attachments\AttachmentURLGenerator;
use App\Services\Attachments\PartPreviewGenerator;
use App\Services\EntityURLGenerator;
Expand Down Expand Up @@ -170,6 +171,22 @@ public function renderEdaStatus(Part $context): string
return sprintf('<a href="%s" data-turbo="false">%s</a>', $editUrl, $statusIcon);
}

/**
* Renders the custom state of a part as the colored badge it is configured with.
* Returns an empty string if the part has no custom state.
*/
public function renderPartCustomState(?PartCustomState $state): string
{
if ($state === null) {
return '';
}

return sprintf('<span class="badge %s">%s</span>',
htmlspecialchars($state->getBadgeClass()),
htmlspecialchars($state->getName())
);
}

public function renderAmount(Part $context): string
{
$amount = $context->getAmountSum();
Expand Down
13 changes: 3 additions & 10 deletions src/DataTables/PartsDataTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,18 +198,11 @@ public function configure(DataTable $dataTable, array $options): void
return $tmp;
}
])
->add('partCustomState', TextColumn::class, [
->add('partCustomState', HTMLColumn::class, [
'label' => $this->translator->trans('part.table.partCustomState'),
'orderField' => 'NATSORT(_partCustomState.name)',
'data' => function(Part $context): string {
$partCustomState = $context->getPartCustomState();

if ($partCustomState === null) {
return '';
}

return $partCustomState->getName();
}
'data' => fn(Part $context): string
=> $this->partDataTableHelper->renderPartCustomState($context->getPartCustomState()),
])
->add('addedDate', LocaleDateTimeColumn::class, [
'label' => $this->translator->trans('part.table.addedDate'),
Expand Down
8 changes: 8 additions & 0 deletions src/DataTables/ProjectBomEntriesDataTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,14 @@ public function configure(DataTable $dataTable, array $options): void
},
])

->add('partCustomState', HTMLColumn::class, [
'label' => $this->translator->trans('part.table.partCustomState'),
'orderField' => 'NATSORT(partCustomState.name)',
'visible' => false,
'data' => fn (ProjectBOMEntry $context): string
=> $this->partDataTableHelper->renderPartCustomState($context->getPart()?->getPartCustomState()),
])

->add('mountnames', HTMLColumn::class, [
'label' => 'project.bom.mountnames',
'data' => function (ProjectBOMEntry $context) {
Expand Down
31 changes: 31 additions & 0 deletions src/Entity/Parts/PartCustomState.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
use App\State\Mcp\ListStructuralElementsProcessor;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;
Expand Down Expand Up @@ -108,6 +109,14 @@ class PartCustomState extends AbstractPartsContainingDBElement
#[Groups(['part_custom_state:read', 'part_custom_state:write', 'full', 'import'])]
protected string $comment = '';

/**
* @var PartCustomStateColor|null The semantic color this state is rendered as a badge with.
* Null keeps the default, uncolored appearance Part-DB used before this field existed.
*/
#[ORM\Column(type: Types::STRING, length: 20, nullable: true, enumType: PartCustomStateColor::class)]
#[Groups(['part_custom_state:read', 'part_custom_state:write', 'full', 'import'])]
protected ?PartCustomStateColor $color = null;

#[ORM\OneToMany(targetEntity: self::class, mappedBy: 'parent', cascade: ['persist'])]
#[ORM\OrderBy(['name' => 'ASC'])]
protected Collection $children;
Expand Down Expand Up @@ -152,4 +161,26 @@ public function __construct()
$this->attachments = new ArrayCollection();
$this->parameters = new ArrayCollection();
}

public function getColor(): ?PartCustomStateColor
{
return $this->color;
}

public function setColor(?PartCustomStateColor $color): self
{
$this->color = $color;

return $this;
}

/**
* Returns the CSS class this state is rendered as a badge with, everywhere it is shown.
* Without a configured color this is the color Part-DB used before the color existed, so an unconfigured
* state keeps looking exactly the way it did.
*/
public function getBadgeClass(): string
{
return $this->color?->toBadgeClass() ?? 'bg-primary';
}
}
53 changes: 53 additions & 0 deletions src/Entity/Parts/PartCustomStateColor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 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/>.
*/

declare(strict_types=1);

namespace App\Entity\Parts;

/**
* The semantic Bootstrap color a PartCustomState can be rendered with.
* This is a closed whitelist: no free-form CSS classes or colors can be stored.
*/
enum PartCustomStateColor: string
{
case PRIMARY = 'primary';
case SECONDARY = 'secondary';
case INFO = 'info';
case SUCCESS = 'success';
case WARNING = 'warning';
case DANGER = 'danger';
case LIGHT = 'light';
case DARK = 'dark';

public function toTranslationKey(): string
{
return 'part_custom_state.color.' . $this->value;
}

/**
* Maps this color to the fixed Bootstrap badge class it is rendered with.
* This is the only place that translates a stored color into a CSS class.
*/
public function toBadgeClass(): string
{
return 'text-bg-' . $this->value;
}
}
23 changes: 23 additions & 0 deletions src/Form/AdminPages/PartCustomStateAdminForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,29 @@

namespace App\Form\AdminPages;

use App\Entity\Base\AbstractNamedDBElement;
use App\Entity\Parts\PartCustomState;
use App\Entity\Parts\PartCustomStateColor;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\FormBuilderInterface;

class PartCustomStateAdminForm extends BaseEntityAdminForm
{
protected function additionalFormElements(FormBuilderInterface $builder, array $options, AbstractNamedDBElement $entity): void
{
if (!$entity instanceof PartCustomState) {
return;
}

$is_new = null === $entity->getID();

$builder->add('color', EnumType::class, [
'class' => PartCustomStateColor::class,
'choice_label' => fn (PartCustomStateColor $color) => $color->toTranslationKey(),
'required' => false,
'label' => 'part_custom_state.color.label',
'help' => 'part_custom_state.color.help',
'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity),
]);
}
}
10 changes: 9 additions & 1 deletion src/Serializer/APIPlatform/SkippableItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Serializer\ItemNormalizer;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
Expand Down Expand Up @@ -53,6 +54,7 @@ class SkippableItemNormalizer implements NormalizerInterface, DenormalizerInterf
public function __construct(
private readonly ItemNormalizer $inner,
private readonly IriConverterInterface $iriConverter,
private readonly ResourceClassResolverInterface $resourceClassResolver,
) {
}

Expand All @@ -63,7 +65,13 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a
// check (line 271). For abstract resource classes with a discriminator map (e.g. Attachment), this
// fails because the array has no _type key. Fix by resolving IRI strings directly.
// See: https://github.com/Part-DB/Part-DB-server/issues/1370
if (is_string($data) || (is_array($data) && isset($data['@id']) && is_string($data['@id']))) {
//
// $type must actually be an API resource for this to make sense: this normalizer also runs for plain
// value objects (e.g. backed enums) nested inside a resource, and a string value there is the enum's
// scalar value, not an IRI - treating it as one silently swallows the value instead of letting the
// regular (enum) normalizer handle it.
if ($this->resourceClassResolver->isResourceClass($type)
&& (is_string($data) || (is_array($data) && isset($data['@id']) && is_string($data['@id'])))) {
if (is_array($data)) {
$iri = $data['@id'];
} else {
Expand Down
4 changes: 4 additions & 0 deletions templates/admin/part_custom_state_admin.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@
{% trans %}part_custom_state.new{% endtrans %}
{% endblock %}

{% block additional_controls %}
{{ form_row(form.color) }}
{% endblock %}

2 changes: 1 addition & 1 deletion templates/parts/info/_sidebar.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
{% if part.partCustomState is not null %}
<div class="mt-1">
<h6>
<span class="badge bg-primary" title="{% trans %}part_custom_state.caption{% endtrans %}"><i class="fas fa-tools fa-fw"></i> {{ part.partCustomState.name }}</span>
<span class="badge {{ part.partCustomState.badgeClass }}" title="{% trans %}part_custom_state.caption{% endtrans %}"><i class="fas fa-tools fa-fw"></i> {{ part.partCustomState.name }}</span>

{% if part.partCustomState is not null and part.partCustomState.masterPictureAttachment and attachment_manager.fileExisting(part.partCustomState.masterPictureAttachment) %}
<br/>
Expand Down
18 changes: 18 additions & 0 deletions tests/API/Endpoints/PartCustomStateEndpointTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,22 @@ public function testDeleteItem(): void
{
$this->_testDeleteItem(4);
}

public function testColorIsWritableAndReadable(): void
{
$this->_testPatchItem(5, [
'color' => 'warning',
]);
self::assertJsonContains([
'color' => 'warning',
]);

//Unsetting the color must be possible again (back to the default, uncolored appearance).
//Like every other null-valued field in this API, an unset color is omitted from the response entirely
//rather than being serialized as an explicit "color": null (see e.g. InfoProviderEndpointTest).
$response = $this->_testPatchItem(5, [
'color' => null,
]);
self::assertArrayNotHasKey('color', json_decode($response->getContent(), true));
}
}
Loading