Improved setup and new data inicialization.
CI / Docker Lint (push) Successful in 30s

This commit is contained in:
2024-10-09 20:50:23 +02:00
parent e93a5ff3a9
commit d9489f2558
21 changed files with 2814 additions and 67 deletions
+120
View File
@@ -0,0 +1,120 @@
<?php
namespace App\Controller;
use App\DTO\AppSetupConfig;
use App\DTO\ExampleDataConfig;
use App\Entity\ConfigVariable;
use App\Form\AppSetupFormType;
use App\Form\ExampleDataFormType;
use App\Repository\RoomCategoryRepository;
use App\Service\AppSetupService;
use App\Service\ExampleDataService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class AppSetupController extends AbstractController
{
#[Route(path: '/setup', name: 'app_setup_setup')]
public function addAdmin(
AppSetupService $setupService,
Request $request,
EntityManagerInterface $entityManager
): Response {
$configRepo = $entityManager->getRepository(ConfigVariable::class);
$setupStatus = $configRepo->findBy(["key" => "SETUP_STATUS"]);
if ($setupStatus != null && $setupStatus[0] != null && $setupStatus[0]->getValue() == 1) {
return $this->GoToResultPage(
isError: false,
message: "SomniaRooms already setup.",
linkRoute: "admin",
linkLabel: "Go to admin panel"
);
}
$config = new AppSetupConfig();
$form = $this->createForm(AppSetupFormType::class, $config);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$rs = $setupService->InitialSetup($config);
if (!$rs) {
return $this->GoToResultPage(
isError: false,
message: "An error occurred during setup proccess, try again."
);
}
if ($config->getGenExampleData()) {
return $this->redirectToRoute("app_setup_gendata");
}
return $this->GoToResultPage(
isError: false,
message: "SomniaRooms is setup! Go to admin panel to start!",
linkRoute: "admin",
linkLabel: "Go to admin panel"
);
}
return $this->render('app_setup/setup.html.twig', [
'form' => $form,
]);
}
#[Route('/debug/exampleData', name: 'app_setup_gendata')]
public function generateData(
Request $request,
ExampleDataService $dataService,
RoomCategoryRepository $roomCategoryRepository
): Response {
$config = new ExampleDataConfig();
$form = $this->createForm(ExampleDataFormType::class, $config);
$isFormInvalid = $form->isSubmitted() && !$form->isValid();
//Check for RoomCategories on db.
$roomCategoryCount = $roomCategoryRepository->count();
$hasRoomCategories = $roomCategoryCount > 0;
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$rs = $dataService->AddExampleData($config);
$isOk = $rs == "OK";
$msg = $isOk ? "Example data generated! Go to admin panel to start!" : $rs;
return $this->GoToResultPage(
isError: !$isOk,
message: $msg,
linkRoute: $isOk ? "admin" : "",
linkLabel: $isOk ? "Go to admin panel" : ""
);
}
return $this->render('app_setup/exampleData.html.twig', [
'form' => $form,
'isFormInvalid' => $isFormInvalid,
'hasRoomCategories' => $hasRoomCategories
]);
}
private function GoToResultPage(bool $isError, string $message, string $linkRoute = null, string $linkLabel = null): Response
{
return $this->render('app_setup/result.html.twig', [
'isError' => $isError,
'message' => $message,
'linkLabel' => $linkLabel,
'linkRoute' => $linkRoute
]);
}
}
+1 -55
View File
@@ -2,13 +2,8 @@
namespace App\Controller;
use App\Entity\User;
use App\Entity\ConfigVariable;
use App\Enum\ConfigSectionType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
@@ -34,53 +29,4 @@ class SecurityController extends AbstractController
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route(path: '/setup', name: 'app_security_addAdmin')]
public function addAdmin(UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager): Response
{
$configRepo = $entityManager->getRepository(ConfigVariable::class);
$setupStatus = $configRepo->findBy(["key" => "SETUP_STATUS"]);
if($setupStatus != null && $setupStatus[0] != null && $setupStatus[0]->getValue() != 1) {
return new Response("Setup was already done");
}
$entityManager->beginTransaction();
try {
//Create system variables.
$var_setup = new ConfigVariable();
$var_setup->setKey("SETUP_STATUS");
$var_setup->setValue("1");
$var_setup->setSection(ConfigSectionType::Internal);
$entityManager->persist($var_setup);
//Create user Admin.
$user = new User();
$user->setUsername("admin");
$user->setRoles(["ROLE_USER", "ROLE_ADMIN", "ROLE_SUPERADMIN"]);
$plaintextPassword = "admin";
// hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $passwordHasher->hashPassword(
$user,
$plaintextPassword
);
$user->setPassword($hashedPassword);
$entityManager->persist($user);
$entityManager->flush();
$entityManager->commit();
} catch (\Throwable $th) {
$entityManager->rollback();
throw $th;
}
return new Response("Setup completed :)");
}
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\DTO;
class AppSetupConfig
{
protected string $adminUser;
protected string $adminPass;
protected bool $genExampleData;
public function getAdminUser(): string
{
return $this->adminUser;
}
public function setAdminUser(string $adminUser): void
{
$this->adminUser = $adminUser;
}
public function getAdminPass(): string
{
return $this->adminPass;
}
public function setAdminPass(string $adminPass): void
{
$this->adminPass = $adminPass;
}
public function getGenExampleData(): bool
{
return $this->genExampleData;
}
public function setGenExampleData(bool $genExampleData): void
{
$this->genExampleData = $genExampleData;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace App\DTO;
use DateTime;
class ExampleDataConfig
{
protected DateTime $startDate;
protected DateTime $endDate;
protected bool $genRoomCategories;
protected bool $genFaretables;
protected bool $genAvailability;
protected string $genMode;
public const GENMODE_EXAMPLE = "EXAMPLE";
public const GENMODE_RANDOM = "RANDOM";
public function getStartDate(): DateTime
{
return $this->startDate;
}
public function setStartDate(DateTime $startDate): void
{
$this->startDate = $startDate;
}
public function getEndDate(): DateTime
{
return $this->endDate;
}
public function setEndDate(DateTime $endDate): void
{
$this->endDate = $endDate;
}
public function getGenRoomCategories(): bool
{
return $this->genRoomCategories;
}
public function setGenRoomCategories(bool $genRoomCategories): void
{
$this->genRoomCategories = $genRoomCategories;
}
public function getGenFaretables(): bool
{
return $this->genFaretables;
}
public function setGenFaretables(bool $genFaretables): void
{
$this->genFaretables = $genFaretables;
}
public function getGenAvailability(): bool
{
return $this->genAvailability;
}
public function setGenAvailability(bool $genAvailability): void
{
$this->genAvailability = $genAvailability;
}
public function getGenMode(): string
{
return $this->genMode;
}
public function setGenMode(string $genMode): void
{
$this->genMode = $genMode;
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Form;
use App\DTO\AppSetupConfig;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AppSetupFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('adminUser', TextType::class);
$builder->add('adminPass', PasswordType::class);
$builder->add('genExampleData', CheckboxType::class, [
'required' => false,
]);
$builder->add('setup', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => AppSetupConfig::class,
]);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Form;
use App\DTO\ExampleDataConfig;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ExampleDataFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('startDate', DateType::class);
$builder->add('endDate', DateType::class);
$builder->add('genRoomCategories', CheckboxType::class, [
'required' => false,
]);
$builder->add('genFaretables', CheckboxType::class, [
'required' => false,
]);
$builder->add('genAvailability', CheckboxType::class, [
'required' => false,
]);
$builder->add('genMode', ChoiceType::class, [
'choices' => [
'Random' => ExampleDataConfig::GENMODE_RANDOM,
'Example' => ExampleDataConfig::GENMODE_EXAMPLE
]
]);
$builder->add('Generate', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ExampleDataConfig::class,
]);
}
}
+15 -7
View File
@@ -4,6 +4,7 @@ namespace App\Repository;
use App\Entity\RoomAvailability;
use App\Entity\RoomCategory;
use DateInterval;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
@@ -129,14 +130,16 @@ class RoomAvailabilityRepository extends ServiceEntityRepository
/**
* For a given RoomCategory, sets its availability for all days on a period with the given amount.
*/
public function bulkEditRoomAvailabilityForCategoryOnPeriod(RoomCategory $roomCategory, \DateTimeInterface $startDate, \DateTimeInterface $endDate, int $amount): void
public function bulkEditRoomAvailabilityForCategoryOnPeriod(RoomCategory $roomCategory, \DateTimeInterface $startDate, \DateTimeInterface $endDate, int $amount, bool $useTransactions = true): void
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
$roomCatId = $roomCategory->getId();
$entityManager = $this->getEntityManager();
$entityManager->beginTransaction();
if ($useTransactions) {
$entityManager->beginTransaction();
}
try {
@@ -144,7 +147,7 @@ class RoomAvailabilityRepository extends ServiceEntityRepository
$this->createQueryBuilder('ra')
->delete()
->andWhere('ra.day >= :startDate')
->andWhere('ra.day < :endDate')
->andWhere('ra.day <= :endDate')
->andWhere('ra.roomCategory = :roomCategory')
->setParameter('roomCategory', $roomCatId)
->setParameter('startDate', $strStartDate)
@@ -154,8 +157,10 @@ class RoomAvailabilityRepository extends ServiceEntityRepository
$entityManager->flush();
// Include end date.
$endDateIncluded = date_add($endDate, new DateInterval("P1D"));
//For each day, create item and persist it.
$daterange = new \DatePeriod($startDate, new \DateInterval('P1D'), $endDate);
$daterange = new \DatePeriod($startDate, new \DateInterval('P1D'), $endDateIncluded);
foreach ($daterange as $date) {
$item = new RoomAvailability();
$item->setRoomCategory($roomCategory);
@@ -166,12 +171,15 @@ class RoomAvailabilityRepository extends ServiceEntityRepository
}
$entityManager->flush();
$entityManager->commit();
if ($useTransactions) {
$entityManager->commit();
}
} catch (\Throwable $th) {
$entityManager->rollback();
if ($useTransactions) {
$entityManager->rollback();
}
throw $th;
}
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Service;
use App\DTO\AppSetupConfig;
use App\Entity\ConfigVariable;
use App\Entity\User;
use App\Enum\ConfigSectionType;
use App\Enum\UserRoleEnum;
use App\Repository\ConfigVariableRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
/**
* Service for setup proccess.
*/
class AppSetupService
{
public function __construct(
private LoggerInterface $logger,
private EntityManagerInterface $entityManager,
private ConfigVariableRepository $repoVariables,
private UserPasswordHasherInterface $passwordHasher,
private Security $security
) {}
public function InitialSetup(AppSetupConfig $configData): bool
{
$this->entityManager->beginTransaction();
$user = new User();
try {
//Create system variables.
$this->logger->info("SomniaRooms Setup - Creating system variables...");
$var_setup = $this->repoVariables->find("SETUP_STATUS");
if (!$var_setup) {
$var_setup = new ConfigVariable();
$var_setup->setKey("SETUP_STATUS");
}
$var_setup->setValue("1");
$var_setup->setSection(ConfigSectionType::Internal);
$this->entityManager->persist($var_setup);
//Create user Admin.
$this->logger->info("SomniaRooms Setup - Adding super-admin user...");
$user->setUsername($configData->getAdminUser());
$user->setRoles([UserRoleEnum::ROLE_USER->value, UserRoleEnum::ROLE_ADMIN->value, UserRoleEnum::ROLE_SUPERADMIN->value]);
$plaintextPassword = $configData->getAdminPass();
// hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $this->passwordHasher->hashPassword(
$user,
$plaintextPassword
);
$user->setPassword($hashedPassword);
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->entityManager->commit();
} catch (\Throwable $th) {
$this->entityManager->rollback();
throw $th;
}
//If init was sucessfull, log admin user.
$this->security->login($user);
$this->logger->info("SomniaRooms Setup completed!");
return true;
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Service;
use App\DTO\AppSetupConfig;
use App\DTO\ExampleDataConfig;
use App\Entity\ConfigVariable;
use App\Entity\FareTable;
use App\Entity\RoomCategory;
use App\Entity\RoomFare;
use App\Entity\User;
use App\Enum\ConfigSectionType;
use App\Enum\UserRoleEnum;
use App\Repository\ConfigVariableRepository;
use App\Repository\FareTableRepository;
use App\Repository\RoomAvailabilityRepository;
use App\Repository\RoomCategoryRepository;
use App\Repository\RoomFareRepository;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
/**
* Service for setup proccess.
*/
class ExampleDataService
{
public function __construct(
private LoggerInterface $logger,
private EntityManagerInterface $entityManager,
private RoomCategoryRepository $roomCategoryRepository,
private RoomAvailabilityRepository $roomAvailabilityRepository,
private FareTableRepository $fareTableRepository,
private RoomFareRepository $roomFareRepository,
) {}
public function AddExampleData(ExampleDataConfig $config): string
{
$genMode = $config->getGenMode();
if ($genMode == ExampleDataConfig::GENMODE_EXAMPLE) {
return "'Example' generation mode is not supported yet!";
}
$this->entityManager->beginTransaction();
try {
if ($config->getGenRoomCategories()) {
$this->GenerateRoomCategories();
}
if ($config->getGenAvailability()) {
$this->GenerateAvailability($config);
}
if ($config->getGenFaretables()) {
$this->GenerateFares($config);
}
$this->entityManager->flush();
$this->entityManager->commit();
} catch (\Throwable $th) {
$this->entityManager->rollback();
throw $th;
}
return "OK";
}
private function GenerateRoomCategories(): bool
{
//TODOME.
return true;
}
private function GenerateAvailability(ExampleDataConfig $config): bool
{
$roomCategoryList = $this->roomCategoryRepository->findAll();
foreach ($roomCategoryList as $room) {
//TODOME: Make amounts configurable.
$amount = random_int(0, 7);
$this->roomAvailabilityRepository->bulkEditRoomAvailabilityForCategoryOnPeriod(
$room,
$config->getStartDate(),
$config->getEndDate(),
$amount,
useTransactions: false
);
}
return true;
}
private function GenerateFares(ExampleDataConfig $config): bool
{
$generationTime = new DateTime();
$strGenTime = $generationTime->format('d-m-Y H:i:s');
$roomCategoryList = $this->roomCategoryRepository->findAll();
foreach ($roomCategoryList as $room) {
$list = $this->fareTableRepository->findFareTable($room->getId(), $config->getStartDate(), $config->getEndDate());
if (count($list) > 0) {
//TODOME: Log info.
continue;
}
$fareTable = new FareTable();
$fareTable->setStartDate($config->getStartDate());
$fareTable->setEndDate($config->getEndDate());
$fareTable->setRoomCategory($room);
$fareTable->setComment("Autogenerated " . $strGenTime);
$this->entityManager->persist($fareTable);
for ($i = 1; $i < $room->getMaxGuestNum(); $i++) {
$roomFare = new RoomFare();
$roomFare->setGuestNumber($i);
$roomFare->setFareTable($fareTable);
//TODOME: Make amounts configurable.
// Random price per person.
$amount = random_int(10, 25) * $i * 100;
$roomFare->setFareAmount($amount);
$this->entityManager->persist($roomFare);
}
}
return true;
}
}