src/DcSiteBundle/Controller/OnlineServiceController.php line 988

Open in your IDE?
  1. <?php
  2. namespace DcSiteBundle\Controller;
  3. use CoreBundle\Component\CoreFormFactory;
  4. use CoreBundle\Component\FormManager;
  5. use CoreBundle\Entity\Brand;
  6. use CoreBundle\Entity\Dealer;
  7. use CoreBundle\Entity\Model;
  8. use CoreBundle\Entity\User;
  9. use CoreBundle\Entity\UserCar;
  10. use CoreBundle\Factory\Vehicle as VehicleFactory;
  11. use CoreBundle\Model\Api\MVD\MvdServer;
  12. use CoreBundle\Model\Api\OnlineService\ApiServer1C;
  13. use CoreBundle\Model\Vehicles\Repository;
  14. use CoreBundle\Services\MediaExtensionVidi;
  15. use DateTime;
  16. use DcSiteBundle\Entity\OnlineServiceBooking;
  17. use DcSiteBundle\Entity\OnlineServiceBookingWorks;
  18. use DcSiteBundle\Entity\ServiceVariation;
  19. use DcSiteBundle\Entity\ServiceWork;
  20. use DcSiteBundle\Entity\ServiceWorkJob;
  21. use DcSiteBundle\Entity\ServiceWorkPart;
  22. use Doctrine\ORM\EntityManagerInterface;
  23. use Exception;
  24. use MyBundle\Component\InfobipSmsSender;
  25. use MyBundle\Factory\OtpCodeGenerator;
  26. use MyBundle\Service\NightBookingService;
  27. use PortalBundle\Model\SeoMetaTag;
  28. use Symfony\Component\Filesystem\Filesystem;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Symfony\Component\HttpFoundation\RequestStack;
  32. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  33. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  34. use Symfony\Component\Routing\RouterInterface;
  35. use Symfony\Contracts\Translation\TranslatorInterface;
  36. use Twig\Environment;
  37. class OnlineServiceController extends BaseDcController
  38. {
  39.     public function __construct(CoreFormFactory $coreFormFactorySeoMetaTag $seoMetaTagRequestStack $requestStackRouterInterface $routerFormManager $formManagerEntityManagerInterface $emApiServer1C $apiServer1CSessionInterface $sessionFilesystem $filesystemMediaExtensionVidi $mediaExtensionVidiRepository $vehicleRepositoryVehicleFactory $vehicleFactoryEnvironment $twig)
  40.     {
  41.         parent::__construct($coreFormFactory$seoMetaTag$requestStack$router$formManager$em$apiServer1C$session$filesystem$mediaExtensionVidi$vehicleRepository$vehicleFactory$twig);
  42.     }
  43.     public function init(Request $request): JsonResponse
  44.     {
  45.         $userData $this->initUserDealer($request);
  46.         $variationId $request->request->get('variationId');
  47.         $modelVariation $request->request->get('modelVariation');
  48.         $Variation null;
  49.         if ($variationId) {
  50.             /** @var ServiceVariation $Variation */
  51.             $Variation $this->em->getRepository(ServiceVariation::class)->find($variationId);
  52.         }
  53.         if ($Variation) {
  54.             $Dealer $Variation->getDealer();;
  55.         } else {
  56.             $Dealer $this->getDealer($request->get('dealerId'));
  57.         }
  58.         $Brand $Dealer->getBrand();
  59.         $brandId $request->get('brandId');
  60.         if (!$brandId) {
  61.             $brandId $Brand->getId();
  62.         }
  63.         if ($modelVariation) {
  64.             $Models $this->em->getRepository(Model::class)->findByBrand($brandId);
  65.         } else {
  66.             $Models $this->em->getRepository(Model::class)->findByBrandWithVariation($brandId);
  67.         }
  68.         $modelsArray = [];
  69.         /** @var Model $model */
  70.         foreach ($Models as $model) {
  71.             if ($model->getIsAutocreate() || !$model->getUid1c()) {
  72.                 continue;
  73.             }
  74.             $modelImg null;
  75.             if ($model->getImage()) {
  76.                 $modelImg $this->mediaExtensionVidi->getPath($model->getImage(), 'reference');
  77.             }
  78.             $modelsArray[] = [
  79.                 'id' => $model->getId(),
  80.                 'title' => strtolower($model->getTitle()),
  81.                 'brand' => $model->getBrand()->getName(),
  82.                 'brandId' => $model->getBrand()->getId(),
  83.                 'img' => $modelImg,
  84.             ];
  85.         }
  86.         usort($modelsArray, fn($a$b) => $a['title'] <=> $b['title']);
  87.         $firstLetter false;
  88.         foreach ($modelsArray as &$model) {
  89.             $fL substr($model['title'], 01);
  90.             if (!$firstLetter || $fL != $firstLetter) {
  91.                 $model['isFirstLetter'] = true;
  92.                 $firstLetter $fL;
  93.             }
  94.         }
  95.         $responseData = [
  96.             'user' => $userData,
  97.             'models' => $modelsArray,
  98.             'isNightDealer' => $Dealer->getIsNightDealer(),
  99.             'brandId' => $Dealer->getBrand()->getId(),
  100.             'brand' => $Dealer->getBrand()->getName(),
  101.             'brandLogo' => $this->mediaExtensionVidi->getPath($Dealer->getBrand()->getLogo(), 'reference'),
  102.         ];
  103.         if ($Variation) {
  104.             $yearTo = (new DateTime())->format('Y');
  105.             if ($Variation->getYearTo()) {
  106.                 $yearTo $Variation->getYearTo();
  107.             }
  108.             $carData = [
  109.                 'title' => (string)$Variation->getModel(),
  110.                 'MakeYear' => $Variation->getYearFrom() . ' - ' $yearTo,
  111.                 'modelId' => $Variation->getModel()->getId(),
  112.                 'variationId' => $variationId,
  113.             ];
  114.             $responseData['defaultCar'] = $carData;
  115.             $responseData['dealer_id'] = $Dealer->getId();
  116.         }
  117.         return new JsonResponse($responseData);
  118.     }
  119.     public function findDealerBrand(Request $request): JsonResponse
  120.     {
  121.         $userData $this->initUserDealer($request);
  122.         $brands $this->vehicleRepository->getAvailBrandsInstance($request->getLocale());
  123.         return new JsonResponse(['success' => true'brands' => $brands'user' => $userData]);
  124.     }
  125.     public function initService(Request $request): JsonResponse
  126.     {
  127.         $userData $this->initUserDealer($request);
  128.         $repositoryBrands $this->em->getRepository(Brand::class)->getBrandsHasRegulation();
  129.         $brands = [];
  130.         $models = [];
  131.         $dealers = [];
  132.         /** @var Brand $brand */
  133.         foreach ($repositoryBrands as $brand) {
  134.             $brands[$brand->getId()] = [
  135.                 'id' => $brand->getId(),
  136.                 'title' => $brand->getName(),
  137.                 'dealers' => []
  138.             ];
  139.             /** @var Dealer $dealer */
  140.             foreach ($brand->getDealer() as $dealer) {
  141.                 if ($dealer->getId() == 7) {
  142.                     continue;
  143.                 }
  144.                 $isNight $dealer->getIsNightDealer();
  145.                 $agreementUrl = ($isNight) ? $this->router->generate('my_profile_night_service_agreement_dealer', ['dealerUrl' => $dealer->getUrl()]) : false;
  146.                 $dealers[$dealer->getId()] = [
  147.                     'id' => $dealer->getId(),
  148.                     'title' => $dealer->getNameByLocale($request->getLocale()),
  149.                     'address' => $dealer->getAddressByLocale($request->getLocale()),
  150.                     'isNight' => $isNight,
  151.                     'agreementUrl' => $agreementUrl,
  152.                     'brandId' => $brand->getId(),
  153.                     'image' => $this->mediaExtensionVidi->getPath($brand->getLogo(), 'reference'),
  154.                 ];
  155.                 $brands[$brand->getId()]['dealers'][] = [
  156.                     'id' => $dealer->getId(),
  157.                     'title' => $dealer->getNameByLocale($request->getLocale())
  158.                 ];
  159.             }
  160.             $repositoryModels $this->em->getRepository(Model::class)->getModelsHasRegulationByBrand($brand->getId());
  161.             /** @var Model $item */
  162.             foreach ($repositoryModels as $item) {
  163.                 $models[$item->getId()] = [
  164.                     'id' => $item->getId(),
  165.                     'title' => $item->getTitle(),
  166.                     'brandId' => $item->getBrand()->getId(),
  167.                 ];
  168.             }
  169.         }
  170.         return new JsonResponse(['success' => true'user' => $userData'brands' => $brands'models' => $models'dealers' => $dealers]);
  171.     }
  172.     public function findServiceVariationByFilter(Request $request): JsonResponse
  173.     {
  174.         $modelId $request->get('modelId');
  175.         $dealerId $request->get('dealerId');
  176.         $locale $request->getLocale();
  177.         $repositoryServiceVariations $this->em->getRepository(ServiceVariation::class)->findRegulationWorkByVariation($dealerId$modelId);
  178.         $hasWorkByVariation false;
  179.         $makeYears = [];
  180.         $variations = [];
  181.         /** @var ServiceVariation $serviceVariation */
  182.         foreach ($repositoryServiceVariations as $serviceVariation) {
  183.             $yearTo = ($serviceVariation->getYearTo() == 0) ? date('Y'time()) : $serviceVariation->getYearTo();
  184.             $makeYearId $serviceVariation->getYearFrom() . $yearTo;
  185.             if (!isset($makeYears[$serviceVariation->getYearFrom()])) {
  186.                 $makeYears[$makeYearId] = [
  187.                     'id' => $makeYearId,
  188.                     'title' => $serviceVariation->getYearFrom() . ' - ' $yearTo,
  189.                 ];
  190.             }
  191.             $variationsTitle '';
  192.             if ($serviceVariation->getFuelType()) {
  193.                 $variationsTitle .= $serviceVariation->getFuelType()->getValue($locale);
  194.             }
  195.             $variationsTitle .= ' ' round($serviceVariation->getEngineVolume() / 10001) . 'л';
  196.             $titleShort $variationsTitle;
  197.             if ($serviceVariation->getDriveUnit()) {
  198.                 $variationsTitle .= ', ' $serviceVariation->getDriveUnit()->getValue($locale);
  199.             }
  200.             if ($serviceVariation->getTransmissionType()) {
  201.                 $variationsTitle .= ', ' $serviceVariation->getTransmissionType()->getValue($locale);
  202.             }
  203.             $variationsTitle .= ($serviceVariation->getTransmissionStepCount()) ? ', ' $serviceVariation->getTransmissionStepCount() . 'ст.' '';
  204.             if ($serviceVariation->getEmission()) {
  205.                 $variationsTitle .= ', ' $serviceVariation->getEmission();
  206.             }
  207.             if ($serviceVariation->getDescription()) {
  208.                 $variationsTitle .= ', ' $serviceVariation->getDescription();
  209.             }
  210.             $variations[$serviceVariation->getId()] = [
  211.                 'id' => $serviceVariation->getId(),
  212.                 'title' => $variationsTitle,
  213.                 'titleShort' => $titleShort,
  214.                 'makeYearId' => $makeYearId,
  215.                 'yearFrom' => $serviceVariation->getYearFrom(),
  216.                 'yearTo' => $yearTo,
  217.                 'fuelType' => ($serviceVariation->getFuelType()) ? $serviceVariation->getFuelType()->getValue($locale) : '',
  218.                 'engineVolume' => round($serviceVariation->getEngineVolume() / 10001),
  219.             ];
  220.         }
  221.         if (count($variations)) {
  222.             $hasWorkByVariation true;
  223.         }
  224.         return new JsonResponse(['success' => true'makeYears' => $makeYears'variations' => $variations'hasWorkByVariation' => $hasWorkByVariation]);
  225.     }
  226.     public function initDealer(Request $request): JsonResponse
  227.     {
  228.         $userData $this->initUserDealer($request);
  229.         $brands $this->vehicleRepository->getAvailBrandsInstance($request->getLocale(), true);
  230.         foreach ($brands as &$brand) {
  231.             $brand['image'] = $this->mediaExtensionVidi->getPath($brand['image'], 'menu');
  232.         }
  233.         return new JsonResponse(['success' => true'brands' => $brands'user' => $userData]);
  234.     }
  235.     public function initUserDealer(Request $request): array
  236.     {
  237.         /** @var User $User */
  238.         if ($User $this->getUser()) {
  239.             $cars = [];
  240.             /** @var UserCar $car */
  241.             foreach ($User->getCars() as $car) {
  242.                 if (!$car->getCarModel()) {
  243.                     continue;
  244.                 }
  245.                 if ($car->getIsDeleted()) {
  246.                     continue;
  247.                 }
  248.                 $dealers $car->getCarModel()->getBrand()->getDealer();
  249.                 $dealersData = [];
  250.                 /** @var Dealer $dealer */
  251.                 foreach ($dealers as $dealer) {
  252.                     $dealersData[] = [
  253.                         'id' => $dealer->getId(),
  254.                         'title' => $dealer->getNameByLocale($request->getLocale()),
  255.                         'adress' => $dealer->getAddressByLocale($request->getLocale()),
  256.                     ];
  257.                 }
  258.                 $cars[] = [
  259.                     'id' => $car->getId(),
  260.                     'title' => $car->getBrand() . ' ' $car->getModel(),
  261.                     'MakeYear' => $car->getYearOfProduction(),
  262.                     'Number' => $car->getNumber(),
  263.                     'dealer' => $dealersData,
  264.                     'VIN' => $car->getVin(),
  265.                     'brandId' => $car->getCarModel()->getBrand()->getId(),
  266.                     'modelId' => $car->getCarModel()->getId(),
  267.                     'variationId' => $car->getServiceVariation() ? $car->getServiceVariation()->getId() : null,
  268.                 ];
  269.             }
  270.             $userData = [
  271.                 'id' => $User->getId(),
  272.                 'name' => $User->getFullName(),
  273.                 'email' => $User->getEmail(),
  274.                 'phone' => $User->getPhone(),
  275.                 'cars' => $cars,
  276.             ];
  277.         } else {
  278.             $userData = [
  279.                 'id' => null,
  280.                 'name' => null,
  281.                 'email' => null,
  282.                 'phone' => null,
  283.                 'cars' => [],
  284.             ];
  285.         }
  286.         return $userData;
  287.     }
  288.     public function findVariation(Request $request): JsonResponse
  289.     {
  290.         $dealerId $request->get('dealerId');
  291.         $modelId $request->get('modelId');
  292.         $byGroup $request->get('byGroup');
  293.         if (!$dealerId) {
  294.             throw new NotFoundHttpException();
  295.         }
  296.         $Dealer $this->em->getRepository(Dealer::class)->find($dealerId);
  297.         if ($byGroup) {
  298.             $variationsResult = [];
  299.             $variations $this->em->getRepository(ServiceVariation::class)->findBy(['dealer' => $Dealer'model' => $modelId'is_delete' => [0null]], ['year_from' => 'ASC']);
  300.             /** @var ServiceVariation $row */
  301.             foreach ($variations as $row) {
  302.                 if (!$row->getFuelType()) {
  303.                     continue;
  304.                 }
  305.                 $key $row->getYearFrom() . ' - ' . ('...');
  306.                 if ($row->getYearTo()) {
  307.                     $key $row->getYearFrom() . ' - ' . ($row->getYearTo());
  308.                 }
  309.                 if (!isset($variationsResult[$key])) {
  310.                     $variationsResult[$key] = [
  311.                         'period' => $key,
  312.                         'from' => $row->getYearFrom(),
  313.                         'to' => $row->getYearTo() ?: (new DateTime())->format('Y'),
  314.                         'image' => null,
  315.                         'items' => [],
  316.                     ];
  317.                 }
  318.                 $vImage $row->getImage();
  319.                 if (!$variationsResult[$key]['image'] && $vImage) {
  320.                     $variationsResult[$key]['image'] = $this->mediaExtensionVidi->getPath($vImage'reference');
  321.                 }
  322.                 $transmission false;
  323.                 if ($row->getTransmissionType()) {
  324.                     $transmission $row->getTransmissionType()->getValue($request->getLocale());
  325.                 }
  326.                 if ($transmission && $row->getTransmissionStepCount()) {
  327.                     $transmission .= ', ' $row->getTransmissionStepCount() . ' ст.';
  328.                 }
  329.                 $volume $row->getEngineVolume();
  330.                 if ($volume 200) {
  331.                     $volume number_format(round($volume 10001), 1'.''');
  332.                 }
  333.                 $variationsResult[$key]['items'][] = [
  334.                     'id' => $row->getId(),
  335.                     'capacity' => $volume,
  336.                     'drive' => $row->getDriveUnit() ? $row->getDriveUnit()->getValue($request->getLocale()) : null,
  337.                     'driveId' => $row->getDriveUnit() ? $row->getDriveUnit()->getId() : null,
  338.                     'fuel' => $row->getFuelType()->getValue($request->getLocale()),
  339.                     'fuelId' => $row->getFuelType()->getId(),
  340.                     'transmission' => $transmission,
  341.                     'engineName' => $row->getEngineName(),
  342.                     'emission' => $row->getEmission(),
  343.                     'transmissionId' => $row->getTransmissionType() ? $row->getTransmissionType()->getId() : null,
  344.                     'power' => $row->getPower(),
  345.                     'form' => $row->getYearFrom(),
  346.                     'to' => $row->getYearTo() ?: '...',
  347.                     'description' => $row->getDescription(),
  348.                 ];
  349.             }
  350.             foreach ($variationsResult as &$row) {
  351.                 if (!$row['image']) {
  352.                     $row['image'] = $this->mediaExtensionVidi->getPath($Dealer->getBrand()->getLogo(), 'reference');
  353.                 }
  354.             }
  355.             return new JsonResponse(['variations' => $variationsResult]);
  356.         }
  357.         $year $request->get('MakeYear');
  358.         $SaleMonth $request->get('SaleMonth');
  359.         $SaleYear $request->get('SaleYear');
  360.         $SaleData null;
  361.         if ($SaleMonth && $SaleYear) {
  362.             $SaleData = new DateTime($SaleYear '-' $SaleMonth '-01');
  363.         }
  364.         $variationsResult = [];
  365.         $variations $this->em->getRepository(ServiceVariation::class)->getByCarParams($Dealer->getId(), $modelId$year$SaleData);
  366.         /** @var ServiceVariation $row */
  367.         foreach ($variations as $row) {
  368.             $transmission false;
  369.             if ($row->getTransmissionType()) {
  370.                 $transmission $row->getTransmissionType()->getValue($request->getLocale());
  371.             }
  372.             if ($transmission && $row->getTransmissionStepCount()) {
  373.                 $transmission .= ', ' $row->getTransmissionStepCount() . ' ст.';
  374.             }
  375.             $variationsResult[] = [
  376.                 'id' => $row->getId(),
  377.                 'capacity' => $row->getEngineVolume(),
  378.                 'drive' => $row->getDriveUnit() ? $row->getDriveUnit()->getValue($request->getLocale()) : null,
  379.                 'driveId' => $row->getDriveUnit() ? $row->getDriveUnit()->getId() : null,
  380.                 'fuel' => $row->getFuelType()->getValue($request->getLocale()),
  381.                 'fuelId' => $row->getFuelType()->getId(),
  382.                 'transmission' => $transmission,
  383.                 'engineName' => $row->getEngineName(),
  384.                 'transmissionId' => $row->getTransmissionType() ? $row->getTransmissionType()->getId() : null,
  385.                 'power' => $row->getPower(),
  386.                 'form' => $row->getYearFrom(),
  387.                 'to' => $row->getYearTo() ?: '...',
  388.             ];
  389.         }
  390.         return new JsonResponse(['variations' => $variationsResult]);
  391.     }
  392.     public function findVariationBy(Request $request): JsonResponse
  393.     {
  394.         $dealerId $request->get('dealerId');
  395.         $modelId $request->get('modelId');
  396.         $variationsResult = [];
  397.         $Dealer $this->em->getRepository(Dealer::class)->find($dealerId);
  398.         $variations $this->em->getRepository(ServiceVariation::class)->findBy(['dealer' => $Dealer'model' => $modelId'is_delete' => [0null]], ['year_from' => 'ASC']);
  399.         /** @var ServiceVariation $row */
  400.         foreach ($variations as $row) {
  401.             if (!$row->getFuelType()) {
  402.                 continue;
  403.             }
  404.             $transmission false;
  405.             $to = (new DateTime())->format('Y');
  406.             if ($row->getTransmissionType()) {
  407.                 $transmission $row->getTransmissionType()->getValue($request->getLocale());
  408.             }
  409.             if ($transmission && $row->getTransmissionStepCount()) {
  410.                 $transmission .= ', ' $row->getTransmissionStepCount() . ' ст.';
  411.             }
  412.             $volume $row->getEngineVolume();
  413.             if ($volume 200) {
  414.                 $volume number_format(round($volume 10001), 1'.''');
  415.             }
  416.             if ($row->getYearTo()) {
  417.                 $to $row->getYearTo();
  418.             }
  419.             $variationsResult[] = [
  420.                 'id' => $row->getId(),
  421.                 'dealerId' => (int)$dealerId,
  422.                 'modelId' => (int)$modelId,
  423.                 'capacityId' => $row->getEngineVolume(),
  424.                 'capacity' => $volume,
  425.                 'driveId' => $row->getDriveUnit() ? $row->getDriveUnit()->getId() : null,
  426.                 'driveUnit' => $row->getDriveUnit() ? $row->getDriveUnit()->getValue($request->getLocale()) : null,
  427.                 'fuelId' => $row->getFuelType()->getId(),
  428.                 'fuelType' => $row->getFuelType()->getValue($request->getLocale()),
  429.                 'transmissionId' => $row->getTransmissionType() ? $row->getTransmissionType()->getId() : null,
  430.                 'transmissionType' => $transmission,
  431.                 'engineName' => $row->getEngineName(),
  432.                 'emission' => $row->getEmission(),
  433.                 'power' => $row->getPower(),
  434.                 'year' => $row->getYearFrom() . ' - ' $to,
  435.             ];
  436.         }
  437.         return new JsonResponse(['variations' => $variationsResult]);
  438.     }
  439.     private function checkModel(Brand $brand$modelStr)
  440.     {
  441.         $models $brand->getModels();
  442.         /** @var Model $model */
  443.         foreach ($models as $model) {
  444.             $modelTitle str_replace(' '''$model->getTitle());
  445.             $modelTitle str_replace('-'''$modelTitle);
  446.             $modelTitle strtolower($modelTitle);
  447.             $modelStr str_replace(' '''$modelStr);
  448.             $modelStr str_replace('-'''$modelStr);
  449.             $modelStr strtolower($modelStr);
  450.             if ($modelTitle == $modelStr) {
  451.                 return $model;
  452.             }
  453.         }
  454.         /** @var Model $model */
  455.         foreach ($models as $model) {
  456.             $modelTitle str_replace(' '''$model->getTitle());
  457.             $modelTitle str_replace('-'''$modelTitle);
  458.             $modelTitle strtolower($modelTitle);
  459.             $modelStr str_replace(' '''$modelStr);
  460.             $modelStr str_replace('-'''$modelStr);
  461.             $modelStr strtolower($modelStr);
  462.             if ($modelTitle && $modelTitle !== '' && strpos($modelStr$modelTitle) !== false) {
  463.                 return $model;
  464.             }
  465.             if (strpos($modelTitle$modelStr) !== false) {
  466.                 return $model;
  467.             }
  468.         }
  469.         return false;
  470.     }
  471.     public function find(Request $requestMvdServer $mvdServerApiServer1C $apiServer1C): JsonResponse
  472.     {
  473.         $responseData = [];
  474.         $num $request->get('number');
  475.         $carData $mvdServer->getCarInfoByNumber($numnull$request->getLocale());
  476.         $dealer false;
  477.         try {
  478.             $dealer $this->getDealer($request->get('dealerId'));
  479.         } catch (NotFoundHttpException $e) {
  480.         }
  481.         $apiData false;
  482.         if ($dealer) {
  483.             $apiData $apiServer1C->getCarInfoByVin(['VIN' => $carData['VIN']], $dealer);
  484.         }
  485.         if (!$carData) {
  486.             return new JsonResponse(['car' => false]);
  487.         }
  488.         $brandStr $carData['Brand'];
  489.         $brand $this->em->getRepository(Brand::class)->getByName($brandStr);
  490.         if (!$brand) {
  491.             $brand = new Brand();
  492.             $brand->setName(ucfirst(mb_strtolower($brandStr)));
  493.             $this->em->persist($brand);
  494.             $this->em->flush();
  495.         }
  496.         $modelStr $carData['Model'];
  497.         //TODO ForBrand Lexus
  498.         if ($brand->getId() == 5) {
  499.             $modelStr preg_replace('/[\d\s]/'''$carData['Model']);
  500.         }
  501.         $model $this->em->getRepository(Model::class)->getByMVDName($modelStr$brand->getId(), $dealer);
  502.         if (!$model) {
  503.             $model $this->checkModel($brand$modelStr);
  504.         }
  505.         if (!$model) {
  506.             $model = new Model();
  507.             $model->setBrand($brand);
  508.             $model->setTitle($modelStr);
  509.             $model->setIsAutocreate(1);
  510.             $this->em->persist($model);
  511.             $this->em->flush();
  512.         }
  513.         $carData['BrandInfo'] = [
  514.             'id' => $brand->getId(),
  515.             'name' => $brand->getName(),
  516.         ];
  517.         $carData['ModelInfo'] = [
  518.             'id' => $model->getId(),
  519.             'name' => $model->getTitle(),
  520.         ];
  521.         $modelImg null;
  522.         if ($model->getImage()) {
  523.             $modelImg $this->mediaExtensionVidi->getPath($model->getImage(), 'reference');
  524.         }
  525.         $carData['ModelImg'] = $modelImg;
  526.         $carData['ModelUrl'] = $model->getUrl();
  527.         $carData['ModelName'] = "{$carData['Brand']} {$carData['Model']} {$carData['MakeYear']}";
  528.         $responseData['car'] = $carData;
  529.         $fuelId null;
  530.         if (isset($carData['FuelInfo']) && isset($carData['FuelInfo']['id'])) {
  531.             $fuelId $carData['FuelInfo']['id'];
  532.         }
  533.         if (!$dealer) {
  534.             $brands = [];
  535.             $dealers $brand->getDealer();
  536.             if (count($dealers) == 1) {
  537.                 $dealer $dealers->first();
  538.                 $responseData['brands'][] = [
  539.                     'id' => $brand->getId(),
  540.                     'name' => $brand->getName(),
  541.                     'image' => $this->mediaExtensionVidi->getPath($brand->getImage(), 'menu'),
  542.                     'dealerId' => $dealers->first()->getId()
  543.                 ];
  544.             } else {
  545.                 if (count($dealers)) {
  546.                     $item = [
  547.                         'id' => $brand->getId(),
  548.                         'name' => $brand->getName(),
  549.                         'image' => $this->mediaExtensionVidi->getPath($brand->getLogo(), 'menu'),
  550.                     ];
  551.                     foreach ($dealers as $row) {
  552.                         $item['dealers'][] = [
  553.                             'id' => $row->getId(),
  554.                             'title' => $row->getNameByLocale($request->getLocale()),
  555.                             'adres' => $row->getAddressByLocale($request->getLocale()),
  556.                         ];
  557.                     }
  558.                     $brands[] = $item;
  559.                 } else {
  560.                     $brands $this->vehicleRepository->getAvailBrandsInstance($request->getLocale());
  561.                     foreach ($brands as &$item) {
  562.                         $item['image'] = $this->mediaExtensionVidi->getPath($item['image'], 'menu');
  563.                     }
  564.                 }
  565.                 $responseData['brands'] = $brands;
  566.                 return new JsonResponse($responseData);
  567.             }
  568.         }
  569.         $variations false;
  570.         $variationsResult = [];
  571.         $currentVariation null;
  572.         if ($apiData && $apiData->VariationID) {
  573.             $currentVariation $this->em->getRepository(ServiceVariation::class)->findOneBy(['uid_1c' => $apiData->VariationID'dealer' => $dealer]);
  574.             if ($currentVariation) {
  575.                 $variations[] = $currentVariation;
  576.             }
  577.         }
  578.         if (!$variations && $dealer->getBrand()->getId() == $brand->getId()) {
  579.             $variations $this->em->getRepository(ServiceVariation::class)
  580.                 ->getByCarParams(
  581.                     $dealer->getId(),
  582.                     $model->getId(),
  583.                     $carData['MakeYear'],
  584.                     null,
  585.                     $fuelId,
  586.                     $carData['Capacity']
  587.                 );
  588.         }
  589.         if (!empty($variations)) {
  590.             /** @var ServiceVariation $row */
  591.             foreach ($variations as $row) {
  592.                 $transmission null;
  593.                 $drive null;
  594.                 $driveId null;
  595.                 $to '...';
  596.                 $toYear = (new DateTime())->format('Y');
  597.                 $transmission false;
  598.                 if ($row->getTransmissionType()) {
  599.                     $transmission $row->getTransmissionType()->getValue($request->getLocale());
  600.                 }
  601.                 if ($transmission && $row->getTransmissionStepCount()) {
  602.                     $transmission .= ', ' $row->getTransmissionStepCount() . ' ст.';
  603.                 }
  604.                 if ($row->getDriveUnit()) {
  605.                     $drive $row->getDriveUnit()->getValue($request->getLocale());
  606.                 }
  607.                 $driveId = ($row->getDriveUnit()) ? $row->getDriveUnit()->getId() : $row->getDriveUnit();
  608.                 $transmissionId = ($row->getTransmissionType()) ? $row->getTransmissionType()->getId() : $row->getTransmissionType();
  609.                 if ($row->getYearTo()) {
  610.                     $to $toYear $row->getYearTo();
  611.                 }
  612.                 $volume $row->getEngineVolume();
  613.                 if ($volume 200) {
  614.                     $volume number_format(round($volume 10001), 1'.''');
  615.                 }
  616.                 $variationsResult[] = [
  617.                     'id' => $row->getId(),
  618.                     'capacity' => $volume,
  619.                     'drive' => $drive,
  620.                     'driveId' => $driveId,
  621.                     'fuel' => $row->getFuelType()->getValue($request->getLocale()),
  622.                     'fuelId' => $row->getFuelType()->getId(),
  623.                     'transmission' => $transmission,
  624.                     'emission' => $row->getEmission(),
  625.                     'transmissionId' => $transmissionId,
  626.                     'power' => $row->getPower(),
  627.                     'form' => $row->getYearFrom(),
  628.                     'to' => $to,
  629.                     'year' => $row->getYearFrom() . ' - ' $toYear,
  630.                 ];
  631.             }
  632.         }
  633.         $responseData['variations'] = $variationsResult;
  634.         if ($dealer) {
  635.             $responseData['dealerId'] = $dealer->getId();
  636.         }
  637.         return new JsonResponse($responseData);
  638.     }
  639.     public function saveCar(Request $request): JsonResponse
  640.     {
  641.         $User $this->getUser();
  642.         if (!($User instanceof User)) {
  643.             return new JsonResponse(['success' => false]);
  644.         }
  645.         $vin $request->get('VIN');
  646.         $UserCar $this->em->getRepository(UserCar::class)->findOneBy(['vin' => $vin]);
  647.         $number $request->get('Number');
  648.         if ($number) {
  649.             $UserCar $this->em->getRepository(UserCar::class)->findOneBy(['is_deleted' => [0null], 'number' => $number]);
  650.         }
  651.         if (!$UserCar) {
  652.             $UserCar = new UserCar();
  653.         }
  654.         $UserCar->setUser($User);
  655.         $UserCar->setVin($request->get('VIN'));
  656.         $modelId $request->get('modelId');
  657.         $Model false;
  658.         if ($modelId) {
  659.             $Model $this->em->getRepository(Model::class)->find($modelId);
  660.         }
  661.         if (!$Model) {
  662.             return new JsonResponse(['success' => false]);
  663.         }
  664.         /** @var Brand $Brand */
  665.         $Brand $Model->getBrand();
  666.         $UserCar->setIsDeleted(0);
  667.         $UserCar->setBrand($Brand->getName());
  668.         $UserCar->setModel($Model->getTitle());
  669.         $UserCar->setCarModel($Model);
  670.         $UserCar->setYearOfProduction($request->get('MakeYear'));
  671.         $UserCar->setNumber($request->get('Number'));
  672.         $Variation false;
  673.         $variationId $request->get('variationId');
  674.         if ($variationId) {
  675.             $Variation $this->em->getRepository(ServiceVariation::class)->find($variationId);
  676.         }
  677.         if ($Variation) {
  678.             $UserCar->setServiceVariation($Variation);
  679.         }
  680.         $this->em->persist($UserCar);
  681.         $this->em->flush();
  682.         return new JsonResponse(['success' => true]);
  683.     }
  684.     public function byModel(Request $request): JsonResponse
  685.     {
  686.         $locale $request->getLocale();
  687.         $variationId $request->get('variationId');
  688.         $Variation null;
  689.         if ($variationId) {
  690.             $Variation $this->em->getRepository(ServiceVariation::class)->find($variationId);
  691.         }
  692.         $Dealer $this->getDealer($request->get('dealerId'));
  693.         $works $this->em->getRepository(ServiceWork::class)->findByVariation($Variation$Dealer);
  694.         $groupsArray = [];
  695.         /** @var ServiceWork $work */
  696.         foreach ($works as $work) {
  697.             $Group $this->getWorkGroup($work->getGroup());
  698.             if (!$Group) {
  699.                 continue;
  700.             }
  701.             $groupsArray[$Group->getId()] = [
  702.                 'id' => $Group->getId(),
  703.                 'title' => $Group->getTitle($request->getLocale()),
  704.                 'position' => $Group->getPosition(),
  705.                 'groups' => [
  706.                     [
  707.                         'id' => $Group->getId(),
  708.                         'title' => $Group->getTitle($request->getLocale()),
  709.                     ]
  710.                 ],
  711.             ];
  712.         }
  713.         usort($groupsArray, fn($a$b) => $a['position'] <=> $b['position']);
  714.         $worksArray = [];
  715.         /** @var ServiceWork $work */
  716.         foreach ($works as $work) {
  717.             $Group $this->getWorkGroup($work->getGroup());
  718.             if (!$Group) {
  719.                 continue;
  720.             }
  721.             $groupId $Group->getId();
  722.             if (!isset($worksArray[$groupId])) {
  723.                 $worksArray[$groupId] = [
  724.                     'id' => $groupId,
  725.                     'title' => $Group->getTitle($request->getLocale()),
  726.                     'works' => [],
  727.                 ];
  728.             }
  729.             $workItem = [
  730.                 'id' => $work->getId(),
  731.                 'groupId' => $groupId,
  732.                 'position' => $work->getPosition(),
  733.                 'isRegulation' => $work->getIsRegulations(),
  734.                 'millage' => $work->getMileage(),
  735.                 'title' => $work->getTitle($request->getLocale()),
  736.                 'totalCost' => 0,
  737.                 'worksCost' => 0,
  738.                 'partsCost' => 0,
  739.                 'time' => 0,
  740.                 'works' => [],
  741.                 'parts' => [],
  742.             ];
  743.             /** @var ServiceWorkJob $rJob */
  744.             foreach ($work->getJobs() as $rJob) {
  745.                 $workItem['works'][] = [
  746.                     'title' => $rJob->getJob()->getNameByLocale($locale),
  747.                     'hours' => $rJob->getJobHours(),
  748.                     'price' => round($rJob->getPrice()),
  749.                 ];
  750.                 $workItem['worksCost'] += $rJob->getPrice();
  751.                 $workItem['time'] += $rJob->getJobHours();
  752.             }
  753.             /** @var ServiceWorkPart $rPart */
  754.             foreach ($work->getParts() as $rPart) {
  755.                 if (empty($rPart->getPrice())) {
  756.                     $cost round($rPart->getCount() * $rPart->getPart()->getPrice());
  757.                 } else {
  758.                     $cost round($rPart->getCount() * $rPart->getPrice());
  759.                 }
  760.                 $workItem['parts'][] = [
  761.                     'title' => $rPart->getPart()->getNameByLocale($locale),
  762.                     'count' => $rPart->getCount(),
  763.                     'unit' => $rPart->getUnits()->getShort($locale),
  764.                     'price' => round($cost),
  765.                 ];
  766.                 $workItem['partsCost'] += $cost;
  767.             }
  768.             $workItem['time'] = round($workItem['time'], 2);
  769.             $workItem['worksCost'] = round($workItem['worksCost']);
  770.             $workItem['partsCost'] = round($workItem['partsCost']);
  771.             $workItem['totalCost'] = round($workItem['partsCost'] + $workItem['worksCost']);
  772.             $worksArray[$groupId]['works'][] = $workItem;
  773.         }
  774.         foreach ($worksArray as &$row) {
  775.             usort($row['works'], function ($a$b) {
  776.                 $aVal $a['isRegulation'] ? $a['millage'] : $a['position'];
  777.                 $bVal $b['isRegulation'] ? $b['millage'] : $b['position'];
  778.                 return $aVal <=> $bVal;
  779.             });
  780.         }
  781.         return $this->json(['success' => true'works' => $worksArray'groups' => $groupsArray]);
  782.     }
  783.     private function getWorkGroup($Group)
  784.     {
  785.         if (!$Group) {
  786.             return false;
  787.         }
  788.         if (!$Group->getParent()) {
  789.             return $Group;
  790.         }
  791.         $ParentGroup $Group->getParent();
  792.         //Якщо аксессуари
  793.         if ($ParentGroup->getUid() == 'eb2b75eb-4a5d-11ef-ac14-005056a799b6') {
  794.             return $ParentGroup;
  795.         }
  796.         if (!$ParentGroup->getParent()) {
  797.             return $Group;
  798.         }
  799.         return $this->getWorkGroup($ParentGroup);
  800.     }
  801.     public function getWorksByModel(Request $request): JsonResponse
  802.     {
  803.         $locale $request->getLocale();
  804.         $variationId $request->get('variationId');
  805.         $Variation null;
  806.         if ($variationId) {
  807.             $Variation $this->em->getRepository(ServiceVariation::class)->find($variationId);
  808.         }
  809.         $Dealer $this->getDealer($request->get('dealerId'));
  810.         $works $this->em->getRepository(ServiceWork::class)->findByVariation($Variation$Dealer);
  811.         $serviceGroupArray = [];
  812.         $serviceWorksArray = [];
  813.         /** @var ServiceWork $work */
  814.         foreach ($works as $work) {
  815.             $Group $this->getWorkGroup($work->getGroup());
  816.             if (!$Group || $Group->getUid() == 'eb2b75eb-4a5d-11ef-ac14-005056a799b6') {
  817.                 continue;
  818.             }
  819.             $serviceGroupArray[$Group->getId()] = [
  820.                 'id' => $Group->getId(),
  821.                 'title' => $Group->getTitle($request->getLocale()),
  822.                 'position' => $Group->getPosition(),
  823.                 'groups' => [
  824.                     [
  825.                         'id' => $Group->getId(),
  826.                         'title' => $Group->getTitle($request->getLocale()),
  827.                     ]
  828.                 ],
  829.             ];
  830.             $workItem = [
  831.                 'id' => $work->getId(),
  832.                 'title' => $work->getTitle($locale),
  833.                 'groupId' => $Group->getId(),
  834.                 'parentGroupId' => $Group->getId(),
  835.                 'position' => $work->getPosition(),
  836.                 'isRegulation' => $work->getIsRegulations(),
  837.                 'millage' => $work->getMileage(),
  838.                 'totalCost' => 0,
  839.                 'worksCost' => 0,
  840.                 'partsCost' => 0,
  841.                 'time' => 0,
  842.                 'works' => [],
  843.                 'parts' => [],
  844.             ];
  845.             /** @var ServiceWorkJob $wJob */
  846.             foreach ($work->getJobs() as $wJob) {
  847.                 $workItem['works'][] = [
  848.                     'title' => $wJob->getJob()->getNameByLocale($locale),
  849.                     'hours' => $wJob->getJobHours(),
  850.                     'price' => round($wJob->getPrice()),
  851.                 ];
  852.                 $workItem['worksCost'] += $wJob->getPrice();
  853.                 $workItem['time'] += $wJob->getJobHours();
  854.             }
  855.             /** @var ServiceWorkPart $wPart */
  856.             foreach ($work->getParts() as $wPart) {
  857.                 if (empty($wPart->getPrice())) {
  858.                     $cost round($wPart->getCount() * $wPart->getPart()->getPrice());
  859.                 } else {
  860.                     $cost round($wPart->getCount() * $wPart->getPrice());
  861.                 }
  862.                 $workItem['parts'][] = [
  863.                     'title' => $wPart->getPart()->getNameByLocale($locale),
  864.                     'count' => $wPart->getCount(),
  865.                     'unit' => $wPart->getUnits()->getShort($locale),
  866.                     'price' => round($cost),
  867.                 ];
  868.                 $workItem['partsCost'] += $cost;
  869.             }
  870.             $workItem['time'] = round($workItem['time'], 2);
  871.             $workItem['worksCost'] = round($workItem['worksCost']);
  872.             $workItem['partsCost'] = round($workItem['partsCost']);
  873.             $workItem['totalCost'] = round($workItem['partsCost'] + $workItem['worksCost']);
  874.             $serviceWorksArray[] = $workItem;
  875.         }
  876.         usort($serviceGroupArray, fn($a$b) => $a['position'] <=> $b['position']);
  877.         return $this->json(['success' => true'groups' => $serviceGroupArray'works' => $serviceWorksArray]);
  878.     }
  879.     public function getTime(Request $requestApiServer1C $apiServer1CTranslatorInterface $translator): JsonResponse
  880.     {
  881.         $date = new DateTime($request->get('date'));
  882.         $Dealer $this->getDealer($request->get('dealerId'));
  883.         $works $request->request->all('works');
  884.         $worksArray = [];
  885.         $servicesWorks $this->em->getRepository(ServiceWork::class)->findBy(['id' => $works]);
  886.         /** @var ServiceWork $servicesWork */
  887.         foreach ($servicesWorks as $servicesWork) {
  888.             /** @var ServiceWorkJob $job */
  889.             foreach ($servicesWork->getJobs() as $job) {
  890.                 $worksArray[] = [
  891.                     'WorkID' => $job->getJob()->getUid(),
  892.                     'Count' => $job->getJobHours(),
  893.                 ];
  894.             }
  895.         }
  896.         $times $apiServer1C->getTimes($date$Dealer$worksArray);
  897.         if (!$times) {
  898.             return new JsonResponse(['success' => false'error' => [
  899.                 'title' => $translator->trans('modules.online-booking.time-error-title', [], 'dc_base'),
  900.                 'text' => $translator->trans('modules.online-booking.time-error-text', [], 'dc_base'),
  901.             ]]);
  902.         }
  903.         $result = [];
  904.         foreach ($times as $time) {
  905.             $tDate = new DateTime((string)$time->StartDate);
  906.             $result[] = $tDate->format('H:i');
  907.         }
  908.         return new JsonResponse(['success' => true'time' => (array)$result]);
  909.     }
  910.     public function bookingConfirm(Request          $requestApiServer1C $apiServer1CTranslatorInterface $translator,
  911.                                    InfobipSmsSender $infobipSmsSenderNightBookingService $nightBookingService): JsonResponse
  912.     {
  913.         $code $request->get('confirmCode');
  914.         $id $request->get('bookingId');
  915.         $isNight filter_var($request->get('isNight'), FILTER_VALIDATE_BOOLEAN);
  916.         $User null;
  917.         $UserCar null;
  918.         $selectedConnectionType $request->get('selectedConnectionType');
  919.         $selectedMobilityService $request->get('selectedMobilityService');
  920.         $toGoService strtolower($request->get('toGoService')) === 'false' false true;
  921.         try {
  922.             if ($isNight) {
  923.                 $User $this->getUserNight($request);
  924.                 $UserCar $this->getUserCarNight($request$User);
  925.             }
  926.         } catch (Exception $e) {
  927.             return new JsonResponse(
  928.                 [
  929.                     'success' => false,
  930.                     'error' =>
  931.                         [
  932.                             'title' => $translator->trans('modules.online-booking.booking-error-2-title', [], 'dc_base'),
  933.                             'text' => $translator->trans('modules.online-booking.booking-total-text', [], 'dc_base'),
  934.                             'message' => $e->getMessage()
  935.                         ]
  936.                 ]
  937.             );
  938.         }
  939.         /** @var OnlineServiceBooking $onlineBookingEntity */
  940.         $onlineBookingEntity $this->em->getRepository(OnlineServiceBooking::class)->find($id);
  941.         if (!$onlineBookingEntity) {
  942.             return new JsonResponse(
  943.                 [
  944.                     'success' => false,
  945.                     'error' =>
  946.                         [
  947.                             'title' => $translator->trans('modules.online-booking.time-error-title', [], 'dc_base'),
  948.                             'text' => $translator->trans('modules.online-booking.booking-total-text', [], 'dc_base'),
  949.                         ]
  950.                 ]
  951.             );
  952.         }
  953.         if ($onlineBookingEntity->getConfirmCode() != $code) {
  954.             return new JsonResponse(
  955.                 [
  956.                     'success' => false,
  957.                     'error' =>
  958.                         [
  959.                             'title' => $translator->trans('modules.online-booking.time-error-title', [], 'dc_base'),
  960.                             'text' => $translator->trans('modules.online-booking.confirm-code-error', [], 'dc_base'),
  961.                         ]
  962.                 ]
  963.             );
  964.         }
  965.         $worksArray = [];
  966.         /** @var OnlineServiceBookingWorks $work */
  967.         foreach ($onlineBookingEntity->getWorks() as $work) {
  968.             $worksArray[] = [
  969.                 'WorkID' => $work->getJob()->getUid(),
  970.                 'Count' => $work->getTime(),
  971.             ];
  972.         }
  973.         $car json_decode($onlineBookingEntity->getCarData(), true);
  974.         $carVinCode null;
  975.         if (isset($car['VIN'])) {
  976.             $carVinCode $car['VIN'];
  977.         }
  978.         $visitDate $onlineBookingEntity->getVisitDate()->format('d.m.Y H:i:s');
  979.         $comment sprintf("%s %s %s, %s %s, %s %s",
  980.             $onlineBookingEntity->getComment(),
  981.             ' Послуга мобільності - '$selectedMobilityService,
  982.             "Спосіб зв`язку - "$selectedConnectionType,
  983.             "Послуга To Go - "$toGoService 'Так' 'Ні'
  984.         );
  985.         $data = [
  986.             'CustomerID' => null,
  987.             'CustomerName' => $onlineBookingEntity->getName(),
  988.             'PhoneMobile' => $onlineBookingEntity->getPhone(),
  989.             'VehicleID' => null,
  990.             'VehicleDescriptin' => $car['title'] . ' ' $car['MakeYear'],
  991.             'VIN' => $carVinCode,
  992.             'Date' => $onlineBookingEntity->getVisitDate()->format('d.m.Y H:i:s'),
  993.             'Works' => $worksArray,
  994.             'Comment' => $comment,
  995.             'isNight' => filter_var($request->get('isNight'), FILTER_VALIDATE_BOOLEAN)
  996.         ];
  997.         $dealer $this->getDealer($request->get('dealerId'));
  998.         $resultBooking $apiServer1C->booking($data$dealer);
  999.         if ($resultBooking->Code != 0) {
  1000.             switch ((int)$resultBooking->Code) {
  1001.                 //TODO need some documentation
  1002.                 case 2:
  1003.                 case 5:
  1004.                     $error = [
  1005.                         'title' => $translator->trans('modules.online-booking.booking-error-2-title', [], 'dc_base'),
  1006.                         'text' => $translator->trans('modules.online-booking.booking-error-2-text', [], 'dc_base'),
  1007.                     ];
  1008.                     break;
  1009.                 default:
  1010.                     $error = [
  1011.                         'title' => $translator->trans('modules.online-booking.time-error-title', [], 'dc_base'),
  1012.                         'text' => $translator->trans('modules.online-booking.booking-total-text', [], 'dc_base'),
  1013.                     ];
  1014.                     break;
  1015.             }
  1016.             return new JsonResponse(['success' => false'code' => (int)$resultBooking->Code'error' => $error]);
  1017.         }
  1018.         try {
  1019.             if ($isNight) {
  1020.                 $result $nightBookingService->addToBookingForService($User$dealer, (string)$resultBooking->Data->RegistrationID$visitDate$UserCar);
  1021.                 if (!$result['success']) {
  1022.                     throw new Exception($result['error']);
  1023.                 }
  1024.                 $infobipSmsSender->sendSms($User->getPhone(), "Ваша заявка на нічне приймання {$result['href']}");
  1025.             }
  1026.         } catch (Exception $e) {
  1027.             return new JsonResponse(
  1028.                 [
  1029.                     'success' => false,
  1030.                     'error' =>
  1031.                         [
  1032.                             'title' => $translator->trans('modules.online-booking.booking-error-2-title', [], 'dc_base'),
  1033.                             'text' => $translator->trans('modules.online-booking.booking-total-text', [], 'dc_base'),
  1034.                             'message' => $e->getMessage()
  1035.                         ]
  1036.                 ]
  1037.             );
  1038.         }
  1039.         $onlineBookingEntity->setDealer($dealer);
  1040.         $onlineBookingEntity->setBookingUid((string)$resultBooking->Data->RegistrationID);
  1041.         $onlineBookingEntity->setIsSend(1);
  1042.         $this->em->persist($onlineBookingEntity);
  1043.         $this->em->flush();
  1044.         return new JsonResponse(['success' => true'message' => [
  1045.             'title' => $translator->trans('modules.online-booking.booking-success-title', [], 'dc_base'),
  1046.             'text' => $translator->trans('modules.online-booking.booking-success-text', [], 'dc_base'),
  1047.         ]]);
  1048.     }
  1049.     public function booking(Request          $requestTranslatorInterface $translatorInfobipSmsSender $infobipSmsSenderb,
  1050.                             OtpCodeGenerator $otpCodeGenerator): JsonResponse
  1051.     {
  1052.         $car $request->get('car');
  1053.         $userData $request->get('user');
  1054.         $user $this->getUser();
  1055.         $works $request->get('works');
  1056.         $comment $request->get('comment');
  1057.         $date $request->get('date');
  1058.         $phone $userData['phone'];
  1059.         $selectedConnectionType $request->get('selectedConnectionType');
  1060.         $selectedMobilityService $request->get('selectedMobilityService');
  1061.         $toGoService strtolower($request->get('toGoService')) === 'false' false true;
  1062.         $senderCode = (is_null($request->get('senderCode'))) ? true boolval($request->get('senderCode'));
  1063.         $dateInst = new DateTime($date);
  1064.         $dealer $this->getDealer($request->get('dealerId'));
  1065.         $onlineBookingEntity $this->em->getRepository(OnlineServiceBooking::class)
  1066.             ->getByDate($dateInst$phone$user$dealer);
  1067.         if ($onlineBookingEntity) {
  1068.             return new JsonResponse(
  1069.                 [
  1070.                     'success' => false,
  1071.                     'error' =>
  1072.                         [
  1073.                             'title' => $translator->trans('modules.online-booking.time-error-title', [], 'dc_base'),
  1074.                             'text' => $translator->trans('modules.online-booking.today-double', [], 'dc_base'),
  1075.                         ]
  1076.                 ]
  1077.             );
  1078.         }
  1079.         $id $request->get('bookingId');
  1080.         $onlineBookingEntity $this->em->getRepository(OnlineServiceBooking::class)->find($id);
  1081.         if (!$onlineBookingEntity) {
  1082.             $onlineBookingEntity = new OnlineServiceBooking();
  1083.             $onlineBookingEntity->setReferrer($request->get('referrer'));
  1084.             $onlineBookingEntity->setHref($request->get('href'));
  1085.             $onlineBookingEntity->setUtm($request->get('utm'));
  1086.             $onlineBookingEntity->setGclId($request->get('gcl_id'));
  1087.         }
  1088.         $onlineBookingEntity->setNotifySend(0);
  1089.         $onlineBookingEntity->setDateCreate(new DateTime());
  1090.         $onlineBookingEntity->setName($userData['name']);
  1091.         if (isset($userData['email'])) {
  1092.             $onlineBookingEntity->setEmail($userData['email']);
  1093.         }
  1094.         $onlineBookingEntity->setPhone($phone);
  1095.         $onlineBookingEntity->setIsSend(0);
  1096.         $code $otpCodeGenerator->generateCustomLength(4);
  1097.         $onlineBookingEntity->setConfirmCode($code);
  1098.         $onlineBookingEntity->setVisitDate($dateInst);
  1099.         $onlineBookingEntity->setDealer($dealer);
  1100.         $onlineBookingEntity->setComment($comment);
  1101.         if ($user) {
  1102.             $onlineBookingEntity->setUser($user);
  1103.         }
  1104.         $carId false;
  1105.         if (isset($car['id'])) {
  1106.             $carId $car['id'];
  1107.         }
  1108.         if ($carId) {
  1109.             $userCar $this->em->getRepository(UserCar::class)->find($carId);
  1110.             if ($userCar) {
  1111.                 $onlineBookingEntity->setUserCar($userCar);
  1112.             }
  1113.         }
  1114.         $onlineBookingEntity->setCarData(json_encode($car));
  1115.         if ($request->get('dealerId') == 14) {
  1116.             $extra_options = [
  1117.                 'ConnectionType' => $selectedConnectionType,
  1118.                 'MobilityService' => $selectedMobilityService,
  1119.                 'ToGoService' => $toGoService
  1120.             ];
  1121.             $onlineBookingEntity->setExtraOptionsData(json_encode($extra_options));
  1122.         }
  1123.         if ($works && count($works)) {
  1124.             foreach ($works as $regulationId) {
  1125.                 $Regulation $this->em->getRepository(ServiceWork::class)->find($regulationId);
  1126.                 if (!$Regulation) {
  1127.                     continue;
  1128.                 }
  1129.                 /** @var ServiceWorkJob $job */
  1130.                 foreach ($Regulation->getJobs() as $job) {
  1131.                     $Work = new OnlineServiceBookingWorks();
  1132.                     $Work->setJob($job->getJob());
  1133.                     $Work->setTime($job->getJobHours());
  1134.                     $Work->setBooking($onlineBookingEntity);
  1135.                     $this->em->persist($Work);
  1136.                 }
  1137.             }
  1138.         }
  1139.         $this->em->persist($onlineBookingEntity);
  1140.         $this->em->flush();
  1141.         $smsMsgWithAuthCode $translator->trans('auth.your_confirm_code', ['%code%' => $code], 'loyality');
  1142.         if ($senderCode) {
  1143.             $infobipSmsSenderb->sendSms($phone$smsMsgWithAuthCode);
  1144.         }
  1145.         return new JsonResponse(['success' => true'bookingId' => $onlineBookingEntity->getId()]);
  1146.     }
  1147.     public function getDealer($dealerId null): Dealer
  1148.     {
  1149.         $Dealer false;
  1150.         try {
  1151.             $Dealer parent::getDealer();
  1152.         } catch (NotFoundHttpException $e) {
  1153.             if ($dealerId) {
  1154.                 $Dealer $this->em->getRepository(Dealer::class)->find($dealerId);
  1155.             }
  1156.         }
  1157.         if (!$Dealer) {
  1158.             throw new NotFoundHttpException();
  1159.         }
  1160.         return $Dealer;
  1161.     }
  1162.     public function getServiceModelByDealer(Request $request): JsonResponse
  1163.     {
  1164.         $dealerId $request->get('dealerId');
  1165.         $models = [];
  1166.         $repositoryModels $this->em->getRepository(Model::class)->getModelsHasRegulationByDealer($dealerId);
  1167.         foreach ($repositoryModels as $item) {
  1168.             $models[$item->getId()] = [
  1169.                 'id' => $item->getId(),
  1170.                 'title' => $item->getTitle(),
  1171.                 'brandId' => $item->getBrand()->getId(),
  1172.             ];
  1173.         }
  1174.         return new JsonResponse(['success' => true'models' => $models]);
  1175.     }
  1176.     private function getUserNight(Request $request): User
  1177.     {
  1178.         $phone $request->get('phone');
  1179.         $phone preg_replace("/[^0-9]/"''$phone);
  1180.         $phone preg_replace("/^38/"''$phone);
  1181.         $rows $this->em->getRepository(User::class)
  1182.             ->createQueryBuilder('u')
  1183.             ->where('u.phone = :phone')
  1184.             ->setParameter('phone'$phone)
  1185.             ->orderBy('u.id''DESC')
  1186.             ->getQuery()
  1187.             ->getResult();
  1188.         if (!empty($rows)) {
  1189.             return $rows[0];
  1190.         }
  1191.         $User = new User();
  1192.         $User->setName($request->get('name'));
  1193.         $User->setPhone($phone);
  1194.         $User->setEmail(bin2hex(random_bytes(5)) . '@gmail.com');
  1195.         $User->setConfirmedPhone(true);
  1196.         $User->setUsername($phone);
  1197.         $User->setUsernameCanonical($phone);
  1198.         $User->setEnabled(true);
  1199.         $User->setPlainPassword(time());
  1200.         $User->addRole('ROLE_LOYALTY_USER');
  1201.         $User->setRegistrationConfirm(true);
  1202.         $this->em->persist($User);
  1203.         $this->em->flush();
  1204.         return $User;
  1205.     }
  1206.     private function getUserCarNight(Request $requestUser $User)
  1207.     {
  1208.         $UserCar $this->em->getRepository(UserCar::class)->findOneBy(['number' => $request->get('carNumber'), 'user' => $User]);
  1209.         if (empty($UserCar)) {
  1210.             $UserCar = new UserCar();
  1211.             $UserCar->setUser($User);
  1212.         }
  1213.         $UserCar->setBrand($request->get('carBrand'));
  1214.         $UserCar->setModel($request->get('carModel'));
  1215.         $UserCar->setNumber($request->get('carNumber'));
  1216.         $this->em->persist($UserCar);
  1217.         $this->em->flush();
  1218.         return $UserCar;
  1219.     }
  1220. }