src/Controller/Frontend/Customer/CustomersController.php line 238

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Frontend\Customer;
  3. use App\Entity\Assay\Assay;
  4. use App\Entity\Customer\Customer;
  5. use App\Entity\Customer\CustomerArea;
  6. use App\Entity\Customer\DeleteAccounts;
  7. use App\Entity\QrCode\QrAssayRelation;
  8. use App\Entity\QrCode\QRData;
  9. use App\Entity\User\User;
  10. use App\Form\Type\Frontend\Base64UploadedFileType;
  11. use App\Form\Type\Frontend\CustomerAreaType;
  12. use App\Form\Type\Frontend\CustomerType;
  13. use App\Form\Type\Frontend\DeleteAccountType;
  14. use App\Service\AccessTokenService;
  15. use App\Uploader\CustomerAreaUploader;
  16. use App\Uploader\CustomerUploader;
  17. use App\ViewModel\Frontend\AccessTokenViewModel;
  18. use App\Service\StabVidaTokenService;
  19. use App\ViewModel\Frontend\StabVidaTokenViewModel;
  20. use App\ViewModel\Frontend\CustomerAreaViewModel;
  21. use App\ViewModel\Frontend\CustomerViewModel;
  22. use DateTime;
  23. use Doctrine\ORM\EntityManagerInterface;
  24. use Exception;
  25. use Nelmio\ApiDocBundle\Annotation\Model;
  26. use Nelmio\ApiDocBundle\Annotation\Security;
  27. use OpenApi\Annotations as OA;
  28. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  29. use Symfony\Component\Form\FormFactoryInterface;
  30. use Symfony\Component\HttpFoundation\File\UploadedFile;
  31. use Symfony\Component\HttpFoundation\JsonResponse;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  34. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  35. use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
  36. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  37. use Symfony\Component\Routing\Annotation\Route;
  38. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  39. use Symfony\Component\Validator\Constraints as Assert;
  40. /**
  41.  * Class CustomersController
  42.  *
  43.  * @package App\Controller
  44.  */
  45. class CustomersController extends AbstractController {
  46.     /**
  47.      * @var EntityManagerInterface
  48.      */
  49.     private $entityManager;
  50.     /**
  51.      * @var FormFactoryInterface
  52.      */
  53.     private $formFactory;
  54.     /**
  55.      * @var CustomerUploader
  56.      */
  57.     private $customerUploader;
  58.     /**
  59.      * @var CustomerAreaUploader
  60.      */
  61.     private $customerAreaUploader;
  62.     /**
  63.      * @var UserPasswordEncoderInterface
  64.      */
  65.     private $passwordEncoder;
  66.     /**
  67.      * @var AccessTokenService
  68.      */
  69.     private $accessTokenService;
  70.     /**
  71.      * @var StabVidaTokenService
  72.      */
  73.     private $stabVidaTokenService;
  74.     /**
  75.      * CustomersController constructor.
  76.      *
  77.      * @param EntityManagerInterface $entityManager
  78.      * @param FormFactoryInterface $formFactory
  79.      * @param AccessTokenService $accessTokenService
  80.      * @param StabVidaTokenService $stabVidaTokenService
  81.      * @param UserPasswordEncoderInterface $passwordEncoder
  82.      * @param CustomerUploader $customerUploader ,
  83.      * @param CustomerAreaUploader $customerAreaUploader
  84.      */
  85.     public function __construct(
  86.         EntityManagerInterface $entityManager,
  87.         FormFactoryInterface $formFactory,
  88.         AccessTokenService $accessTokenService,
  89.         StabVidaTokenService $stabVidaTokenService,
  90.         UserPasswordEncoderInterface $passwordEncoder,
  91.         CustomerUploader $customerUploader,
  92.         CustomerAreaUploader $customerAreaUploader
  93.     ) {
  94.         $this->entityManager $entityManager;
  95.         $this->formFactory $formFactory;
  96.         $this->accessTokenService $accessTokenService;
  97.         $this->stabVidaTokenService $stabVidaTokenService;
  98.         $this->passwordEncoder $passwordEncoder;
  99.         $this->customerUploader $customerUploader;
  100.         $this->customerAreaUploader $customerAreaUploader;
  101.     }
  102.     /**
  103.      * Get the currently logged-in customer profile
  104.      *
  105.      * @Route(path="/me", methods={"GET"})
  106.      * @Security(name="Bearer")
  107.      * @OA\Response(
  108.      *     response="200",
  109.      *     ref="#/components/schemas/Customer"
  110.      * )
  111.      * @OA\Response(
  112.      *     response="401",
  113.      *     description="Authentication needed",
  114.      *     ref="#/components/schemas/UnauthorizedResponseError"
  115.      * )
  116.      */
  117.     public function meAction(): JsonResponse {
  118.         $customer $this->entityManager
  119.             ->getRepository(Customer::class)
  120.             ->getCustomerForUser($this->getUser());
  121.         return $this->json($customer200, [], CustomerViewModel::create($customer$this->customerUploader));
  122.     }
  123.     /**
  124.      * Update customer information
  125.      *
  126.      * @Route(path="/me", methods={"PATCH"})
  127.      * @param Request $request
  128.      * @return JsonResponse
  129.      * @throws Exception
  130.      * @Security(name="Bearer")
  131.      * @OA\Response(
  132.      *     response="200",
  133.      *     description="The access token",
  134.      *     @Model(type=AccessTokenViewModel::class)
  135.      * )
  136.      * @OA\Response(
  137.      *     response="400",
  138.      *     description="Authentication needed",
  139.      *     ref="#/components/schemas/BadRequestError"
  140.      * )
  141.      * @OA\Response(
  142.      *     response="401",
  143.      *     description="Authentication needed",
  144.      *     ref="#/components/schemas/UnauthorizedResponseError"
  145.      * )
  146.      * @OA\Response(
  147.      *     response="404",
  148.      *     description="Invalid password",
  149.      *     ref="#/components/schemas/NotFoundError"
  150.      * )
  151.      * @OA\Response(
  152.      *     response="409",
  153.      *     description="Invalid e-mail",
  154.      *     ref="#/components/schemas/ConflictError"
  155.      * )
  156.      */
  157.     public function updateAction(Request $request): JsonResponse {
  158.         /** @var User $user */
  159.         $user $this->getUser();
  160.         $customer $this->entityManager
  161.             ->getRepository(Customer::class)
  162.             ->getCustomerForUser($user);
  163.         $form $this->formFactory->create(CustomerType::class, $customer);
  164.         $form->submit(json_decode($request->getContent(), true));
  165.         
  166.         if(!$form->isSubmitted() || !$form->isValid()) {
  167.             throw new BadRequestHttpException($form->getErrors(truefalse)); // 400 - Bad Request
  168.         }
  169.         $currentPassword $form->get('currentPassword')->getData();
  170.         $plainPassword $form->get('password')->getData();
  171.         if(!$this->passwordEncoder->isPasswordValid($user$currentPassword)) {
  172.             throw new NotFoundHttpException();
  173.         }
  174.         $this->entityManager->beginTransaction();
  175.         if($customer->getEmail() !== $user->getEmail()) {
  176.             $existingUser $this->entityManager
  177.                 ->getRepository(User::class)
  178.                 ->findOneBy(['email' => $customer->getEmail()]);
  179.             if($existingUser !== null) {
  180.                 throw new ConflictHttpException(); //409 - Conflict
  181.             }
  182.             $user->setEmail($customer->getEmail());
  183.         }
  184.         if(!empty($plainPassword)) {
  185.             $passwordEncoded $this->passwordEncoder->encodePassword($user$plainPassword);
  186.             $user->setPassword($passwordEncoded);
  187.             $user->setResetPasswordToken(null);
  188.             $user->setResetPasswordExpiresAt(null);
  189.         }
  190.         $this->entityManager->persist($user);
  191.         $this->entityManager->persist($customer);
  192.         $this->entityManager->flush();
  193.         $this->entityManager->commit();
  194.         $accessToken $this->accessTokenService->createAccessToken($user);
  195.         return $this->json(AccessTokenViewModel::create($accessToken));
  196.     }
  197.     /**
  198.      * Get customer settings
  199.      *
  200.      * @Route(path="/myArea", methods={"GET"})
  201.      * @Security(name="Bearer")
  202.      * @OA\Response(
  203.      *     response="200",
  204.      *     ref="#/components/schemas/CustomerArea"
  205.      * )
  206.      * @OA\Response(
  207.      *     response="401",
  208.      *     description="Authentication needed",
  209.      *     ref="#/components/schemas/UnauthorizedResponseError"
  210.      * )
  211.      */
  212.     public function myAreaAction(): JsonResponse {
  213.         $customerArea $this->entityManager
  214.             ->getRepository(CustomerArea::class)
  215.             ->getCustomerAreaForUser($this->getUser());
  216.         if(!$customerArea) {
  217.             $customerArea = new CustomerArea();
  218.             $customerArea->setUser($this->getUser());
  219.             $this->entityManager->persist($customerArea);
  220.             $this->entityManager->flush();
  221.         }
  222.         return $this->json(
  223.             $customerArea,
  224.             200,
  225.             [],
  226.             CustomerAreaViewModel::create($customerArea$this->customerAreaUploader)
  227.         );
  228.     }
  229.     /**
  230.      * Update customer settings
  231.      *
  232.      * @Route(path="/setMyArea", methods={"POST"})
  233.      * @Security(name="Bearer")
  234.      * @OA\RequestBody(
  235.      *     @Model(type=CustomerAreaType::class)
  236.      * )
  237.      * @OA\Response(
  238.      *     response="200",
  239.      *     ref="#/components/schemas/CustomerArea"
  240.      * )
  241.      * @OA\Response(
  242.      *     response="400",
  243.      *     ref="#/components/schemas/BadRequestError"
  244.      * )
  245.      * @OA\Response(
  246.      *     response="401",
  247.      *     description="Authentication needed",
  248.      *     ref="#/components/schemas/UnauthorizedResponseError"
  249.      * )
  250.      */
  251.     public function setMyArea(Request $request): JsonResponse {
  252.         $customerArea $this->entityManager
  253.             ->getRepository(CustomerArea::class)
  254.             ->getCustomerAreaForUser($this->getUser());
  255.         $customerAreaForm $this->formFactory
  256.             ->create(CustomerAreaType::class, $customerArea);
  257.         $customerAreaForm->submit(json_decode($request->getContent(), true));
  258.         if(!$customerAreaForm->isSubmitted() || !$customerAreaForm->isValid()) {
  259.             throw new BadRequestHttpException($customerAreaForm->getErrors());
  260.         }
  261.         /** @var UploadedFile $uploadedFile */
  262.         $uploadedFile $customerAreaForm->get('signature')->getData();
  263.         /** @var CustomerArea $newArea * */
  264.         $newArea $customerAreaForm->getData();
  265.         if (isset($uploadedFile)) {
  266.             $uploadedFilename $this->customerAreaUploader->upload($uploadedFile);
  267.             $newArea->setSignatureFilename($uploadedFilename);
  268.         } 
  269.         else {
  270.             $newArea->setSignatureFilename(null);
  271.         }
  272.         $this->entityManager->persist($newArea);
  273.         $this->entityManager->flush();
  274.         return $this->json($newArea200, [], CustomerAreaViewModel::VIEW_CONTEXT);
  275.     }
  276.     /**
  277.      * Upload customer logo
  278.      *
  279.      * @Route(path="/uploadLogo", methods={"POST"})
  280.      * @param Request $request
  281.      * @return JsonResponse
  282.      * @Security(name="Bearer")
  283.      * @OA\RequestBody(
  284.      *     @Model(type=Base64UploadedFileType::class)
  285.      * )
  286.      * @OA\Response(
  287.      *     response="200",
  288.      *     description="Empty response",
  289.      *     @OA\Schema(type="array")
  290.      * )
  291.      * @OA\Response(
  292.      *     response="400",
  293.      *     ref="#/components/schemas/BadRequestError"
  294.      * )
  295.      * @OA\Response(
  296.      *     response="401",
  297.      *     description="Authentication needed",
  298.      *     ref="#/components/schemas/UnauthorizedResponseError"
  299.      * )
  300.      */
  301.     public function uploadLogo(Request $request): JsonResponse {
  302.         /** @var Customer $customer */
  303.         $customer $this->entityManager
  304.             ->getRepository(Customer::class)
  305.             ->getCustomerForUser($this->getUser());
  306.         $form $this->formFactory
  307.             ->create(
  308.                 Base64UploadedFileType::class,
  309.                 null,
  310.                 [
  311.                     'constraints' => [
  312.                         new Assert\Image(),
  313.                     ],
  314.                 ]
  315.             );
  316.         $form->submit($request->getContent());
  317.         if(!$form->isSubmitted() || !$form->isValid()) {
  318.             throw new BadRequestHttpException($form->getErrors());
  319.         }
  320.         /** @var UploadedFile $uploadedFile */
  321.         $uploadedFile $form->getData();
  322.         if(isset($uploadedFile)) {
  323.             $uploadedFilename $this->customerUploader->upload($uploadedFile);
  324.             $customer->setLogoFilename($uploadedFilename);
  325.         } 
  326.         else {
  327.             $customer->setLogoFilename(null);
  328.         }
  329.         $this->entityManager->persist($customer);
  330.         $this->entityManager->flush();
  331.         return $this->json([]);
  332.     }
  333.     /**
  334.      * Delete the customer account
  335.      *
  336.      * @Route(path="/deleteAccount", methods={"PATCH"})
  337.      * @param Request $request
  338.      * @return JsonResponse
  339.      * @throws Exception
  340.      * @Security(name="Bearer")
  341.      * @OA\RequestBody(
  342.      *     @Model(type=DeleteAccountType::class)
  343.      * )
  344.      * @OA\Response(
  345.      *     response="200",
  346.      *     description="Empty response",
  347.      *     @OA\Schema(type="array")
  348.      * )
  349.      * @OA\Response(
  350.      *     response="400",
  351.      *     ref="#/components/schemas/BadRequestError"
  352.      * )
  353.      * @OA\Response(
  354.      *     response="401",
  355.      *     description="Authentication needed",
  356.      *     ref="#/components/schemas/UnauthorizedResponseError"
  357.      * )
  358.      * @OA\Response(
  359.      *     response="404",
  360.      *     description="Invalid password",
  361.      *     ref="#/components/schemas/NotFoundError"
  362.      * )
  363.      * @OA\Response(
  364.      *     response="409",
  365.      *     description="Conflict",
  366.      *     ref="#/components/schemas/ConflictError"
  367.      * )
  368.      */
  369.     public function deleteAccountAction(Request $request): JsonResponse {
  370.         $user $this->getUser();
  371.         $customer $this->entityManager
  372.             ->getRepository(Customer::class)
  373.             ->getCustomerForUser($user);
  374.         $form $this->formFactory->create(DeleteAccountType::class, null);
  375.         $form->submit(json_decode($request->getContent(), true));
  376.         
  377.         if(!$form->isSubmitted() || !$form->isValid()) {
  378.             throw new BadRequestHttpException($form->getErrors(truefalse)); // 400 - Bad Request
  379.         }
  380.         $email $form->get('email')->getData();
  381.         $currentPassword $form->get('currentPassword')->getData();
  382.         if(!$this->passwordEncoder->isPasswordValid($user$currentPassword)) {
  383.             throw new NotFoundHttpException();
  384.         }
  385.         $this->entityManager->beginTransaction();
  386.         if($customer->getEmail() === $user->getEmail()) {
  387.             $existingUser $this->entityManager
  388.                 ->getRepository(User::class)
  389.                 ->findOneBy(['email' => $user->getUsername()]);
  390.             if($existingUser === null) {
  391.                 throw new ConflictHttpException(); //409 - Conflict
  392.             }
  393.             if($email !== $user->getEmail()) {
  394.                 throw new ConflictHttpException(); //409 - Conflict
  395.             }
  396.             $pocketsInfo $this->entityManager
  397.                 ->getRepository(Assay::class)
  398.                 ->getDistinctHardwareVersionDevicesFromAssays($user);
  399.             $pocketsSts "";
  400.             $i 0;
  401.             
  402.             foreach($pocketsInfo as $jsonPockets) {
  403.                 $pockets $jsonPockets['hardwareVersion'];
  404.                 
  405.                 if(trim($pockets) != null) {
  406.                     if($i 0) {
  407.                         $pocketsSts $pocketsSts.";".$pockets;
  408.                     } 
  409.                     else {
  410.                         $pocketsSts $pockets;
  411.                     }
  412.                     $i++;
  413.                 }
  414.             }
  415.             $IdsInfo $this->entityManager
  416.                 ->getRepository(Assay::class)
  417.                 ->getAssaysIds($user);
  418.             $idsSt "";
  419.             $i 0;
  420.             foreach ($IdsInfo as $jsonIds) {
  421.                 $ids $jsonIds['assayId'];
  422.                 
  423.                 if(trim($ids) != null) {
  424.                     if($i 0) {
  425.                         $idsSt $idsSt.";".$ids;
  426.                     } 
  427.                     else {
  428.                         $idsSt $ids;
  429.                     }
  430.                     $i++;
  431.                 }
  432.             }
  433.             $deleteAcc = new DeleteAccounts();
  434.             $deleteAcc->setUserId($customer->getCustomerId());
  435.             $deleteAcc->setAssayIds($idsSt);
  436.             $deleteAcc->setPockets($pocketsSts);
  437.             $deleteAcc->setDeleteDatetime(new DateTime());
  438.             $this->entityManager->persist($deleteAcc);
  439.             //######### DELETE QR DATA ############//
  440.             $qrData $this->entityManager
  441.                 ->getRepository(QRData::class)
  442.                 ->deleteQrDataByUser($user);
  443.             $qrAssayRelation $this->entityManager
  444.                 ->getRepository(QrAssayRelation::class)
  445.                 ->deleteQrAssayRelationByUser($user);
  446.             //######### DELETE USER AND CASCADE ############//
  447.             $this->entityManager->remove($user);
  448.             // ON DELETE CASCADE // //# UESRS #//
  449.             //# ACCESS TOKEN #//    //# ASSAYS #//  //# ASSAY_DATA #//
  450.             //# ASSAY_RESULTS #//   //# CUSTOMERS #//   //# CUSTOMER_AREA #//
  451.             $this->entityManager->flush();
  452.             $this->entityManager->commit();
  453.         } 
  454.         else {
  455.             throw new ConflictHttpException(); //409 - Conflict
  456.         }
  457.         return $this->json([]);
  458.     }
  459.     /**
  460.      * Get the stab vida access token
  461.      *
  462.      * @Route(path="/stabVidaToken", methods={"GET"})
  463.      * @Security(name="Bearer")
  464.      * @OA\Response(
  465.      *     response="200",
  466.      *     description="The stab vida access token",
  467.      *     @Model(type=StabVidaTokenViewModel::class)
  468.      * )
  469.      * @OA\Response(
  470.      *     response="400",
  471.      *     ref="#/components/schemas/BadRequestError"
  472.      * )
  473.      * @throws Exception
  474.      */
  475.     public function getStabVidaAccessToken(): JsonResponse {
  476.         $user $this->getUser();
  477.         $stabVidaToken $this->stabVidaTokenService->getStabVidaToken($user);
  478.         if($stabVidaToken === null) {
  479.             throw new BadRequestHttpException("User is not registered in clients.stabvida.com");
  480.         }
  481.         $stabVidaTokenViewModel StabVidaTokenViewModel::create($stabVidaToken);
  482.         return $this->json($stabVidaTokenViewModel);
  483.     }
  484. }