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