diff --git a/config/api_platform/OrganizationalUnit.yaml b/config/api_platform/OrganizationalUnit.yaml index d3793b0..f465857 100644 --- a/config/api_platform/OrganizationalUnit.yaml +++ b/config/api_platform/OrganizationalUnit.yaml @@ -33,6 +33,12 @@ resources: input: false uriTemplate: /organizational-units/{uuid}/change-parent controller: App\Controller\OrganizationalUnitChangeParentAction + propagate_network_settings: + class: ApiPlatform\Metadata\Post + method: POST + input: false + uriTemplate: /organizational-units/{uuid}/propagate-network-settings + controller: App\Controller\PropagateNetworkSettingsAction properties: App\Entity\OrganizationalUnit: diff --git a/config/services/api_platform.yaml b/config/services/api_platform.yaml index 19a2e47..a53c30c 100644 --- a/config/services/api_platform.yaml +++ b/config/services/api_platform.yaml @@ -20,7 +20,7 @@ services: api_platform.filter.client.search: parent: 'api_platform.doctrine.orm.search_filter' - arguments: [ { 'id': 'exact', 'uuid': exact, 'name': 'partial', 'serialNumber': 'exact', 'template.id': 'exact', status: 'exact', organizationalUnit.id: 'exact', mac: 'exact', ip: 'exact', subnet.id: 'exact' } ] + arguments: [ { 'id': 'exact', 'uuid': exact, 'name': 'partial', 'serialNumber': 'exact', 'template.id': 'exact', status: 'exact', organizationalUnit.id: 'exact', mac: 'exact', ip: 'exact', subnet.id: 'exact', 'notes': 'partial' } ] tags: [ 'api_platform.filter' ] api_platform.filter.client.exist: diff --git a/migrations/Version20260406092549.php b/migrations/Version20260406092549.php new file mode 100644 index 0000000..b777dd0 --- /dev/null +++ b/migrations/Version20260406092549.php @@ -0,0 +1,39 @@ +addSql('ALTER TABLE software_profile DROP FOREIGN KEY FK_B70C3C9BFB84408A'); + $this->addSql('DROP INDEX IDX_B70C3C9BFB84408A ON software_profile'); + $this->addSql('ALTER TABLE software_profile ADD image_id INT DEFAULT NULL, DROP organizational_unit_id'); + $this->addSql('ALTER TABLE software_profile ADD CONSTRAINT FK_B70C3C9B3DA5256D FOREIGN KEY (image_id) REFERENCES image (id)'); + $this->addSql('CREATE INDEX IDX_B70C3C9B3DA5256D ON software_profile (image_id)'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('ALTER TABLE software_profile DROP FOREIGN KEY FK_B70C3C9B3DA5256D'); + $this->addSql('DROP INDEX IDX_B70C3C9B3DA5256D ON software_profile'); + $this->addSql('ALTER TABLE software_profile ADD organizational_unit_id INT NOT NULL, DROP image_id'); + $this->addSql('ALTER TABLE software_profile ADD CONSTRAINT FK_B70C3C9BFB84408A FOREIGN KEY (organizational_unit_id) REFERENCES organizational_unit (id)'); + $this->addSql('CREATE INDEX IDX_B70C3C9BFB84408A ON software_profile (organizational_unit_id)'); + } +} diff --git a/migrations/Version20260406092901.php b/migrations/Version20260406092901.php new file mode 100644 index 0000000..cd08306 --- /dev/null +++ b/migrations/Version20260406092901.php @@ -0,0 +1,33 @@ +addSql('ALTER TABLE command_task DROP FOREIGN KEY FK_F3D475A8FB84408A'); + $this->addSql('ALTER TABLE command_task ADD CONSTRAINT FK_F3D475A8FB84408A FOREIGN KEY (organizational_unit_id) REFERENCES organizational_unit (id) ON DELETE SET NULL'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('ALTER TABLE command_task DROP FOREIGN KEY FK_F3D475A8FB84408A'); + $this->addSql('ALTER TABLE command_task ADD CONSTRAINT FK_F3D475A8FB84408A FOREIGN KEY (organizational_unit_id) REFERENCES organizational_unit (id)'); + } +} diff --git a/migrations/Version20260413120000.php b/migrations/Version20260413120000.php new file mode 100644 index 0000000..3a888d7 --- /dev/null +++ b/migrations/Version20260413120000.php @@ -0,0 +1,26 @@ +addSql('ALTER TABLE client ADD notes LONGTEXT DEFAULT NULL'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE client DROP notes'); + } +} diff --git a/migrations/Version20260414120000.php b/migrations/Version20260414120000.php new file mode 100644 index 0000000..8708871 --- /dev/null +++ b/migrations/Version20260414120000.php @@ -0,0 +1,34 @@ +getTable('user'); + + if (!$table->hasColumn('clients_per_page')) { + $this->addSql('ALTER TABLE `user` ADD clients_per_page INT DEFAULT NULL'); + } + } + + public function down(Schema $schema): void + { + $table = $schema->getTable('user'); + + if ($table->hasColumn('clients_per_page')) { + $this->addSql('ALTER TABLE `user` DROP clients_per_page'); + } + } +} diff --git a/migrations/Version20260415120000.php b/migrations/Version20260415120000.php new file mode 100644 index 0000000..42170bb --- /dev/null +++ b/migrations/Version20260415120000.php @@ -0,0 +1,26 @@ +addSql('ALTER TABLE image_image_repository ADD size VARCHAR(255) DEFAULT NULL'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE image_image_repository DROP COLUMN size'); + } +} diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index c72352a..b48917f 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -37,7 +37,7 @@ class RunScriptAction extends AbstractOgAgentController throw new BadRequestHttpException('IP is required'); } - $data = $this->buildRequestData($client, $input->script); + $data = $this->buildRequestData($client, $input->script, $input->runAsAdmin); $response = $this->executeScript($client, $data); if (isset($response['code']) && $response['code'] === 409) { @@ -58,21 +58,14 @@ class RunScriptAction extends AbstractOgAgentController return new JsonResponse(data: $clientJobs, status: Response::HTTP_OK); } - private function buildRequestData(Client $client, string $script): array + private function buildRequestData(Client $client, string $script, bool $runAsAdmin = false): array { $scriptBase64 = base64_encode($script); - if ($this->isLinuxOrWindows($client)) { + if ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) { return [ 'script' => $scriptBase64, - 'client' => 'false' - ]; - } - - if ($this->isLinuxOrWindowsSession($client)) { - return [ - 'script' => $scriptBase64, - 'client' => 'true' + 'client' => $runAsAdmin ? 'false' : 'true' ]; } diff --git a/src/Controller/OgRepository/Image/DeletePermanentAction.php b/src/Controller/OgRepository/Image/DeletePermanentAction.php index ecc0561..d3faf2a 100644 --- a/src/Controller/OgRepository/Image/DeletePermanentAction.php +++ b/src/Controller/OgRepository/Image/DeletePermanentAction.php @@ -6,6 +6,7 @@ use App\Controller\OgRepository\AbstractOgRepositoryController; use App\Entity\Image; use App\Entity\ImageImageRepository; use App\Entity\ImageRepository; +use App\Model\ImageStatus; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\AsController; @@ -38,7 +39,13 @@ class DeletePermanentAction extends AbstractOgRepositoryController $repository = $data->getRepository(); - $content = $this->createRequest( 'DELETE', 'http://'.$repository->getIp().':8006/ogrepository/v1/images/'.$data->getImageFullsum().'?method=permanent'); + if ($data->getStatus() === ImageStatus::TRASH) { + $url = 'http://'.$repository->getIp().':8006/ogrepository/v1/trash/images/'.$data->getImageFullsum(); + } else { + $url = 'http://'.$repository->getIp().':8006/ogrepository/v1/images/'.$data->getImageFullsum().'?method=permanent'; + } + + $content = $this->createRequest('DELETE', $url); $this->logger->info('Image deleted', ['image' => $image->getName()]); diff --git a/src/Controller/OgRepository/Image/GetAction.php b/src/Controller/OgRepository/Image/GetAction.php index da01c99..85b01dd 100644 --- a/src/Controller/OgRepository/Image/GetAction.php +++ b/src/Controller/OgRepository/Image/GetAction.php @@ -36,6 +36,24 @@ class GetAction extends AbstractOgRepositoryController throw new BadRequestHttpException('An error occurred while fetching the image: ' . $content['details']); } + $datasize = $content['details']['images'][0]['datasize'] ?? null; + $size = $content['details']['images'][0]['size'] ?? null; + $changed = false; + + if ($datasize !== null && $data->getDatasize() !== (string) $datasize) { + $data->setDatasize((string) $datasize); + $changed = true; + } + + if ($size !== null && $data->getSize() !== (string) $size) { + $data->setSize((string) $size); + $changed = true; + } + + if ($changed) { + $this->entityManager->flush(); + } + return new JsonResponse(data: $content, status: Response::HTTP_OK); } } \ No newline at end of file diff --git a/src/Controller/OgRepository/Image/SyncAction.php b/src/Controller/OgRepository/Image/SyncAction.php index 0c34fd7..26c2237 100644 --- a/src/Controller/OgRepository/Image/SyncAction.php +++ b/src/Controller/OgRepository/Image/SyncAction.php @@ -28,23 +28,24 @@ class SyncAction extends AbstractOgRepositoryController { $content = $this->createRequest('GET', 'http://' . $input->getIp() . ':8006/ogrepository/v1/images'); - if (!isset($content['output']['REPOSITORY']['images'])) { + if (!isset($content['details']['REPOSITORY']['images'])) { return new JsonResponse(data: 'No images found', status: Response::HTTP_NOT_FOUND); } - $repository = $this->entityManager->getRepository(ImageImageRepository::class); + $imageImageRepositoryRepo = $this->entityManager->getRepository(ImageImageRepository::class); + $imageRepo = $this->entityManager->getRepository(Image::class); - $existingImages = $repository->findBy(['repository' => $input]); + $existingMappings = $imageImageRepositoryRepo->findBy(['repository' => $input]); - $newImageFullsums = array_column($content['output']['REPOSITORY']['images'], 'fullsum'); + $repoImageNames = array_column($content['details']['REPOSITORY']['images'], 'name'); - foreach ($content['output']['REPOSITORY']['images'] as $image) { - $imageImageRepositoryEntity = $repository->findOneBy([ - 'imageFullsum' => $image['fullsum'], - 'repository' => $input + foreach ($content['details']['REPOSITORY']['images'] as $image) { + $imageImageRepositoryEntity = $imageImageRepositoryRepo->findOneBy([ + 'name' => $image['name'], + 'repository' => $input, ]); - $imageEntity = $this->entityManager->getRepository(Image::class)->findOneBy(['name' => $image['name']]); + $imageEntity = $imageRepo->findOneBy(['name' => $image['name']]); if (!$imageEntity) { $imageEntity = new Image(); @@ -58,22 +59,22 @@ class SyncAction extends AbstractOgRepositoryController if (!$imageImageRepositoryEntity) { $imageImageRepositoryEntity = new ImageImageRepository(); + $imageImageRepositoryEntity->setImage($imageEntity); + $imageImageRepositoryEntity->setRepository($input); } $imageImageRepositoryEntity->setName($image['name']); - $imageImageRepositoryEntity->setImageFullsum($image['fullsum']); - $imageImageRepositoryEntity->setDatasize($image['datasize']); + $imageImageRepositoryEntity->setImageFullsum($image['fullsum'] ?? null); + $imageImageRepositoryEntity->setDatasize(isset($image['datasize']) ? (string) $image['datasize'] : null); + $imageImageRepositoryEntity->setSize(isset($image['size']) ? (string) $image['size'] : null); $imageImageRepositoryEntity->setStatus(ImageStatus::SUCCESS); - $imageImageRepositoryEntity->setImage($imageEntity); - $imageImageRepositoryEntity->setRepository($input); $this->entityManager->persist($imageImageRepositoryEntity); - } - foreach ($existingImages as $existingImage) { - if (!in_array($existingImage->getImageFullsum(), $newImageFullsums)) { - $this->entityManager->remove($existingImage); + foreach ($existingMappings as $existingMapping) { + if (!in_array($existingMapping->getName(), $repoImageNames, true)) { + $this->entityManager->remove($existingMapping); } } diff --git a/src/Controller/PropagateNetworkSettingsAction.php b/src/Controller/PropagateNetworkSettingsAction.php new file mode 100644 index 0000000..7d1d103 --- /dev/null +++ b/src/Controller/PropagateNetworkSettingsAction.php @@ -0,0 +1,53 @@ +getNetworkSettings(); + + if (!$networkSettings) { + return new JsonResponse( + data: 'No network settings found for this organizational unit', + status: Response::HTTP_UNPROCESSABLE_ENTITY + ); + } + + foreach ($organizationalUnit->getOrganizationalUnits() as $childUnit) { + if (!$childUnit->isExcludeParentChanges()) { + $childUnit->updateNetworkSettingsRecursively($networkSettings); + } + } + + foreach ($organizationalUnit->getClients() as $client) { + $client->setMenu($networkSettings->getMenu()); + $client->setHardwareProfile($networkSettings->getHardwareProfile()); + $client->setOgLive($networkSettings->getOgLive()); + $client->setRepository($networkSettings->getRepository()); + $client->setTemplate($networkSettings->getPxeTemplate()); + } + + $this->entityManager->flush(); + + return new JsonResponse( + data: 'Network settings propagated successfully', + status: Response::HTTP_OK + ); + } +} diff --git a/src/Dto/Input/ClientInput.php b/src/Dto/Input/ClientInput.php index dcb4c40..12173b5 100644 --- a/src/Dto/Input/ClientInput.php +++ b/src/Dto/Input/ClientInput.php @@ -117,6 +117,13 @@ final class ClientInput )] public ?string $resolution = null; + #[Groups(['client:write'])] + #[ApiProperty( + description: 'Notas sobre el cliente', + example: 'Cliente ubicado en el aula 1' + )] + public ?string $notes = null; + public function __construct(?Client $client = null) { @@ -134,6 +141,7 @@ final class ClientInput $this->position = $client->getPosition(); $this->status = $client->getStatus(); $this->resolution = $client->getResolution(); + $this->notes = $client->getNotes(); if ($client->getMenu()) { $this->menu = new MenuOutput($client->getMenu()); @@ -177,8 +185,9 @@ final class ClientInput $client->setPosition($this->position); $client->setStatus($this->status); $client->setMaintenance($this->maintenance); - $client->setResolution($this->resolution); - + $client->setResolution($this->resolution); + $client->setNotes($this->notes); + return $client; } } diff --git a/src/Dto/Input/CommandExecuteInput.php b/src/Dto/Input/CommandExecuteInput.php index 4f71b31..8d8b6f4 100644 --- a/src/Dto/Input/CommandExecuteInput.php +++ b/src/Dto/Input/CommandExecuteInput.php @@ -34,4 +34,11 @@ final class CommandExecuteInput example: false )] public bool $queue = false; + + #[Groups(['command:write'])] + #[ApiProperty( + description: 'Si ejecutar el script en modo administrador', + example: false + )] + public bool $runAsAdmin = false; } \ No newline at end of file diff --git a/src/Dto/Input/SoftwareProfileInput.php b/src/Dto/Input/SoftwareProfileInput.php index 87ee072..79331fe 100644 --- a/src/Dto/Input/SoftwareProfileInput.php +++ b/src/Dto/Input/SoftwareProfileInput.php @@ -3,8 +3,8 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; +use App\Dto\Output\ImageOutput; use App\Dto\Output\OperativeSystemOutput; -use App\Dto\Output\OrganizationalUnitOutput; use App\Entity\SoftwareProfile; use Symfony\Component\Serializer\Annotation\Groups; @@ -19,8 +19,8 @@ final class SoftwareProfileInput public ?string $comments = null; #[Groups(['software-profile:write'])] - #[ApiProperty(description: 'The organizational unit of the software profile')] - public ?OrganizationalUnitOutput $organizationalUnit = null; + #[ApiProperty(description: 'The image of the software profile')] + public ?ImageOutput $image = null; #[Groups(['software-profile:write'])] #[ApiProperty(description: 'The operative system of the software profile')] @@ -35,8 +35,8 @@ final class SoftwareProfileInput $this->description = $softwareProfile->getDescription(); $this->comments = $softwareProfile->getComments(); - if($softwareProfile->getOrganizationalUnit()) { - $this->organizationalUnit = new OrganizationalUnitOutput($softwareProfile->getOrganizationalUnit()); + if ($softwareProfile->getImage()) { + $this->image = new ImageOutput($softwareProfile->getImage()); } if($softwareProfile->getOperativeSystem()) { @@ -52,9 +52,7 @@ final class SoftwareProfileInput $softwareProfile->setDescription($this->description); $softwareProfile->setComments($this->comments); - if ($this->organizationalUnit) { - $softwareProfile->setOrganizationalUnit($this->organizationalUnit->getEntity()); - } + $softwareProfile->setImage($this->image?->getEntity()); if ($this->operativeSystem) { $softwareProfile->setOperativeSystem($this->operativeSystem->getEntity()); diff --git a/src/Dto/Input/UserInput.php b/src/Dto/Input/UserInput.php index c524e2b..bb0e1d8 100644 --- a/src/Dto/Input/UserInput.php +++ b/src/Dto/Input/UserInput.php @@ -49,6 +49,13 @@ final class UserInput )] public ?string $groupsView = null; + #[Groups('user:write')] + #[ApiProperty( + description: 'Número de clientes por página en el listado de clientes', + example: 20 + )] + public ?int $clientsPerPage = null; + #[Assert\NotNull] #[Groups('user:write')] #[ApiProperty( @@ -105,6 +112,7 @@ final class UserInput $this->username = $user->getUsername(); $this->enabled= $user->isEnabled(); $this->groupsView = $user->getGroupsView(); + $this->clientsPerPage = $user->getClientsPerPage(); if ($user->getUserGroups()) { foreach ($user->getUserGroups() as $userGroup) { @@ -128,6 +136,7 @@ final class UserInput $user->setUsername($this->username); $user->setEnabled($this->enabled); $user->setGroupsView($this->groupsView); + $user->setClientsPerPage($this->clientsPerPage); foreach ($this->userGroups as $userGroup) { $userGroupsToAdd[] = $userGroup->getEntity(); diff --git a/src/Dto/Output/ClientOutput.php b/src/Dto/Output/ClientOutput.php index bb7dc26..8be920c 100644 --- a/src/Dto/Output/ClientOutput.php +++ b/src/Dto/Output/ClientOutput.php @@ -167,6 +167,13 @@ final class ClientOutput extends AbstractOutput )] public ?string $resolution = null; + #[Groups(['client:read'])] + #[ApiProperty( + description: 'Notas sobre el cliente', + example: 'Cliente ubicado en el aula 1' + )] + public ?string $notes = null; + public function __construct(Client $client) { parent::__construct($client); @@ -216,6 +223,7 @@ final class ClientOutput extends AbstractOutput $this->maintenance = $client->isMaintenance(); $this->pxeSync = $client->isPxeSync(); $this->resolution = $client->getResolution(); + $this->notes = $client->getNotes(); } public function convertMaskToCIDR($mask): int diff --git a/src/Dto/Output/HardwareProfileOutput.php b/src/Dto/Output/HardwareProfileOutput.php index 93a3b55..980d2e4 100644 --- a/src/Dto/Output/HardwareProfileOutput.php +++ b/src/Dto/Output/HardwareProfileOutput.php @@ -53,13 +53,13 @@ final class HardwareProfileOutput extends AbstractOutput )] public ?string $createdBy = null; - public function __construct(HardwareProfile $hardwareProfile) + public function __construct(HardwareProfile $hardwareProfile, bool $includeClient = true) { parent::__construct($hardwareProfile); $this->description = $hardwareProfile->getDescription(); $this->comments = $hardwareProfile->getComments(); - if($hardwareProfile->getClient()) { + if($includeClient && $hardwareProfile->getClient()) { $this->client = new ClientOutput($hardwareProfile->getClient()); } diff --git a/src/Dto/Output/ImageImageRepositoryOutput.php b/src/Dto/Output/ImageImageRepositoryOutput.php index d4cf4e9..6cfe2d8 100644 --- a/src/Dto/Output/ImageImageRepositoryOutput.php +++ b/src/Dto/Output/ImageImageRepositoryOutput.php @@ -54,11 +54,18 @@ class ImageImageRepositoryOutput extends AbstractOutput #[Groups(['image-image-repository:read', 'image:read'])] #[ApiProperty( - description: 'El tamaño de los datos en bytes', - example: '10737418240' + description: 'El tamaño de los datos sin comprimir en bytes', + example: '12902400000' )] public ?string $datasize = null; + #[Groups(['image-image-repository:read', 'image:read'])] + #[ApiProperty( + description: 'El tamaño de la imagen comprimida en bytes', + example: '3795024506' + )] + public ?string $size = null; + #[Groups(['image-image-repository:read', 'image:read'])] #[ApiProperty( description: 'La descripción de la imagen', @@ -107,6 +114,7 @@ class ImageImageRepositoryOutput extends AbstractOutput $this->status = $imageImageRepository->getStatus(); $this->imageFullsum = $imageImageRepository->getImageFullsum(); $this->datasize = $imageImageRepository->getDatasize(); + $this->size = $imageImageRepository->getSize(); $this->description = $imageImageRepository->getDescription(); $this->createdAt = $imageImageRepository->getCreatedAt(); $this->createdBy = $imageImageRepository->getCreatedBy(); diff --git a/src/Dto/Output/ImageOutput.php b/src/Dto/Output/ImageOutput.php index 9e857fc..4ee6c2c 100644 --- a/src/Dto/Output/ImageOutput.php +++ b/src/Dto/Output/ImageOutput.php @@ -91,7 +91,7 @@ final class ImageOutput extends AbstractOutput parent::__construct($image); $this->name = $image->getName(); - $this->softwareProfile = $image->getSoftwareProfile() ? new SoftwareProfileOutput($image->getSoftwareProfile()) : null; + $this->softwareProfile = $image->getSoftwareProfile() ? new SoftwareProfileOutput($image->getSoftwareProfile(), false) : null; $this->imageRepositories = $image->getImageImageRepositories()->map( fn(ImageImageRepository $image) => new ImageImageRepositoryOutput($image) diff --git a/src/Dto/Output/NetworkSettingsOutput.php b/src/Dto/Output/NetworkSettingsOutput.php index d433c8f..e797034 100644 --- a/src/Dto/Output/NetworkSettingsOutput.php +++ b/src/Dto/Output/NetworkSettingsOutput.php @@ -189,7 +189,7 @@ final class NetworkSettingsOutput extends AbstractOutput } if ($networkSettings->getHardwareProfile()) { - $this->hardwareProfile = new HardwareProfileOutput($networkSettings->getHardwareProfile()); + $this->hardwareProfile = new HardwareProfileOutput($networkSettings->getHardwareProfile(), false); } if ($networkSettings->getOgLive()) { diff --git a/src/Dto/Output/SoftwareProfileOutput.php b/src/Dto/Output/SoftwareProfileOutput.php index b3945bf..715b935 100644 --- a/src/Dto/Output/SoftwareProfileOutput.php +++ b/src/Dto/Output/SoftwareProfileOutput.php @@ -8,6 +8,7 @@ use App\Entity\Software; use App\Entity\SoftwareProfile; use Symfony\Component\Serializer\Annotation\Groups; + #[Get(shortName: 'SoftwareProfile')] final class SoftwareProfileOutput extends AbstractOutput { @@ -27,10 +28,10 @@ final class SoftwareProfileOutput extends AbstractOutput #[Groups(['software-profile:read'])] #[ApiProperty( - description: 'La unidad organizativa asociada', + description: 'La imagen asociada al perfil de software', example: null )] - public ?OrganizationalUnitOutput $organizationalUnit = null; + public ?ImageOutput $image = null; #[Groups(['software-profile:read'])] #[ApiProperty( @@ -60,15 +61,15 @@ final class SoftwareProfileOutput extends AbstractOutput )] public ?string $createdBy = null; - public function __construct(SoftwareProfile $softwareProfile) + public function __construct(SoftwareProfile $softwareProfile, bool $includeImage = true) { parent::__construct($softwareProfile); $this->description = $softwareProfile->getDescription(); $this->comments = $softwareProfile->getComments(); - if($softwareProfile->getOrganizationalUnit()) { - $this->organizationalUnit = new OrganizationalUnitOutput($softwareProfile->getOrganizationalUnit()); + if ($includeImage && $softwareProfile->getImage()) { + $this->image = new ImageOutput($softwareProfile->getImage()); } if ($softwareProfile->getOperativeSystem()) { diff --git a/src/Dto/Output/UserOutput.php b/src/Dto/Output/UserOutput.php index c67c8fc..bbdbb17 100644 --- a/src/Dto/Output/UserOutput.php +++ b/src/Dto/Output/UserOutput.php @@ -54,6 +54,13 @@ final class UserOutput extends AbstractOutput )] public ?string $groupsView = 'card'; + #[Groups(['user:read'])] + #[ApiProperty( + description: 'Número de clientes por página en el listado de clientes', + example: 20 + )] + public ?int $clientsPerPage = null; + #[Groups(['user:read'])] #[ApiProperty( description: 'Fecha de creación del usuario', @@ -76,6 +83,7 @@ final class UserOutput extends AbstractOutput $this->roles = $user->getRoles(); $this->enabled = $user->isEnabled(); $this->groupsView = $user->getGroupsView(); + $this->clientsPerPage = $user->getClientsPerPage(); $this->userGroups = $user->getUserGroups()->map( fn(UserGroup $userGroup) => new UserGroupOutput($userGroup) diff --git a/src/Entity/Client.php b/src/Entity/Client.php index 51d5064..79d9eaf 100644 --- a/src/Entity/Client.php +++ b/src/Entity/Client.php @@ -97,6 +97,9 @@ class Client extends AbstractEntity #[ORM\Column(length: 255, nullable: true)] private ?string $resolution = null; + #[ORM\Column(type: 'text', nullable: true)] + private ?string $notes = null; + public function __construct() { parent::__construct(); @@ -385,4 +388,16 @@ class Client extends AbstractEntity $this->resolution = $resolution; return $this; } + + public function getNotes(): ?string + { + return $this->notes; + } + + public function setNotes(?string $notes): static + { + $this->notes = $notes; + + return $this; + } } diff --git a/src/Entity/CommandTask.php b/src/Entity/CommandTask.php index 8bb719c..4caf661 100644 --- a/src/Entity/CommandTask.php +++ b/src/Entity/CommandTask.php @@ -26,6 +26,7 @@ class CommandTask extends AbstractEntity private ?array $parameters = null; #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')] private ?OrganizationalUnit $organizationalUnit = null; /** diff --git a/src/Entity/ImageImageRepository.php b/src/Entity/ImageImageRepository.php index 69c9116..fc9fd55 100644 --- a/src/Entity/ImageImageRepository.php +++ b/src/Entity/ImageImageRepository.php @@ -32,6 +32,9 @@ class ImageImageRepository extends AbstractEntity #[ORM\Column(length: 255, nullable: true)] private ?string $datasize = null; + #[ORM\Column(length: 255, nullable: true)] + private ?string $size = null; + #[ORM\Column(nullable: true)] private ?int $version = null; @@ -125,6 +128,18 @@ class ImageImageRepository extends AbstractEntity return $this; } + public function getSize(): ?string + { + return $this->size; + } + + public function setSize(?string $size): static + { + $this->size = $size; + + return $this; + } + public function getVersion(): ?int { return $this->version; diff --git a/src/Entity/OrganizationalUnit.php b/src/Entity/OrganizationalUnit.php index 75b5849..71f05ba 100644 --- a/src/Entity/OrganizationalUnit.php +++ b/src/Entity/OrganizationalUnit.php @@ -78,12 +78,6 @@ class OrganizationalUnit extends AbstractEntity #[ORM\Column(nullable: true)] private ?int $capacity = null; - /** - * @var Collection - */ - #[ORM\OneToMany(mappedBy: 'organizationalUnit', targetEntity: SoftwareProfile::class)] - private Collection $softwareProfiles; - #[ORM\ManyToOne(inversedBy: 'organizationalUnits')] private ?Subnet $subnet = null; @@ -106,7 +100,7 @@ class OrganizationalUnit extends AbstractEntity $this->organizationalUnits = new ArrayCollection(); $this->users = new ArrayCollection(); $this->clients = new ArrayCollection(); - $this->softwareProfiles = new ArrayCollection(); + } public function getDescription(): ?string @@ -347,41 +341,16 @@ class OrganizationalUnit extends AbstractEntity foreach ($this->getClients() as $client) { $client->setMenu($networkSettings->getMenu()); $client->setHardwareProfile($networkSettings->getHardwareProfile()); + $client->setOgLive($networkSettings->getOgLive()); + $client->setRepository($networkSettings->getRepository()); + $client->setTemplate($networkSettings->getPxeTemplate()); } foreach ($this->getOrganizationalUnits() as $childUnit) { - $childUnit->updateNetworkSettingsRecursively($networkSettings); - } - } - - /** - * @return Collection - */ - public function getSoftwareProfiles(): Collection - { - return $this->softwareProfiles; - } - - public function addSoftwareProfile(SoftwareProfile $softwareProfile): static - { - if (!$this->softwareProfiles->contains($softwareProfile)) { - $this->softwareProfiles->add($softwareProfile); - $softwareProfile->setOrganizationalUnit($this); - } - - return $this; - } - - public function removeSoftwareProfile(SoftwareProfile $softwareProfile): static - { - if ($this->softwareProfiles->removeElement($softwareProfile)) { - // set the owning side to null (unless already changed) - if ($softwareProfile->getOrganizationalUnit() === $this) { - $softwareProfile->setOrganizationalUnit(null); + if (!$childUnit->isExcludeParentChanges()) { + $childUnit->updateNetworkSettingsRecursively($networkSettings); } } - - return $this; } public function getSubnet(): ?Subnet diff --git a/src/Entity/SoftwareProfile.php b/src/Entity/SoftwareProfile.php index 38eac0f..86971fb 100644 --- a/src/Entity/SoftwareProfile.php +++ b/src/Entity/SoftwareProfile.php @@ -16,9 +16,9 @@ class SoftwareProfile extends AbstractEntity #[ORM\Column(length: 255, nullable: true)] private ?string $comments = null; - #[ORM\ManyToOne(inversedBy: 'softwareProfiles')] - #[ORM\JoinColumn(nullable: false)] - private ?OrganizationalUnit $organizationalUnit = null; + #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: true)] + private ?Image $image = null; /** * @var Collection @@ -66,14 +66,14 @@ class SoftwareProfile extends AbstractEntity return $this; } - public function getOrganizationalUnit(): ?OrganizationalUnit + public function getImage(): ?Image { - return $this->organizationalUnit; + return $this->image; } - public function setOrganizationalUnit(?OrganizationalUnit $organizationalUnit): static + public function setImage(?Image $image): static { - $this->organizationalUnit = $organizationalUnit; + $this->image = $image; return $this; } diff --git a/src/Entity/User.php b/src/Entity/User.php index 809ea75..cbbe295 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -54,6 +54,9 @@ class User extends AbstractEntity implements UserInterface, PasswordAuthenticate #[ORM\Column(length: 255, nullable: true)] private ?string $groupsView = null; + #[ORM\Column(nullable: true)] + private ?int $clientsPerPage = null; + public function __construct() { @@ -260,4 +263,16 @@ class User extends AbstractEntity implements UserInterface, PasswordAuthenticate return $this; } + + public function getClientsPerPage(): ?int + { + return $this->clientsPerPage; + } + + public function setClientsPerPage(?int $clientsPerPage): static + { + $this->clientsPerPage = $clientsPerPage; + + return $this; + } } diff --git a/src/EventSubscriber/OrganizationalUnitSubscriber.php b/src/EventSubscriber/OrganizationalUnitSubscriber.php index 30591b1..60022ed 100644 --- a/src/EventSubscriber/OrganizationalUnitSubscriber.php +++ b/src/EventSubscriber/OrganizationalUnitSubscriber.php @@ -6,7 +6,6 @@ use ApiPlatform\Symfony\EventListener\EventPriorities; use App\Controller\OgBoot\PxeBootFile\PostAction; use App\Dto\Output\OrganizationalUnitOutput; use App\Entity\Client; -use App\Entity\NetworkSettings; use App\Entity\OrganizationalUnit; use App\Model\OrganizationalUnitTypes; use Doctrine\ORM\EntityManagerInterface; @@ -55,99 +54,12 @@ final readonly class OrganizationalUnitSubscriber implements EventSubscriberInte /** @var OrganizationalUnit $organizationalUnitEntity */ $organizationalUnitEntity = $organizationalUnitOutput->getEntity(); - if ($organizationalUnitEntity->getNetworkSettings() === null || $organizationalUnitEntity->isExcludeParentChanges()) { - return; - } - - $newNetworkSettings = $this->cloneNetworkSettings($organizationalUnitEntity->getNetworkSettings()); - - $this->updateChildrenNetworkSettings($organizationalUnitEntity, $newNetworkSettings); - if ($organizationalUnitEntity->getType() === OrganizationalUnitTypes::CLASSROOM) { $this->syncOgBoot($organizationalUnitEntity); } } - private function updateChildrenNetworkSettings(OrganizationalUnit $parentUnit, NetworkSettings $networkSettings): void - { - /** @var OrganizationalUnit $childUnit */ - foreach ($parentUnit->getOrganizationalUnits() as $childUnit) { - if ($childUnit->isExcludeParentChanges()) { - $childUnit->setNetworkSettings(null); - } else{ - - $childUnit->setNetworkSettings($networkSettings); - - foreach ($childUnit->getClients() as $client) { - $client->setOgLive($networkSettings->getOgLive()); - $client->setMenu($networkSettings->getMenu()); - $client->setRepository($networkSettings->getRepository()); - $client->setTemplate($networkSettings->getPxeTemplate()); - $this->entityManager->persist($client); - } - } - $this->entityManager->persist($childUnit); - $this->entityManager->flush(); - - $this->updateChildrenNetworkSettings($childUnit, $networkSettings); - } - } - - private function cloneNetworkSettings(NetworkSettings $original): NetworkSettings - { - $cloned = new NetworkSettings(); - - $cloned->setNextServer($original->getNextServer()); - $cloned->setBootFileName($original->getBootFileName()); - $cloned->setProxy($original->getProxy()); - $cloned->setDns($original->getDns()); - $cloned->setNetmask($original->getNetmask()); - $cloned->setRouter($original->getRouter()); - $cloned->setP2pTime($original->getP2pTime()); - $cloned->setP2pMode($original->getP2pMode()); - $cloned->setMcastMode($original->getMcastMode()); - $cloned->setMcastIp($original->getMcastIp()); - $cloned->setMcastPort($original->getMcastPort()); - $cloned->setMcastSpeed($original->getMcastSpeed()); - $cloned->setMenu($original->getMenu()); - $cloned->setRepository($original->getRepository()); - $cloned->setOgLive($original->getOgLive()); - $cloned->setPxeTemplate($original->getPxeTemplate()); - $cloned->setNetiface($original->getNetiface()); - - return $cloned; - } - - private function buildNetworkSettings($organizationalUnitEntity): NetworkSettings - { - if ($organizationalUnitEntity->getNetworkSettings() === null) { - $newNetworkSettings = new NetworkSettings(); - } else { - $newNetworkSettings = $organizationalUnitEntity->getNetworkSettings(); - } - - $newNetworkSettings->setNextServer($organizationalUnitEntity->getNetworkSettings()->getNextServer()); - $newNetworkSettings->setBootFileName($organizationalUnitEntity->getNetworkSettings()->getBootFileName()); - $newNetworkSettings->setProxy($organizationalUnitEntity->getNetworkSettings()->getProxy()); - $newNetworkSettings->setDns($organizationalUnitEntity->getNetworkSettings()->getDns()); - $newNetworkSettings->setNetmask($organizationalUnitEntity->getNetworkSettings()->getNetmask()); - $newNetworkSettings->setRouter($organizationalUnitEntity->getNetworkSettings()->getRouter()); - $newNetworkSettings->setP2pTime($organizationalUnitEntity->getNetworkSettings()->getP2pTime()); - $newNetworkSettings->setP2pMode($organizationalUnitEntity->getNetworkSettings()->getP2pMode()); - $newNetworkSettings->setMcastMode($organizationalUnitEntity->getNetworkSettings()->getMcastMode()); - $newNetworkSettings->setMcastIp($organizationalUnitEntity->getNetworkSettings()->getMcastIp()); - $newNetworkSettings->setMcastPort($organizationalUnitEntity->getNetworkSettings()->getMcastPort()); - $newNetworkSettings->setMcastSpeed($organizationalUnitEntity->getNetworkSettings()->getMcastSpeed()); - $newNetworkSettings->setMenu($organizationalUnitEntity->getNetworkSettings()->getMenu()); - $newNetworkSettings->setRepository($organizationalUnitEntity->getNetworkSettings()->getRepository()); - $newNetworkSettings->setOgLive($organizationalUnitEntity->getNetworkSettings()->getOgLive()); - $newNetworkSettings->setPxeTemplate($organizationalUnitEntity->getNetworkSettings()->getPxeTemplate()); - $newNetworkSettings->setNetiface($organizationalUnitEntity->getNetworkSettings()->getNetiface()); - - return $newNetworkSettings; - } - /** * @throws TransportExceptionInterface * @throws ServerExceptionInterface diff --git a/src/Factory/SoftwareProfileFactory.php b/src/Factory/SoftwareProfileFactory.php index d3d370c..2f368a8 100644 --- a/src/Factory/SoftwareProfileFactory.php +++ b/src/Factory/SoftwareProfileFactory.php @@ -3,7 +3,7 @@ namespace App\Factory; use App\Entity\SoftwareProfile; -use App\Model\OrganizationalUnitTypes; +use App\Factory\ImageFactory; use App\Repository\SoftwareProfileRepository; use Zenstruck\Foundry\ModelFactory; use Zenstruck\Foundry\Persistence\PersistentProxyObjectFactory; @@ -37,7 +37,7 @@ final class SoftwareProfileFactory extends ModelFactory 'description' => self::faker()->text(255), 'updatedAt' => self::faker()->dateTime(), 'operativeSystem' => OperativeSystemFactory::createOne()->_save(), - 'organizationalUnit' => OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT])->_save(), + 'image' => ImageFactory::createOne()->_save(), ]; } diff --git a/src/Lexik/JWTCreatedListener.php b/src/Lexik/JWTCreatedListener.php index ae37549..d6f001b 100644 --- a/src/Lexik/JWTCreatedListener.php +++ b/src/Lexik/JWTCreatedListener.php @@ -24,6 +24,7 @@ class JWTCreatedListener $payload['uuid'] = $user->getUuid(); $payload['roles'] = $user->getRoles(); $payload['groupsView'] = $user->getGroupsView(); + $payload['clientsPerPage'] = $user->getClientsPerPage(); $event->setData($payload); } diff --git a/src/Repository/ClientRepository.php b/src/Repository/ClientRepository.php index c6f77f2..392b257 100644 --- a/src/Repository/ClientRepository.php +++ b/src/Repository/ClientRepository.php @@ -67,11 +67,12 @@ class ClientRepository extends AbstractRepository $qb->andWhere("c.name LIKE :name") ->setParameter('name', "%$value%"); } elseif ($key === 'query') { - // Búsqueda en múltiples campos (name, ip, mac) + // Búsqueda en múltiples campos (name, ip, mac, notes) $qb->andWhere($qb->expr()->orX( $qb->expr()->like('c.name', ':searchQuery'), $qb->expr()->like('c.ip', ':searchQuery'), - $qb->expr()->like('c.mac', ':searchQuery') + $qb->expr()->like('c.mac', ':searchQuery'), + $qb->expr()->like('c.notes', ':searchQuery') ))->setParameter('searchQuery', "%$value%"); } else { // Búsqueda exacta para otros campos @@ -149,7 +150,8 @@ class ClientRepository extends AbstractRepository $qb->andWhere($qb->expr()->orX( $qb->expr()->like('c.name', ':searchQuery'), $qb->expr()->like('c.ip', ':searchQuery'), - $qb->expr()->like('c.mac', ':searchQuery') + $qb->expr()->like('c.mac', ':searchQuery'), + $qb->expr()->like('c.notes', ':searchQuery') ))->setParameter('searchQuery', "%$value%"); } else { $qb->andWhere("c.$key = :$key")->setParameter($key, $value); diff --git a/src/Service/UDS/UDSClient.php b/src/Service/UDS/UDSClient.php index 5842986..f3a1c1b 100644 --- a/src/Service/UDS/UDSClient.php +++ b/src/Service/UDS/UDSClient.php @@ -5,10 +5,11 @@ namespace App\Service\UDS; use AllowDynamicProperties; use App\Entity\OrganizationalUnit; use Doctrine\ORM\EntityManagerInterface; -use Symfony\Component\DependencyInjection\Attribute\Autowire; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpClient\Exception\TransportException; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; @@ -22,19 +23,33 @@ class UDSClient private string $scrambler; + private string $udsAPIurl; + + private string $udsAuthLogin; + + private string $udsAuthUsername; + + private string $udsAuthPassword; + public function __construct( private HttpClientInterface $httpClient, private readonly EntityManagerInterface $entityManager, - #[Autowire(env: 'REMOTE_PC_URL')] - private readonly string $udsAPIurl, - #[Autowire(env: 'REMOTE_PC_AUTH_LOGIN')] - private readonly string $udsAuthLogin, - #[Autowire(env: 'REMOTE_PC_AUTH_USERNAME')] - private readonly string $udsAuthUsername, - #[Autowire(env: 'REMOTE_PC_AUTH_PASSWORD')] - private readonly string $udsAuthPassword, + private readonly LoggerInterface $logger, + private readonly KernelInterface $kernel, ) { + $envFile = $this->kernel->getProjectDir() . DIRECTORY_SEPARATOR . 'env.json'; + if (!is_file($envFile)) { + throw new \RuntimeException('Configuration file not found: ' . $envFile); + } + + $config = json_decode(file_get_contents($envFile), true); + $vars = $config['vars'] ?? []; + + $this->udsAPIurl = $vars['UDS_URL'] ?? throw new \RuntimeException('UDS_URL not set in env.json'); + $this->udsAuthLogin = $vars['UDS_AUTH_LOGIN'] ?? throw new \RuntimeException('UDS_AUTH_LOGIN not set in env.json'); + $this->udsAuthUsername = $vars['UDS_AUTH_USERNAME'] ?? throw new \RuntimeException('UDS_AUTH_USERNAME not set in env.json'); + $this->udsAuthPassword = $vars['UDS_AUTH_PASSWORD'] ?? throw new \RuntimeException('UDS_AUTH_PASSWORD not set in env.json'); } /** @@ -89,14 +104,35 @@ class UDSClient ] ]); + $statusCode = $response->getStatusCode(); $data = json_decode($response->getContent(false), true); + if ($statusCode !== 200 || empty($data['token'])) { + $this->logger->error('UDS login failed', [ + 'status_code' => $statusCode, + 'response' => $data, + 'uds_url' => $this->udsAPIurl, + 'uds_auth' => $this->udsAuthLogin, + 'uds_username' => $this->udsAuthUsername, + ]); + throw new \RuntimeException('UDS login failed with status ' . $statusCode); + } + $this->token = $data['token']; $this->scrambler = $data['scrambler']; } catch (TransportExceptionInterface $e) { - throw new TransportException('Error while logging in to UDS'); + $this->logger->error('UDS login transport error', [ + 'message' => $e->getMessage(), + 'uds_url' => $this->udsAPIurl, + ]); + throw new TransportException('Error while logging in to UDS: ' . $e->getMessage(), 0, $e); } catch (ClientExceptionInterface|ServerExceptionInterface|RedirectionExceptionInterface $e) { + $this->logger->error('UDS login HTTP error', [ + 'message' => $e->getMessage(), + 'uds_url' => $this->udsAPIurl, + ]); + throw new \RuntimeException('UDS login HTTP error: ' . $e->getMessage(), 0, $e); } }