diff --git a/config/services/api_platform.yaml b/config/services/api_platform.yaml index 2553ba1..771501b 100644 --- a/config/services/api_platform.yaml +++ b/config/services/api_platform.yaml @@ -142,7 +142,7 @@ services: api_platform.filter.hardware.search: parent: 'api_platform.doctrine.orm.search_filter' - arguments: [ { 'id': 'exact', 'name': 'partial' } ] + arguments: [ { 'id': 'exact', 'name': 'partial', 'clients.id': 'exact' } ] tags: [ 'api_platform.filter' ] api_platform.filter.menu.order: diff --git a/migrations/Version20260710100654.php b/migrations/Version20260710100654.php new file mode 100644 index 0000000..bc99704 --- /dev/null +++ b/migrations/Version20260710100654.php @@ -0,0 +1,42 @@ + HardwareProfile de OneToOne (perfil propio + * de cada cliente) a OneToMany (un perfil de hardware compartido por varios + * clientes de una misma aula), para permitir asignarlo y propagarlo desde + * la unidad organizativa. + */ +final class Version20260710100654 extends AbstractMigration +{ + public function getDescription(): string + { + return 'Client.hardwareProfile pasa a ser propietario de la relación (N clientes por perfil) en vez de HardwareProfile.client (1 cliente por perfil)'; + } + + public function up(Schema $schema): void + { + $this->addSql('ALTER TABLE client ADD hardware_profile_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE client ADD CONSTRAINT FK_C7440455CFA495C1 FOREIGN KEY (hardware_profile_id) REFERENCES hardware_profile (id) ON DELETE SET NULL'); + $this->addSql('CREATE INDEX IDX_C7440455CFA495C1 ON client (hardware_profile_id)'); + $this->addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921'); + $this->addSql('DROP INDEX IDX_2D9A246019EB6921 ON hardware_profile'); + $this->addSql('ALTER TABLE hardware_profile DROP client_id'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE hardware_profile ADD client_id INT NOT NULL'); + $this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE'); + $this->addSql('CREATE INDEX IDX_2D9A246019EB6921 ON hardware_profile (client_id)'); + $this->addSql('ALTER TABLE client DROP FOREIGN KEY FK_C7440455CFA495C1'); + $this->addSql('DROP INDEX IDX_C7440455CFA495C1 ON client'); + $this->addSql('ALTER TABLE client DROP hardware_profile_id'); + } +} diff --git a/src/Controller/OgAgent/HardwareInventoryAction.php b/src/Controller/OgAgent/HardwareInventoryAction.php index fb95c52..b8f5d39 100644 --- a/src/Controller/OgAgent/HardwareInventoryAction.php +++ b/src/Controller/OgAgent/HardwareInventoryAction.php @@ -167,20 +167,25 @@ class HardwareInventoryAction extends AbstractOgAgentController $hardwareProfile = $client->getHardwareProfile(); $isNewProfile = false; - + $isSharedProfile = $hardwareProfile !== null && $hardwareProfile->getClients()->count() > 1; + if (!$hardwareProfile) { $hardwareProfile = new HardwareProfile(); $hardwareProfile->setDescription('Perfil de hardware generado automáticamente para ' . $client->getIp()); - $hardwareProfile->setClient($client); $this->entityManager->persist($hardwareProfile); $isNewProfile = true; - + $this->logger->info('Nuevo perfil de hardware creado', [ 'client' => $client->getId(), 'client_ip' => $client->getIp() ]); - + $client->setHardwareProfile($hardwareProfile); + } elseif ($isSharedProfile) { + $this->logger->info('Perfil de hardware compartido con otros clientes del aula, no se sobrescribe con el inventario individual', [ + 'client' => $client->getId(), + 'profile_id' => $hardwareProfile->getId() + ]); } else { $this->logger->info('Actualizando perfil de hardware existente', [ 'client' => $client->getId(), @@ -188,16 +193,17 @@ class HardwareInventoryAction extends AbstractOgAgentController ]); } - foreach ($hardwareItems as $hardware) { - $hardwareProfile->addHardwareCollection($hardware); + if (!$isSharedProfile) { + foreach ($hardwareItems as $hardware) { + $hardwareProfile->addHardwareCollection($hardware); + } + + $this->logger->debug('Nuevo hardware añadido al perfil', [ + 'client' => $client->getId(), + 'added_hardware_count' => count($hardwareItems) + ]); } - $this->logger->debug('Nuevo hardware añadido al perfil', [ - 'client' => $client->getId(), - 'added_hardware_count' => count($hardwareItems) - ]); - - $client->setHardwareProfile($hardwareProfile); $this->entityManager->persist($client); $this->entityManager->flush(); diff --git a/src/Controller/PropagateNetworkSettingsAction.php b/src/Controller/PropagateNetworkSettingsAction.php index aa94df5..0a41156 100644 --- a/src/Controller/PropagateNetworkSettingsAction.php +++ b/src/Controller/PropagateNetworkSettingsAction.php @@ -43,11 +43,7 @@ class PropagateNetworkSettingsAction extends AbstractController foreach ($organizationalUnit->getClients() as $client) { $client->setMenu($networkSettings->getMenu()); - // No se propaga hardwareProfile: Client::$hardwareProfile es un registro 1:1 - // propio de cada cliente (hardware_profile.client_id es NOT NULL), no una - // plantilla compartible como menu/repository/bootServer/ogLive/template. - // Esta llamada además tocaba el lado inverso de la relación de Doctrine y - // nunca llegaba a persistirse. + $client->setHardwareProfile($networkSettings->getHardwareProfile()); $client->setRepository($networkSettings->getRepository()); $client->setBootServer($networkSettings->getBootServer()); $client->setOgLive($networkSettings->getOgLive()); diff --git a/src/Dto/Input/ClientInput.php b/src/Dto/Input/ClientInput.php index efa8e84..317a244 100644 --- a/src/Dto/Input/ClientInput.php +++ b/src/Dto/Input/ClientInput.php @@ -86,7 +86,13 @@ final class ClientInput #[ApiProperty( description: 'La plantilla PXE del cliente' )] - public ?PxeTemplateOutput $pxeTemplate = null; + public ?PxeTemplateOutput $pxeTemplate = null; + + #[Groups(['client:write'])] + #[ApiProperty( + description: 'El perfil de hardware del cliente' + )] + public ?HardwareProfileOutput $hardwareProfile = null; #[Groups(['client:write'])] #[ApiProperty( @@ -162,6 +168,10 @@ final class ClientInput $this->pxeTemplate = new PxeTemplateOutput($client->getTemplate()); } + if ($client->getHardwareProfile()) { + $this->hardwareProfile = new HardwareProfileOutput($client->getHardwareProfile(), includeClients: false); + } + if ($client->getRepository()) { $this->repository = new ImageRepositoryOutput($client->getRepository()); } @@ -179,6 +189,7 @@ final class ClientInput $menu = $this->menu?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getMenu(); $ogLive = $this->ogLive?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getOgLive(); + $hardwareProfile = $this->hardwareProfile?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getHardwareProfile(); $repository = $this->repository?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getRepository(); $template = $this->pxeTemplate?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getPxeTemplate(); @@ -191,6 +202,7 @@ final class ClientInput $client->setIp($this->ip); $client->setMenu($menu); $client->setOgLive($ogLive); + $client->setHardwareProfile($hardwareProfile); $client->setRepository($repository); $client->setTemplate($template); $client->setPosition($this->position); diff --git a/src/Dto/Input/HardwareProfileInput.php b/src/Dto/Input/HardwareProfileInput.php index c162328..64aacdd 100644 --- a/src/Dto/Input/HardwareProfileInput.php +++ b/src/Dto/Input/HardwareProfileInput.php @@ -5,7 +5,6 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; use App\Entity\HardwareProfile; use Symfony\Component\Serializer\Annotation\Groups; -use App\Dto\Output\ClientOutput; final class HardwareProfileInput { @@ -17,10 +16,6 @@ final class HardwareProfileInput #[ApiProperty(description: 'Comments of the hardware profile', example: "Hardware 1")] public ?string $comments = null; - #[Groups(['hardware-profile:write'])] - #[ApiProperty(description: 'The client of the hardware profile', readableLink: true)] - public ?ClientOutput $client = null; - public function __construct(?HardwareProfile $hardwareProfile = null) { if (!$hardwareProfile) { @@ -29,7 +24,6 @@ final class HardwareProfileInput $this->description = $hardwareProfile->getDescription(); $this->comments = $hardwareProfile->getComments(); - $this->client = new ClientOutput($hardwareProfile->getClient()); } public function createOrUpdateEntity(?HardwareProfile $hardwareProfile = null): HardwareProfile @@ -40,7 +34,6 @@ final class HardwareProfileInput $hardwareProfile->setDescription($this->description); $hardwareProfile->setComments($this->comments); - $hardwareProfile->setClient($this->client->getEntity()); return $hardwareProfile; } diff --git a/src/Dto/Output/HardwareProfileOutput.php b/src/Dto/Output/HardwareProfileOutput.php index 980d2e4..b67586e 100644 --- a/src/Dto/Output/HardwareProfileOutput.php +++ b/src/Dto/Output/HardwareProfileOutput.php @@ -4,6 +4,7 @@ namespace App\Dto\Output; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\Get; +use App\Entity\Client; use App\Entity\Hardware; use App\Entity\HardwareProfile; use Symfony\Component\Serializer\Annotation\Groups; @@ -27,10 +28,10 @@ final class HardwareProfileOutput extends AbstractOutput #[Groups(['hardware-profile:read'])] #[ApiProperty( - description: 'El cliente asociado a este perfil de hardware', - example: null + description: 'Los clientes que tienen asignado este perfil de hardware', + example: [] )] - public ?ClientOutput $client = null; + public array $clients = []; #[Groups(['hardware-profile:read'])] #[ApiProperty( @@ -53,14 +54,16 @@ final class HardwareProfileOutput extends AbstractOutput )] public ?string $createdBy = null; - public function __construct(HardwareProfile $hardwareProfile, bool $includeClient = true) + public function __construct(HardwareProfile $hardwareProfile, bool $includeClients = true) { parent::__construct($hardwareProfile); $this->description = $hardwareProfile->getDescription(); $this->comments = $hardwareProfile->getComments(); - if($includeClient && $hardwareProfile->getClient()) { - $this->client = new ClientOutput($hardwareProfile->getClient()); + if ($includeClients) { + $this->clients = $hardwareProfile->getClients()->map( + fn(Client $client) => new ClientOutput($client) + )->toArray(); } $this->hardwareCollection = $hardwareProfile->getHardwareCollection()->map( diff --git a/src/Entity/Client.php b/src/Entity/Client.php index 6636720..4f039ab 100644 --- a/src/Entity/Client.php +++ b/src/Entity/Client.php @@ -54,7 +54,8 @@ class Client extends AbstractEntity #[ORM\JoinColumn( onDelete: 'SET NULL')] private ?Menu $menu = null; - #[ORM\OneToOne(mappedBy: 'client', cascade: ['persist', 'remove'])] + #[ORM\ManyToOne(inversedBy: 'clients')] + #[ORM\JoinColumn(onDelete: 'SET NULL')] private ?HardwareProfile $hardwareProfile = null; #[ORM\Column(nullable: true)] diff --git a/src/Entity/HardwareProfile.php b/src/Entity/HardwareProfile.php index 533ff9b..cb40344 100644 --- a/src/Entity/HardwareProfile.php +++ b/src/Entity/HardwareProfile.php @@ -16,9 +16,11 @@ class HardwareProfile extends AbstractEntity #[ORM\Column(length: 255, nullable: true)] private ?string $comments = null; - #[ORM\ManyToOne(targetEntity: Client::class, inversedBy: 'hardwareProfile')] - #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] - private ?Client $client = null; + /** + * @var Collection + */ + #[ORM\OneToMany(mappedBy: 'hardwareProfile', targetEntity: Client::class)] + private Collection $clients; /** * @var Collection @@ -30,6 +32,7 @@ class HardwareProfile extends AbstractEntity { parent::__construct(); + $this->clients = new ArrayCollection(); $this->hardwareCollection = new ArrayCollection(); } @@ -62,14 +65,31 @@ class HardwareProfile extends AbstractEntity return $this; } - public function getClient(): ?Client + /** + * @return Collection + */ + public function getClients(): Collection { - return $this->client; + return $this->clients; } - public function setClient(?Client $client): static + public function addClient(Client $client): static { - $this->client = $client; + if (!$this->clients->contains($client)) { + $this->clients->add($client); + $client->setHardwareProfile($this); + } + + return $this; + } + + public function removeClient(Client $client): static + { + if ($this->clients->removeElement($client)) { + if ($client->getHardwareProfile() === $this) { + $client->setHardwareProfile(null); + } + } return $this; } diff --git a/src/Factory/HardwareProfileFactory.php b/src/Factory/HardwareProfileFactory.php index 13021dc..6d514c9 100644 --- a/src/Factory/HardwareProfileFactory.php +++ b/src/Factory/HardwareProfileFactory.php @@ -38,7 +38,6 @@ final class HardwareProfileFactory extends ModelFactory 'createdAt' => self::faker()->dateTime(), 'updatedAt' => self::faker()->dateTime(), 'description' => self::faker()->text(255), - 'client' => ClientFactory::new(), ]; } diff --git a/tests/Functional/ClientTest.php b/tests/Functional/ClientTest.php index 20efdda..4845bed 100644 --- a/tests/Functional/ClientTest.php +++ b/tests/Functional/ClientTest.php @@ -3,8 +3,10 @@ namespace Functional; use App\Entity\Client; +use App\Entity\HardwareProfile; use App\Entity\OrganizationalUnit; use App\Factory\ClientFactory; +use App\Factory\HardwareProfileFactory; use App\Factory\OrganizationalUnitFactory; use App\Factory\UserFactory; use App\Model\OrganizationalUnitTypes; @@ -108,6 +110,38 @@ class ClientTest extends AbstractTest ]); } + /** + * Verifica que el perfil de hardware de un cliente concreto puede + * modificarse directamente desde su ficha (PATCH), no solo desde el aula. + * + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + */ + public function testPatchClientHardwareProfile(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + $ou = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); + ClientFactory::createOne(['name' => 'test-client-own-hw-profile', 'organizationalUnit' => $ou]); + HardwareProfileFactory::createOne(['description' => 'test-client-own-hw-profile-description']); + + $clientIri = $this->findIriBy(Client::class, ['name' => 'test-client-own-hw-profile']); + $hardwareProfileIri = $this->findIriBy(HardwareProfile::class, ['description' => 'test-client-own-hw-profile-description']); + + $this->createClientWithCredentials()->request('PATCH', $clientIri, ['json' => [ + 'hardwareProfile' => $hardwareProfileIri, + ]]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains([ + '@id' => $clientIri, + 'hardwareProfile' => ['@id' => $hardwareProfileIri], + ]); + } + /** * @throws TransportExceptionInterface * @throws ServerExceptionInterface diff --git a/tests/Functional/HardwareProfileTest.php b/tests/Functional/HardwareProfileTest.php index c4833aa..d014775 100644 --- a/tests/Functional/HardwareProfileTest.php +++ b/tests/Functional/HardwareProfileTest.php @@ -5,9 +5,12 @@ namespace Functional; use App\Entity\Client; use App\Entity\HardwareProfile; +use App\Entity\OrganizationalUnit; use App\Factory\ClientFactory; use App\Factory\HardwareProfileFactory; +use App\Factory\OrganizationalUnitFactory; use App\Factory\UserFactory; +use App\Model\OrganizationalUnitTypes; use App\Model\UserGroupPermissions; use Symfony\Component\HttpFoundation\Response; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; @@ -58,12 +61,8 @@ class HardwareProfileTest extends AbstractTest { UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); - ClientFactory::createOne(['name' => 'test-client']); - $clientIri = $this->findIriBy(Client::class, ['name' => 'test-client']); - $this->createClientWithCredentials()->request('POST', '/hardware-profiles',['json' => [ 'description' => self::HW_PROFILE_CREATE, - 'client' => $clientIri ]]); $this->assertResponseStatusCodeSame(201); @@ -100,6 +99,40 @@ class HardwareProfileTest extends AbstractTest ]); } + /** + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + */ + public function testHardwareProfileSharedByMultipleClients(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + $ou = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); + ClientFactory::createOne(['name' => 'test-client-a', 'organizationalUnit' => $ou]); + ClientFactory::createOne(['name' => 'test-client-b', 'organizationalUnit' => $ou]); + HardwareProfileFactory::createOne(['description' => self::HW_PROFILE_CREATE]); + + $clientAIri = $this->findIriBy(Client::class, ['name' => 'test-client-a']); + $clientBIri = $this->findIriBy(Client::class, ['name' => 'test-client-b']); + $hardwareProfileIri = $this->findIriBy(HardwareProfile::class, ['description' => self::HW_PROFILE_CREATE]); + + $client = $this->createClientWithCredentials(); + + $client->request('PUT', $clientAIri, ['json' => ['name' => 'test-client-a', 'hardwareProfile' => $hardwareProfileIri]]); + $this->assertResponseIsSuccessful(); + + $client->request('PUT', $clientBIri, ['json' => ['name' => 'test-client-b', 'hardwareProfile' => $hardwareProfileIri]]); + $this->assertResponseIsSuccessful(); + + $client->request('GET', $hardwareProfileIri); + $this->assertResponseIsSuccessful(); + $data = $client->getResponse()->toArray(); + $this->assertCount(2, $data['clients']); + } + /** * @throws TransportExceptionInterface * @throws ServerExceptionInterface diff --git a/tests/Functional/OrganizationalUnitTest.php b/tests/Functional/OrganizationalUnitTest.php index c965947..f98dedc 100644 --- a/tests/Functional/OrganizationalUnitTest.php +++ b/tests/Functional/OrganizationalUnitTest.php @@ -2,8 +2,12 @@ namespace Functional; +use App\Entity\Client; +use App\Entity\HardwareProfile; use App\Entity\OrganizationalUnit; use App\Entity\UserGroup; +use App\Factory\ClientFactory; +use App\Factory\HardwareProfileFactory; use App\Factory\OrganizationalUnitFactory; use App\Factory\UserFactory; use App\Model\OrganizationalUnitTypes; @@ -179,4 +183,45 @@ class OrganizationalUnitTest extends AbstractTest static::getContainer()->get('doctrine')->getRepository(UserGroup::class)->findOneBy(['name' => self::ORGANIZATIONAL_UNIT_DELETE]) ); } + + /** + * Verifica que el perfil de hardware asignado en el aula se propaga a todos + * los clientes que tiene por debajo, y que ese perfil queda compartido. + * + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + */ + public function testPropagateHardwareProfileFromOrganizationalUnitToClients(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + $ou = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); + ClientFactory::createOne(['name' => 'test-propagate-client-a', 'organizationalUnit' => $ou]); + ClientFactory::createOne(['name' => 'test-propagate-client-b', 'organizationalUnit' => $ou]); + HardwareProfileFactory::createOne(['description' => 'test-propagate-hw-profile']); + + $ouIri = $this->findIriBy(OrganizationalUnit::class, ['id' => $ou->getId()]); + $hardwareProfileIri = $this->findIriBy(HardwareProfile::class, ['description' => 'test-propagate-hw-profile']); + $clientAIri = $this->findIriBy(Client::class, ['name' => 'test-propagate-client-a']); + $clientBIri = $this->findIriBy(Client::class, ['name' => 'test-propagate-client-b']); + + $client = $this->createClientWithCredentials(); + + $client->request('PUT', $ouIri, ['json' => [ + 'networkSettings' => ['hardwareProfile' => $hardwareProfileIri], + ]]); + $this->assertResponseIsSuccessful(); + + $client->request('POST', $ouIri . '/propagate-network-settings'); + $this->assertResponseIsSuccessful(); + + $client->request('GET', $clientAIri); + $this->assertJsonContains(['hardwareProfile' => ['@id' => $hardwareProfileIri]]); + + $client->request('GET', $clientBIri); + $this->assertJsonContains(['hardwareProfile' => ['@id' => $hardwareProfileIri]]); + } } \ No newline at end of file