src/Controller/Web/DefaultController.php line 88

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Web;
  3. use App\Entity\Building;
  4. use App\Entity\ProcessedFiles;
  5. use App\Exception\ParseFileFailedException;
  6. use App\Form\LastLoginType;
  7. use App\Form\MultipleFileUploadType;
  8. use App\Form\ProcessedFileType;
  9. use App\Helpers\ApiLogger;
  10. use App\Helpers\CommonHelper;
  11. use App\Repository\FlatRepository;
  12. use App\Repository\ProcessedFilesRepository;
  13. use App\Repository\UserRepository;
  14. use App\Response\PdfResponse;
  15. use App\Services\Bank\ParserInterface;
  16. use App\Services\BuildingService;
  17. use App\Services\DefaultService;
  18. use App\Services\ProcessService;
  19. use DateTime;
  20. use Doctrine\ORM\NonUniqueResultException;
  21. use Doctrine\ORM\NoResultException;
  22. use Knp\Snappy\Pdf;
  23. use Symfony\Component\Form\Form;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use App\Entity\User;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  30. use Symfony\Component\Routing\Annotation\Route;
  31. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  32. class DefaultController extends AbstractController
  33. {
  34.     private DefaultService $defaultService;
  35.     private UserRepository $userRepository;
  36.     private Pdf $pdf;
  37.     private FlatRepository $flatRepository;
  38.     private ProcessService $processService;
  39.     private BuildingService $buildingService;
  40.     private ProcessedFilesRepository $processedFilesRepository;
  41.     /**
  42.      * DefaultController constructor.
  43.      * @param DefaultService $defaultService
  44.      * @param UserRepository $userRepository
  45.      * @param Pdf $pdf
  46.      * @param FlatRepository $flatRepository
  47.      * @param ProcessService $processService
  48.      * @param BuildingService $buildingService
  49.      * @param ProcessedFilesRepository $processedFilesRepository
  50.      */
  51.     public function __construct(
  52.         DefaultService $defaultService,
  53.         UserRepository $userRepository,
  54.         Pdf $pdf,
  55.         FlatRepository $flatRepository,
  56.         ProcessService $processService,
  57.         BuildingService $buildingService,
  58.         ProcessedFilesRepository $processedFilesRepository
  59.     ) {
  60.         $this->defaultService $defaultService;
  61.         $this->userRepository $userRepository;
  62.         $this->pdf $pdf;
  63.         $this->flatRepository $flatRepository;
  64.         $this->processService $processService;
  65.         $this->buildingService $buildingService;
  66.         $this->processedFilesRepository $processedFilesRepository;
  67.     }
  68.     /**
  69.      * @Route("/", name="homepage")
  70.      * @return RedirectResponse
  71.      */
  72.     public function indexAction(): RedirectResponse
  73.     {
  74.         return new RedirectResponse($this->generateUrl('dashboard'));
  75.     }
  76.     /**
  77.      * @return Response
  78.      * @throws NoResultException
  79.      * @throws NonUniqueResultException
  80.      */
  81.     #[Route('/dashboard'name'dashboard')]
  82.     public function dashboardAction(): Response
  83.     {
  84.         /** @var User $user */
  85.         $user $this->getUser();
  86.         $isSuperAdmin $this->defaultService->isImpersonatorSuperAdmin();
  87.         return $this->render(
  88.             '@views/Default/dashboard.html.twig',
  89.             $this->defaultService->getDashboardInformation($user$isSuperAdmin)
  90.         );
  91.     }
  92.     /**
  93.      * @return Response
  94.      * @throws NoResultException
  95.      * @throws NonUniqueResultException
  96.      */
  97.     #[Route('/dashboard_new'name'dashboard_new')]
  98.     public function dashboardNewAction(Request $request): Response
  99.     {
  100.         $processedBuildings = [];//todo: fetch unprocessed files
  101.         $logs = [];
  102.         /** @var User $user */
  103.         $user $this->getUser();
  104.         $isSuperAdmin $this->defaultService->isImpersonatorSuperAdmin();
  105.         $allMonths = [
  106.             '2024-10-01' => '2024-10-01',
  107.             '2024-09-01' => '2024-09-01',
  108.             '2024-08-01' => '2024-08-01',
  109.             '2024-07-01' => '2024-07-01',
  110.             '2024-06-01' => '2024-06-01',
  111.             '2024-05-01' => '2024-05-01',
  112.             '2024-04-01' => '2024-04-01',
  113.             '2024-03-01' => '2024-03-01',
  114.             '2024-02-01' => '2024-02-01',
  115.             '2024-01-01' => '2024-01-01',
  116.             '2023-12-01' => '2024-12-01',
  117.         ];
  118.         $allMonthsView = [];
  119.         foreach ($allMonths as $month) {
  120.             $newMonth CommonHelper::getMonth($month);
  121.             $allMonthsView[] = $newMonth;
  122.         }
  123.         $form $this->createForm(MultipleFileUploadType::class);
  124.         $form->handleRequest($request);
  125.         if ($form->isSubmitted() && $form->isValid()) {
  126.             $files $form->get('files')->getData();
  127.             $logs[] = "\n================================== START ==================================================\n";
  128.             foreach ($files as $key => $file) {
  129.                 //// BEGIN - add to job -----------
  130.                 $logs[] = "\n ------- file :$key  ------- ";
  131.                 $fileExtension $file->guessClientExtension();
  132.                 $fileName sprintf(
  133.                     "%s%s.%s",
  134.                     md5($file->getClientOriginalName()),
  135.                     uniqid(),
  136.                     $file->guessClientExtension()
  137.                 );
  138.                 $logs[] = "\n"date("Y-m-m H:i:s") . " - file: ".$file->getClientOriginalName() ."."$fileExtension .". md5 hash:  ".$fileName;
  139.                     // Move the file to the directory where brochures are stored
  140.                 $file->move(
  141.                     $this->getParameter('bank_notification_directory'),
  142.                     $fileName
  143.                 );
  144.                 $logs[] = "\nMoved file to directory: ";
  145.                 $bankNameDetails $this->processService->getBankNameDetails(
  146.                     $fileName,
  147.                     $fileExtension,
  148.                     $this->getParameter('bank_notification_directory')
  149.                 );
  150.                 if (empty($bankNameDetails)) {
  151.                     //to do: add log
  152.                     $logs[] = "\nBank detail is empty. ";
  153.                     $logs[] = "\nFinished file\n==================\n";
  154.                     $processedBuildings[] = [
  155.                         "building" => $file->getClientOriginalName().".".$file->guessClientExtension(),
  156.                         "type"    => "file",
  157.                         "status" => false
  158.                     ];
  159.                     continue;
  160.                 }
  161.                 $logs[] = "\nBank detail: bankName: "$bankNameDetails['bankName'] ." datum: " .$bankNameDetails['datum']->getTimestamp() ;
  162.                 //to do: add log
  163.                 /** @var Building|null $building */
  164.                 $building $this->buildingService->getBuildingByBankAccount($bankNameDetails['account']);
  165.                 if (!$building) {
  166.                     $logs[] = "\nBuilding does not exist with account: ".$bankNameDetails['account'];
  167.                     $logs[] = "\nFinished file\n==================\n";
  168.                     $processedBuildings[] = [
  169.                         "building" => $file->getClientOriginalName().".".$file->guessClientExtension(),
  170.                         "type"    => "building",
  171.                         "status" => false
  172.                     ];
  173.                     continue;
  174.                 }
  175.                 try {
  176.                     $this->defaultService->checkEntity($building$user);
  177.                 } catch (\Exception $exception) {
  178.                     $processedBuildings[] = [
  179.                         "building" => $file->getClientOriginalName().".".$file->guessClientExtension(),
  180.                         "type"    => "building not belong",
  181.                         "status" => false
  182.                     ];
  183.                     $logs[] = "\nBuilding not belong. ";
  184.                     $logs[] = "\nFinished file\n==================\n";
  185.                     continue;
  186.                 }
  187.                 $processedBuildings[] = [
  188.                     "building" => $building ?? null,
  189.                     "type" => "building",
  190.                     "status" => $building true false
  191.                 ];
  192.                 $processedFiles = new ProcessedFiles();
  193.                 $processedFiles->setBankDailyNotification($fileName);
  194.                 $processedFiles->setBankName($bankNameDetails['bankName']);
  195.                 $processedFiles->setBankDate($bankNameDetails['datum']);
  196.                 $processedFiles->setBuilding($building);
  197.                 $processedFiles->setUser($user);
  198.                 $logs[] = "\nSet ProcessedFiles, with values: $fileName, bankName: "$bankNameDetails['bankName'] ." datum: " .$bankNameDetails['datum']->getTimestamp() .",  user: ".$user->getId() .", building: ".$building->getId();
  199.                 /** @var ProcessedFiles|null $file */
  200.                 $file $this->processedFilesRepository->findOneBy([
  201.                     'user' => $building->getUser(),
  202.                     'bankDate' => $bankNameDetails['datum'],
  203.                     'building' => $building,
  204.                     'bankName' => $bankNameDetails['bankName']
  205.                 ]);
  206.                 if (!$file) {
  207.                     $logs[] = "\nSave new file. ";
  208.                     $processedFiles->setStatus(0);
  209.                     $this->processedFilesRepository->save($processedFiles);
  210.                 } else {
  211.                     $logs[] = "\nAlready exist file. ";
  212.                     $processedFiles $file;
  213.                 }
  214.                 $companyUsers $this->userRepository->findUsersByMain($user);
  215.                 if (!in_array($building->getUser(), $companyUsers)) {
  216.                     $logs[] = "\nBuilding is not belong to user: ".$user->getId() .", building: ".$building->getId();
  217.                     $logs[] = "\nFinished file\n==================\n";
  218.                     $processedBuildings[] = [
  219.                         "building" => $fileName,
  220.                         "type"    => "user",
  221.                         "status" => false
  222.                     ];
  223.                     continue;
  224.                 }
  225.                 /** @var ParserInterface $parser */
  226.                 $parser $this->processService->getParser($bankNameDetails['bankName']);
  227.                 $parsedData $parser->parseFile($this->getParameter('bank_notification_directory'), $processedFiles);
  228.                 if (!$this->processService->isValidParsedData($parsedData$building)) {
  229.                     $logs[] = "\nParsed data is not valid";
  230.                     $logs[] = "\nFinished file\n==================\n";
  231.                     $processedBuildings[] = [
  232.                         "building" => $file->getClientOriginalName().".".$file->guessClientExtension(),
  233.                         "type"    => "data",
  234.                         "status" => false
  235.                     ];
  236.                     continue;
  237.                 }
  238.                 $logs[] = "\nParsed file: ".$parsedData['bankDailyCheckPoint'];
  239.                 $processedFiles->setBankFileId($parsedData['bankDailyCheckPoint']);
  240.                 $processedFileStatus $this->processService->processBankNotification($parsedData$processedFiles$building$logs);
  241.                 $count $processedFiles->getProcessedFlats() ? $processedFiles->getProcessedFlats()->count() : 0;
  242.                 $notProcessedFilesCount count($parsedData['flats']) - $count;
  243.                 $currentDate = new \DateTime($parsedData['bankCheckpointData']);
  244.                 $processedFiles->setBankDate($currentDate);
  245.                 $processedFiles->setNumberOfNotProcessedFiles($notProcessedFilesCount);
  246.                 $processedFiles->setStatus($processedFileStatus['status']);
  247.                 $this->processedFilesRepository->save($processedFiles);
  248.                 $logs[] = "\nFinished file\n==================\n";
  249.                 //// END - add to job -----------
  250.             }
  251.             $logs[] = "\n================================== END ========================================================\n";
  252.             $logString implode(" "$logs);
  253.             ApiLogger::addApiLog($logString'bank_statements_bulk');
  254.             //tod: add in action_log table
  255.         }
  256.         $response $this->defaultService->getDashboardInformation($user$isSuperAdmin);
  257.         $response['form'] = $form->createView();
  258.         $response['processedBuildings'] = $processedBuildings;
  259.         $response['allMonths'] = $allMonthsView;
  260.         return $this->render(
  261.             '@views/Default/dashboardNew.html.twig',
  262.             $response
  263.         );
  264.     }
  265.     /**
  266.      * @Route("/datatable-problems", name="datatable_problems", options={"expose"=true})
  267.      * @param Request $request
  268.      * @return JsonResponse
  269.      * @throws NoResultException
  270.      * @throws NonUniqueResultException
  271.      */
  272.     public function datatableProblemsAction(Request $request): JsonResponse
  273.     {
  274.         /** @var User $user */
  275.         $user $this->getUser();
  276.         return new JsonResponse($this->defaultService->getDatatableProblems($request$user));
  277.     }
  278.     /**
  279.      * @Route("super-admin/last-login", name="last_login", options={"expose"=true})
  280.      * @param Request $request
  281.      * @return RedirectResponse|Response
  282.      */
  283.     public function lastLoginAction(Request $request): Response|RedirectResponse
  284.     {
  285.         /** @var User $user */
  286.         $user $this->getUser();
  287.         /** @var Form $form */
  288.         $form $this->createForm(
  289.             LastLoginType::class,
  290.             [],
  291.             [
  292.                 'method' => 'POST',
  293.             ]
  294.         );
  295.         $form->handleRequest($request);
  296.         if ($form->isSubmitted() && $form->isValid()) {
  297.             $startDate $form->getData()['startDate']->format('Y-m-d');
  298.             $endDate null;
  299.             if ($form->getData()['endDate']) {
  300.                 $endDate $form->getData()['endDate']->format('Y-m-d');
  301.             }
  302.             if ($form->getClickedButton() === $form->get('login')) {
  303.                 $url $this->generateUrl('last_login_pdf', ['startDate' => $startDate'endDate' => $endDate]);
  304.             } else {
  305.                 $url $this->generateUrl('flats_import_list', ['startDate' => $startDate'endDate' => $endDate]);
  306.             }
  307.             return new RedirectResponse($url);
  308.         }
  309.         return $this->render('@views/Default/lastLogin.html.twig', [
  310.             'user' => $user,
  311.             'form' => $form->createView()
  312.         ]);
  313.     }
  314.     /**
  315.      * @Route(
  316.      *     "super-admin/last-login-pdf/{startDate}/{endDate}",
  317.      *     requirements={"startDate" = "\d{4}-\d{2}-\d{2}",
  318.      *     "endDate" = "\d{4}-\d{2}-\d{2}"},
  319.      *     name="last_login_pdf",
  320.      *     options={"expose"=true}
  321.      *     )
  322.      * @param DateTime $startDate
  323.      * @param DateTime|null $endDate
  324.      * @return PdfResponse
  325.      */
  326.     public function lastLoginPdfAction(DateTime $startDate, ?DateTime $endDate null): PdfResponse
  327.     {
  328.         $users $this->userRepository->getLastLoginUsers($startDate$endDate);
  329.         $html $this->renderView('@views/Default/lastLoginPdf.html.twig', [
  330.             'users' => $users,
  331.             'startDate' => $startDate,
  332.             'endDate' => $endDate,
  333.         ]);
  334.         return new PdfResponse($this->pdf$html);
  335.     }
  336.     /**
  337.      * @Route(
  338.      *     "super-admin/flats-import-list/{startDate}/{endDate}",
  339.      *     requirements={"startDate" = "\d{4}-\d{2}-\d{2}",
  340.      *     "endDate" = "\d{4}-\d{2}-\d{2}"},
  341.      *     name="flats_import_list",
  342.      *     options={"expose"=true}
  343.      *     )
  344.      * @param DateTime $startDate
  345.      * @param DateTime|null $endDate
  346.      * @return PdfResponse
  347.      */
  348.     public function flatImportPdfAction(DateTime $startDate, ?DateTime $endDate null): PdfResponse
  349.     {
  350.         $users $this->flatRepository->getFlatImportReviewByDate($startDate$endDate);
  351.         $html $this->renderView('@views/Default/flatsImportReport.html.twig', [
  352.             'users' => $users,
  353.             'startDate' => $startDate,
  354.             'endDate' => $endDate,
  355.         ]);
  356.         return new PdfResponse($this->pdf$html);
  357.     }
  358. }