src/Ecommerce/Controller/CustomerController.php line 83

Open in your IDE?
  1. <?php
  2. namespace App\Ecommerce\Controller;
  3. use App\Form\Type\ChangeNameType;
  4. use App\Form\Type\ChangePasswordType;
  5. use App\Form\Type\DeleteAccountType;
  6. use App\Form\Type\DeleteRegisteredWatchType;
  7. use App\Form\Type\NotificationsFilterType;
  8. use App\Form\Type\WatchesInterestType;
  9. use App\Form\Type\WatchRegisterType;
  10. use App\Form\Type\UserReportType;
  11. use App\Form\Type\RemarkType;
  12. use CoreShop\Component\Order\Notes;
  13. use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3Validator;
  14. use Pimcore\Model\Element\Note;
  15. use App\Helpers\HelperFunctions;
  16. use App\Maileon\MaileonService;
  17. use App\Model\DataObject\RegisteredWatch as RegWatch;
  18. use App\Service\AccountDeleteManager;
  19. use App\Service\FileUploader;
  20. use App\Service\MailerService;
  21. use App\Service\MessageCenterService;
  22. use App\Service\RegisteredWatchesManager;
  23. use App\Service\WatchRepairManager;
  24. use App\Service\WishListService;
  25. use App\Traits\NotificationHelper;
  26. use App\Traits\ExceptionHandlerTrait;
  27. use App\Traits\GeneralTrait;
  28. use App\Traits\OrderTrait;
  29. use App\Traits\SiteAware;
  30. use App\Traits\WatchWarranty;
  31. use App\Traits\WatchRepairTrait;
  32. use App\Traits\RegisteredWatch as RegisteredWatchTrait;
  33. use App\Traits\Validator as ValidatorTrait;
  34. use App\Traits\PDFTrait;
  35. use App\Website\LinkGenerator\RegisteredWatchesLinkGenerator;
  36. use Carbon\Carbon;
  37. use CoreShop\Bundle\AddressBundle\Form\Type\AddressType;
  38. use CoreShop\Bundle\FrontendBundle\Controller\CustomerController as BaseCustomerController;
  39. use CoreShop\Component\Address\Model\AddressIdentifierInterface;
  40. use CoreShop\Component\Address\Model\AddressInterface;
  41. use CoreShop\Component\Core\Customer\Address\AddressAssignmentManagerInterface;
  42. use CoreShop\Component\Core\Model\CustomerInterface;
  43. use CoreShop\Component\Order\Repository\OrderShipmentRepositoryInterface;
  44. use CoreShop\Component\Pimcore\DataObject\VersionHelper;
  45. use Doctrine\ORM\EntityManagerInterface;
  46. use Doctrine\ORM\NativeQuery;
  47. use Doctrine\ORM\Query\ResultSetMapping;
  48. use Exception;
  49. use Knp\Component\Pager\PaginatorInterface;
  50. use Pimcore\Log\ApplicationLogger;
  51. use Pimcore\Mail;
  52. use Pimcore\Model\Asset;
  53. use Pimcore\Model\DataObject;
  54. use Pimcore\Model\DataObject\CoreShopAddress;
  55. use Pimcore\Model\DataObject\CoreShopCustomer;
  56. use Pimcore\Model\DataObject\CoreShopOrder;
  57. use Pimcore\Model\DataObject\CoreShopProduct;
  58. use Pimcore\Model\DataObject\CoreShopUser;
  59. use Pimcore\Model\DataObject\Message;
  60. use Pimcore\Model\DataObject\MessageCustomer;
  61. use Pimcore\Model\DataObject\News;
  62. use Pimcore\Model\DataObject\RegisteredWatch;
  63. use Pimcore\Model\DataObject\WatchRepair;
  64. use Pimcore\Model\DataObject\WatchRepairUserReport;
  65. use Pimcore\Model\DataObject\WatchRepairRemark;
  66. use Pimcore\Model\DataObject\Service;
  67. use Pimcore\Model\Site;
  68. use Pimcore\Twig\Extension\Templating\Placeholder;
  69. use Psr\EventDispatcher\EventDispatcherInterface;
  70. use Symfony\Component\Form\FormInterface;
  71. use Symfony\Component\HttpFoundation\File\UploadedFile;
  72. use Symfony\Component\HttpFoundation\JsonResponse;
  73. use Symfony\Component\HttpFoundation\Request;
  74. use Symfony\Component\HttpFoundation\Response;
  75. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  76. use Symfony\Component\RateLimiter\RateLimiterFactory;
  77. use Symfony\Component\Routing\Annotation\Route;
  78. use Symfony\Component\Routing\RouterInterface;
  79. use Pimcore\Model\DataObject\Contact;
  80. class CustomerController extends BaseCustomerController
  81. {
  82.     use SiteAware;
  83.     use \App\Traits\ProductTrait;
  84.     use RegisteredWatchTrait;
  85.     use NotificationHelper;
  86.     use WatchWarranty;
  87.     use WatchRepairTrait;
  88.     use ValidatorTrait;
  89.     use ExceptionHandlerTrait;
  90.     use GeneralTrait;
  91.     use PDFTrait;
  92.     use OrderTrait;
  93.     protected $site;
  94.     public $maxWarrantyFiles;
  95.     public $maxWatchRepairFiles;
  96.     public $allowedWarrantyMimeTypes;
  97.     private string $warrantyPDFPath;
  98.     public $apiSettings;
  99.     public $carrier;
  100.     private const FILTER_ID 'notificationsFilter';
  101.     private string $boutiqueHost;
  102.     private readonly OrderShipmentRepositoryInterface $orderShipmentRepository;
  103.     public function __construct(
  104.         private readonly Placeholder              $placeholder,
  105.         private readonly EventDispatcherInterface $eventDispatcher,
  106.                                                   $maxWarrantyFiles,
  107.                                                   $maxWatchRepairFiles,
  108.                                                   $allowedWarrantyMimeTypes,
  109.         string                                    $warrantyPDFPath,
  110.                                                   $apiSettings,
  111.                                                   $carrier,
  112.         OrderShipmentRepositoryInterface          $orderShipmentRepository,
  113.         private readonly MaileonService           $maileonService
  114.     )
  115.     {
  116.         $this->maxWarrantyFiles $maxWarrantyFiles;
  117.         $this->maxWatchRepairFiles $maxWatchRepairFiles;
  118.         $this->allowedWarrantyMimeTypes $allowedWarrantyMimeTypes;
  119.         $this->warrantyPDFPath $warrantyPDFPath;
  120.         $this->apiSettings $apiSettings;
  121.         $this->carrier $carrier;
  122.         $this->orderShipmentRepository $orderShipmentRepository;
  123. //        $this->site = \Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite() : null;
  124.     }
  125.     public function setBoutiqueHost(string $host): void
  126.     {
  127.         $this->boutiqueHost $host;
  128.     }
  129.     /**
  130.      * @param Request $request
  131.      * @param Recaptcha3Validator $recaptcha3Validator
  132.      * @param ApplicationLogger $logger
  133.      * @return Response
  134.      * @Route("/watches_interest/{sku}", name="watches_modal")
  135.      */
  136.     public function watchesinterestAction(Request $requestRecaptcha3Validator $recaptcha3ValidatorApplicationLogger $logger): Response
  137.     {
  138.         if (!$request->isXmlHttpRequest()) {
  139.             throw new AccessDeniedHttpException('Ez az útvonal csak XHR kéréseket fogad.');
  140.         }
  141.         if (Site::isSiteRequest()) {
  142.             throw $this->createNotFoundException('Page not found!');
  143.         }
  144.         $customer $this->getCustomer();
  145.         $success false;
  146.         $formData = new Contact();
  147.         $formData->setSubject($request->get('sku'));
  148.         if ($customer instanceof CustomerInterface) {
  149.             $formData->setFirstname($customer->getFirstname());
  150.             $formData->setLastname($customer->getLastname());
  151.             $formData->setEmail($customer->getEmail());
  152.         }
  153.         $form $this->container->get('form.factory')->createNamed('watchesinterest'WatchesInterestType::class, $formData);
  154.         $form->handleRequest($request);
  155.         if ($form->isSubmitted() && $form->isValid()) {
  156.             /* @var $data Contact */
  157.             $data $form->getData();
  158.             $data->setPlatform('web');
  159.             try {
  160.                 $data->save();
  161.                 if (!$this->maileonService->getContactByEmail($data->getEmail())) {
  162.                     $this->maileonService->insertOrUpdateContact([
  163.                         'created' => date('Y-m-d H:i:s'),
  164.                         'email' => $data->getEmail(),
  165.                         'lastname' => $data->getLastname(),
  166.                         'firstname' => $data->getFirstname(),
  167.                         'permission' => 1
  168.                     ]);
  169.                 }
  170.                 $maileonData $data->getMaileonData();
  171.                 $maileonData['subject'] = sprintf("Érdeklődés: %s"$data->getSubject());
  172.                 $this->maileonService->sendTriggeredMail('Watchesinterest'$data->getEmail(), $maileonData);
  173.                 $mailConfig $this->container->getParameter('mailingConfig');
  174.                 foreach ($mailConfig['watches_interest']['addresses'] as $address) {
  175.                     $this->maileonService->sendTriggeredMail('Watchesinterest'$address$maileonData);
  176.                 }
  177.             } catch (\Exception $e) {
  178.                 $logger->error($e->getMessage(), ['component' => 'web-watches-intereset']);
  179.             }
  180.             $logger->info('Contact mail successfully sent', ['component' => 'watches-interest''relatedObject' => $data->getId()]);
  181.             $success true;
  182.         }
  183.         return $this->render($this->templateConfigurator->findTemplate('Customer/watches_interest.html'), [
  184.             'form' => $form->createView(),
  185.             'success' => $success
  186.         ]);
  187.     }
  188.     /**
  189.      * @param Request $request
  190.      * @param Recaptcha3Validator $recaptcha3Validator
  191.      * @param ApplicationLogger $logger
  192.      * @return Response
  193.      * @Route("/watches_modify/{id}", name="watches_modify_modal")
  194.      */
  195.     public function watchesModifyAction(Request $requestRecaptcha3Validator $recaptcha3ValidatorApplicationLogger $logger): Response
  196.     {
  197.         if (!$request->isXmlHttpRequest()) {
  198.             throw new AccessDeniedHttpException('Ez az útvonal csak XHR kéréseket fogad.');
  199.         }
  200.         $this->denySite('prospex');
  201.         $customer $this->getCustomer();
  202.         $success false;
  203.         $watchId $request->get('id');
  204.         $watch RegisteredWatch::getById($watchId);
  205.         $formData = new Contact();
  206.         if ($watch instanceof RegisteredWatch) {
  207.             $formData->setSubject('Regisztrált óra - ' $watch->getReference() . ' ' $watch->getSerial() . ' ' $watch->getMechanismNumber());
  208.         }
  209.         if ($customer instanceof CustomerInterface) {
  210.             $formData->setFirstname($customer->getFirstname());
  211.             $formData->setLastname($customer->getLastname());
  212.             $formData->setEmail($customer->getEmail());
  213.         }
  214.         $form $this->container->get('form.factory')->createNamed('watchesinterest'WatchesInterestType::class, $formData);
  215.         $form->handleRequest($request);
  216.         if ($form->isSubmitted() && $form->isValid()) {
  217.             /* @var $data Contact */
  218.             $data $form->getData();
  219.             $textFormat "Adatmódosítási kérelem érkezett\n\n";
  220.             $textFormat .= "Óra link: %s\n\n";
  221.             $textFormat .= "Óra: %s\n\n";
  222.             $textFormat .= "Név: %s %s\n";
  223.             $textFormat .= "E-mail: %s\n";
  224.             $textFormat .= "Telefon: %s\n";
  225.             $textFormat .= "Üzenet: %s\n\n";
  226.             $textFormat .= "Dátum: " date("Y-m-d H:i:s") . "\n";
  227.             $text sprintf($textFormat,
  228.                 $this->boutiqueHost "/seiko-bejelentkezo-oldal?deeplink=object_" $watchId "_object",
  229.                 $data->getSubject(),
  230.                 $customer->getLastname(),
  231.                 $customer->getFirstname(),
  232.                 $customer->getEmail(),
  233.                 $data->getMobile() ?? 'N/A',
  234.                 $data->getMessage() ?? 'N/A',
  235.             );
  236.             $mail = new Mail();
  237.             $mailConfig $this->container->getParameter('mailingConfig');
  238.             foreach ($mailConfig['watches_modify']['addresses'] as $address) {
  239.                 $mail->addTo($address);
  240.             }
  241.             if ($mailConfig['watches_modify']['subject']) {
  242.                 $mail->subject($mailConfig['watches_modify']['subject']);
  243.             }
  244.             $mail->text($text);
  245.             $mail->disableLogging();
  246.             $mail->send();
  247.             $logger->info($text, ['component' => 'watches-modify']);
  248.             $success true;
  249.         }
  250.         return $this->render($this->templateConfigurator->findTemplate('Customer/watches_modify.html'), [
  251.             'form' => $form->createView(),
  252.             'success' => $success
  253.         ]);
  254.     }
  255.     /**
  256.      * @Route("/profil", name="profil")
  257.      */
  258.     public function profileAction(?Request $request null): Response
  259.     {
  260.         $this->denySite('prospex');
  261.         $customer $this->getCustomer();
  262.         $session $request->getSession();
  263.         if ($loginRedirect $request->get('login_redirect')) {
  264.             $session->set('login_redirect'$loginRedirect);
  265.         }
  266.         if (!$customer instanceof CustomerInterface) {
  267.             if ($loginRedirect) {
  268.                 $this->addFlash('warning''Kérlek jelentkezz be a kosár használatához!');
  269.             }
  270.             return $this->forward('CoreShop\Bundle\FrontendBundle\Controller\RegisterController::registerAction');
  271.         }
  272.         if ($loginRedirect $session->remove('login_redirect')) {
  273.             return $this->redirect($loginRedirect);
  274.         }
  275.         $bc = [
  276.             [
  277.                 'title' => 'Főoldal',
  278.                 'path' => '/'
  279.             ],
  280.             [
  281.                 'title' => 'Profil',
  282.                 'path' => null
  283.             ]
  284.         ];
  285.         $pl $this->placeholder;
  286.         $pl('breadcrumbNews')->set($bc);
  287. //        return $this->redirectToRoute('profile_messages');
  288.         return $this->redirectToRoute('profile_profiledata');
  289.     }
  290.     /**
  291.      * @param Request $request
  292.      * @param AccountDeleteManager $manager
  293.      * @return Response
  294.      * @Route("/profil/fiokadatok", name="profile_profiledata")
  295.      */
  296.     public function profiledataAction(Request $requestAccountDeleteManager $manager): Response
  297.     {
  298.         $this->denySite('prospex');
  299.         $customer $this->getCustomer();
  300.         if (!$customer instanceof CustomerInterface) {
  301.             return $this->redirect('/profil');
  302.         }
  303.         $defaultAddressIdentifier $this->container->get('coreshop.repository.address_identifier')->findByName('invoice');
  304.         $addresses $customer->getAddresses();
  305.         foreach ($addresses as $idx => $address) {
  306.             $save false;
  307.             if (!$address->getAddressIdentifier() instanceof AddressIdentifierInterface) {
  308.                 $address->setAddressIdentifier($defaultAddressIdentifier);
  309.                 $save true;
  310.             }
  311.             $phoneNumber HelperFunctions::formatPhoneNumber($address->getPhoneNumber());
  312.             if (strlen($phoneNumber)) {
  313.                 if ($phoneNumber !== $address->getPhoneNumber()) {
  314.                     $address->setPhoneNumber($phoneNumber);
  315.                     $save true;
  316.                 }
  317.                 if ($save) {
  318.                     $address->save();
  319.                 }
  320.             } else {
  321.                 if ($address->getAddressIdentifier()->getName() !== 'magazine') {
  322.                     $address->delete();
  323.                     unset($addresses[$idx]);
  324.                 }
  325.             }
  326.         }
  327.         if (count($addresses) !== count($customer->getAddresses())) {
  328.             $customer->setAddresses($addresses);
  329.             $customer->save();
  330.         }
  331.         $passwordForm $this->container->get('form.factory')->createNamed('changepassword'ChangePasswordType::class, $customer);
  332.         $nameForm $this->container->get('form.factory')->createNamed('changename'ChangeNameType::class, $customer);
  333.         $passwordForm->handleRequest($request);
  334.         $nameForm->handleRequest($request);
  335.         if ($passwordForm->isSubmitted() && $passwordForm->isValid()) {
  336.             try {
  337.                 /** @var CoreShopCustomer $customer */
  338.                 $customer $passwordForm->getData();
  339.                 /** @var CoreShopUser $user */
  340.                 $user $customer->getUser();
  341.                 $user->setPassword($user->getPlainPassword());
  342.                 $user->save();
  343.                 $customer->setUser($user);
  344.                 $customer->save();
  345.                 $this->addFlash('success''Sikeres jelszó változtatás!');
  346.             } catch (Exception $e) {
  347.                 $this->addFlash('error''Hiba történt jelszó változtatás közben!');
  348.             }
  349.             return $this->redirectToRoute('profile_profiledata');
  350.         }
  351.         if ($nameForm->isSubmitted() && $nameForm->isValid()) {
  352.             try {
  353.                 $customer $nameForm->getData();
  354.                 $customer->save();
  355.                 $this->addFlash('success''Sikeres adat változtatás!');
  356.             } catch (Exception $e) {
  357.                 $this->addFlash('error''Hiba történt adat változtatás közben!');
  358.             }
  359.             return $this->redirectToRoute('profile_profiledata');
  360.         }
  361.         $deleteForm $this->container->get('form.factory')->createNamed(
  362.             'deleteAccount'DeleteAccountType::class
  363.         );
  364.         $deleteForm->handleRequest($request);
  365.         if ($deleteForm->isSubmitted() && $deleteForm->isValid() && $deleteForm->get('submit')?->isClicked()) {
  366.             try {
  367.                 $this->container->get('security.token_storage')->setToken(null);
  368.                 $manager->deleteAccount($customer);
  369.                 $request->getSession()->invalidate(0);
  370.                 return $this->redirectToRoute('coreshop_index');
  371.             } catch (Exception $e) {
  372.                 $this->addFlash('error''Hiba történt!');
  373.                 return $this->redirectToRoute('coreshop_index');
  374.             }
  375.         }
  376.         return $this->render($this->templateConfigurator->findTemplate('Customer/profile_data.html'), [
  377.             'customer' => $customer,
  378.             'passwordForm' => $passwordForm->createView(),
  379.             'nameForm' => $nameForm->createView(),
  380.             'deleteForm' => $deleteForm->createView()
  381.         ]);
  382.     }
  383.     /**
  384.      * @param Request $request
  385.      * @param PaginatorInterface $paginator
  386.      * @param EntityManagerInterface $entityManager
  387.      * @param MessageCenterService $messageCenterService
  388.      * @param RouterInterface $router
  389.      * @return Response
  390.      *
  391.      * @Route("/profil/uzenetek", name="profile_messages")
  392.      */
  393.     public function messagesAction(Request $requestPaginatorInterface $paginatorEntityManagerInterface $entityManagerMessageCenterService $messageCenterServiceRouterInterface $router): Response
  394.     {
  395.         $session $request->getSession();
  396.         if (!$session->has(self::FILTER_ID)) {
  397.             $session->set(self::FILTER_ID, ['status' => 'all''topic' => 'all']);
  398.         }
  399.         $filterData $session->get(self::FILTER_ID);
  400.         if ($request->isMethod('POST')) {
  401.             $status $request->get('status');
  402.             if ($status) {
  403.                 $filterData['status'] = $status;
  404.             }
  405.             $topic $request->get('topic');
  406.             if ($topic) {
  407.                 $filterData['topic'] = $topic;
  408.             }
  409.             $session->set(self::FILTER_ID$filterData);
  410.             return $this->redirectToRoute('profile_messages');
  411.         }
  412.         $topic $filterData['topic'] === 'all' null : [$filterData['topic']];
  413.         $customer $this->getCustomer();
  414.         if (!$customer instanceof CustomerInterface) {
  415.             return $this->redirect('/profil');
  416.         }
  417. //        $dao = (new MessageCustomer\Listing())->getDao();
  418. //        $queryBuilder = new QueryBuilder($dao->db);
  419. //        $queryBuilder->from($dao->getTableName());
  420. //        $queryBuilder->orderBy('o16.sendTime', 'DESC');
  421. //        $queryBuilder->andWhere(sprintf('%s.customer__id = %u', $dao->getTableName(), $customer->getId()));
  422. //        $queryBuilder->innerJoin('object_17', 'object_16', 'o16', 'o16.oo_id = object_17.message__id');
  423. //        $queryBuilder->leftJoin('o16', 'object_12', 'o12', 'o12.oo_id = o16.topic__id');
  424. //        $queryBuilder->addSelect($dao->getTableName() . '.oo_id');
  425. //        $queryBuilder->addSelect('o16.image');
  426. //        $queryBuilder->addSelect('o16.title');
  427. //        $queryBuilder->addSelect('o16.text');
  428. //        $queryBuilder->addSelect('o16.sendTime');
  429. //        $queryBuilder->addSelect('object_17.read');
  430. //        $queryBuilder->addSelect('o12.topic');
  431. //
  432. //        switch ($filterData['status']) {
  433. //            case 'readed' :
  434. //                $queryBuilder->andWhere('object_17.read = 1');
  435. //                break;
  436. //            case '1' :
  437. //                $queryBuilder->andWhere('(object_17.read IS NULL OR object_17.read = 0 OR object_17.read = -1)');
  438. //                break;
  439. //        }
  440. //
  441. //        if (is_array($topic) && !empty($topic)) {
  442. //            $topicWhere[] = $queryBuilder->expr()->in('o12.topic', array_map(function ($item) {
  443. //                return "'" . $item . "'";
  444. //            }, $topic));
  445. //
  446. //            if (in_array('system', $topic)) {
  447. //                $topicWhere[] = $queryBuilder->expr()->isNull('o16.topic__id');
  448. //            }
  449. //
  450. //            $queryBuilder->andWhere(implode(' OR ', $topicWhere));
  451. //        }
  452.         $rsm = new ResultSetMapping();
  453.         $rsm->addScalarResult('oo_id''oo_id');
  454.         $rsm->addScalarResult('image''image');
  455.         $rsm->addScalarResult('title''title');
  456.         $rsm->addScalarResult('text''text');
  457.         $rsm->addScalarResult('sendTime''sendTime');
  458.         $rsm->addScalarResult('o_className''o_className');
  459.         $rsm->addScalarResult('o_id''o_id');
  460.         $rsm->addScalarResult('topic''topic');
  461.         $query = new NativeQuery($entityManager);
  462.         $query->setResultSetMapping($rsm);
  463.         $query->setSQL(sprintf(
  464.             "SELECT * FROM (%s UNION %s) a order by a.sendTime DESC",
  465.             $messageCenterService->getMessageQuery($customer$filterData['status'] ?? null$filterData['topic'] != 'all' ? [$filterData['topic']] : null)->getSQL(),
  466.             $messageCenterService->getMessageCustomerQuery($customer$filterData['status'] ?? null$filterData['topic'] != 'all' ? [$filterData['topic']] : null)->getSQL()
  467.         ));
  468.         $result $query->getResult();
  469.         $page = (int)$request->get('page'1);
  470.         try {
  471.             $list $paginator->paginate(
  472.                 $result,
  473.                 $page,
  474.                 10
  475.             );
  476.         } catch (Exception $e) {
  477.         }
  478.         $cache = [];
  479.         if ($list->getItems()) {
  480.             $listing = new MessageCustomer\Listing();
  481.             $listing->setCondition(sprintf("message__id IN (%s) AND customer__id = %u"implode(', 'array_map(function ($item) {
  482.                 return $item['oo_id'];
  483.             }, (array)$list->getItems())), $customer->getId()));
  484.             $cache $listing->getData();
  485.         }
  486.         $notifications = [];
  487.         foreach ($list as $item) {
  488.             $date '';
  489.             try {
  490.                 $carbon Carbon::createFromTimestamp($item['sendTime']);
  491.                 if ($carbon instanceof Carbon) {
  492.                     $date $carbon->format('Y. m. d. H:i');
  493.                 }
  494.             } catch (Exception) {
  495.             }
  496.             $notifications[] = [
  497.                 'id' => $item['oo_id'],
  498.                 'image' => Asset::getById($item['image']),
  499.                 'title' => $item['title'],
  500.                 'text' => $item['text'],
  501.                 'date' => $date,
  502.                 'read' => $messageCenterService->getMessageRead($item['oo_id'], $cache),
  503.                 'topic' => $item['topic'],
  504.                 'link' => $this->getMessageWebLink($item)
  505.             ];
  506.         }
  507.         $form $this->container->get('form.factory')->createNamed(
  508.             self::FILTER_IDNotificationsFilterType::class,
  509.             $filterData
  510.         );
  511.         return $this->render($this->templateConfigurator->findTemplate('Customer/profile_messages.html'), [
  512.             'customer' => $customer,
  513.             'paginator' => $list,
  514.             'notifications' => $notifications,
  515.             'notiFilterForm' => $form->createView(),
  516.         ]);
  517.     }
  518.     protected function getMessageWebLink($item): null|string
  519.     {
  520.         if (!empty($item['o_id']) && !empty($item['o_className'])) {
  521.             $redirect $this->boutiqueHost "/profil?login_redirect=";
  522.             switch ($item['o_className']) {
  523.                 case 'News':
  524.                     return $this->container->get('App\Website\LinkGenerator\NewsLinkGenerator')->generate(News::getById($item['o_id']));
  525.                 case 'RegisteredWatch':
  526.                     return $redirect $this->container->get('App\Website\LinkGenerator\RegisteredWatchesLinkGenerator')->generate(RegisteredWatch::getById($item['o_id']));
  527.                 case 'WatchRepair':
  528.                     return $redirect $this->container->get('App\Website\LinkGenerator\WatchRepairsLinkGenerator')->generate(WatchRepair::getById($item['o_id']));
  529.             }
  530.         }
  531.         return null;
  532.     }
  533.     /**
  534.      * @param Request $request
  535.      * @param MessageCenterService $messageCenterService
  536.      * @return Response
  537.      *
  538.      * @Route("/fetch-notification", name="fetch_notification", methods={"POST"})
  539.      */
  540.     public function fetchNotificationAction(Request $requestMessageCenterService $messageCenterService): Response
  541.     {
  542.         $message Message::getById($request->request->get('id'));
  543.         $html $this->render($this->templateConfigurator->findTemplate('Customer/_notificationRowOpened.html'), [
  544.             'notification' => $message,
  545.             'date' => $message->getSendTime()?->format('Y. m. d. H:i') ?? '',
  546.         ])->getContent();
  547.         $customer $this->getUser()->getCustomer();
  548.         $message Message::getById($request->get('id'));
  549.         if (!$message instanceof Message) {
  550.             return new JsonResponse(null400);
  551.         }
  552.         $listing = new MessageCustomer\Listing();
  553.         $listing->setCondition(sprintf("message__id = %u AND customer__id = %u"$request->get('id'), $customer->getId()));
  554. //        if ($action == 'read') {
  555.         if ($listing->count() === 0) {
  556.             try {
  557.                 $messageCenterService->markMessageRead($customer$message);
  558.             } catch (Exception $e) {
  559.                 return new JsonResponse($e->getMessage(), 400);
  560.             }
  561.         }
  562. //        }
  563. //        else if ($action == 'unread') {
  564. //            if ($listing->count() > 0) {
  565. //                foreach ($listing as $item) {
  566. //                    try {
  567. //                        $item->delete();
  568. //                    } catch (\Exception $e) {
  569. //                        return new JsonResponse($e->getMessage(), 400);
  570. //                    }
  571. //                }
  572. //            } else {
  573. //                return new JsonResponse(null, 400);
  574. //            }
  575. //        }
  576.         return new JsonResponse(['success' => true'html' => $html'link' => $this->getMessageWebLink([
  577.             'o_id' => $message->getContent()?->getId(),
  578.             'o_className' => $message->getContent()?->getClassName()
  579.         ])]);
  580.     }
  581.     /**
  582.      * @param Request $request
  583.      * @param PaginatorInterface $paginator
  584.      * @return Response
  585.      * @Route("/profil/feliratkozasaim", name="profile_subscriptions")
  586.      */
  587.     public function profileSubscriptionsAction(Request $requestPaginatorInterface $paginator): Response
  588.     {
  589.         $this->denySite('prospex');
  590.         $customer $this->getCustomer();
  591.         if (!$customer instanceof CustomerInterface) {
  592.             return $this->redirectToRoute('profil');
  593.         }
  594.         if ($request->getMethod() == 'POST') {
  595.             $subscribeNewsletter $request->request->get('subscribe-newsletter');
  596.             if ($subscribeNewsletter == && !$customer->getNewsletterActive()) {
  597.                 $customer->setNewsletterActive(true);
  598.                 $customer->save();
  599.                 $this->addFlash('success''Sikeresen feliratkoztál a Seiko hírlevelére');
  600.             }
  601.             if ($subscribeNewsletter === "0" && $customer->getNewsletterActive()) {
  602.                 $customer->setNewsletterActive(false);
  603.                 $customer->setMagazineSubscribed(false);
  604.                 $customer->setMagazineSubscriptionDate(null);
  605.                 $this->addFlash('success''Sikeresen leiratkoztál a Seiko hírelvélről és ezzel együtt a Seiko Magazinról is.');
  606.                 $customer->save();
  607.             }
  608.             $subscribeMagazine $request->request->get('subscribe-magazine');
  609.             if ($subscribeMagazine == && !$customer->getMagazineSubscribed()) {
  610.                 $customer->setMagazineSubscribed(true);
  611.                 $customer->setMagazineSubscriptionDate(new Carbon());
  612.                 $customer->setNewsletterActive(true);
  613.                 $customer->save();
  614.                 $this->addFlash('success''Sikeresen feliratkoztál a Seiko Magazinra');
  615.             }
  616.             if ($subscribeMagazine == && $customer->getMagazineSubscribed()) {
  617.                 $customer->setMagazineSubscribed(false);
  618.                 $customer->setMagazineSubscriptionDate(null);
  619.                 $customer->save();
  620.                 $this->addFlash('success''Sikeresen leiratkoztál a Seiko Magazinról és a hírlevélről');
  621.             }
  622.             return $this->redirectToRoute('profile_subscriptions');
  623.         }
  624.         $bc = [
  625.             [
  626.                 'title' => 'Főoldal',
  627.                 'path' => '/'
  628.             ],
  629.             [
  630.                 'title' => 'Profil',
  631.                 'path' => $this->generateUrl('profil')
  632.             ],
  633.             [
  634.                 'title' => 'Feliratkozásaim',
  635.                 'path' => null
  636.             ]
  637.         ];
  638.         $pl $this->placeholder;
  639.         $pl('breadcrumbNews')->set($bc);
  640.         //GetTopic list
  641.         $topicList $this->getTopicSubscriptionList($customer);
  642.         return $this->render($this->templateConfigurator->findTemplate('Customer/profile_subscriptions.html'), [
  643.             'customer' => $customer,
  644.             'topics' => $topicList
  645.         ]);
  646.     }
  647.     /**
  648.      * @param Request $request
  649.      * @return Response
  650.      *
  651.      * @Route("/profil/feliratkozasaim/topicsubscriptions", name="topicsubscriptions", methods={"POST"})
  652.      */
  653.     public function fetchTopicSubscriptions(Request $request): Response
  654.     {
  655.         $user $this->getUser();
  656.         if (!$user) {
  657.             return new JsonResponse(['success' => false'message' => 'Unauthorized'], 401);
  658.         }
  659.         $customer $user->getCustomer();
  660.         $req $request->request->all();
  661.         if (isset($req['action'])) {
  662.             $action $req['action'];
  663.             return $this->topicMarkAllProcess($this->getUser()->getCustomer(), $action);
  664.         }
  665.         return $this->topicSubscribeProcess($req$customer);
  666.     }
  667.     /**
  668.      * @param Request $request
  669.      * @param RegisteredWatchesManager $registeredWatchesManager
  670.      * @param FileUploader $uploader
  671.      * @param MailerService $mailerService
  672.      * @param ApplicationLogger $logger
  673.      * @return Response
  674.      *
  675.      * @throws Exception
  676.      * @Route("/profil/ora-regisztracio", name="profile_watch_register")
  677.      */
  678.     public function registerWatchAction(Request $requestRegisteredWatchesManager $registeredWatchesManagerFileUploader $uploaderMailerService $mailerServiceApplicationLogger $loggerRateLimiterFactory $anonymousApiLimiter): Response
  679.     {
  680.         $this->denySite('prospex');
  681.         $customer $this->getCustomer();
  682.         if (!$customer instanceof CustomerInterface) {
  683.             return $this->redirect('/profil');
  684.         }
  685.         $isDuplicated false;
  686.         $regstrationSource $this->isSite('club') ? 'app' 'web';
  687.         $form $this->container->get('form.factory')->createNamed('registerwatch'WatchRegisterType::class, new RegisteredWatch());
  688.         if (in_array($request->getMethod(), ['POST''PUT''PATCH'], true)) {
  689.             $form $form->handleRequest($request);
  690.             if ($form->isValid()) {
  691.                 $watch $form->getData();
  692.                 $path '/RegisteredWatches';
  693.                 $watch->setParent(Service::createFolderByPath($path));
  694.                 $watch->setStatus('pending');
  695.                 $watch->setCustomer($customer);
  696.                 $watch->setRegisteredAt(Carbon::now());
  697.                 $watch->setRegistrationSource($regstrationSource);
  698.                 $warrantyFile null;
  699.                 $path $this->getNotMappedValue($form'filePath');
  700.                 if ($path !== null) {
  701.                     $filename basename($path);
  702.                     $path $this->container->getParameter('kernel.project_dir') . '/public' $path;
  703.                     $mimeType mime_content_type($path);
  704.                     if ($filename &&
  705.                         in_array($mimeType, ['image/jpeg''image/jpg''application/pdf''application/x-pdf'], true) &&
  706.                         file_exists($path)
  707.                     ) {
  708.                         $warrantyFile $uploader->upload(new UploadedFile($path$filename$mimeType));
  709.                     }
  710.                 }
  711.                 try {
  712.                     $registeredWatchesManager->persistWatch($watch$warrantyFile);
  713.                     $this->addFlash('success''Sikeres óra regisztráció!');
  714.                     $mailerService->sendRegisteredWatchMail($watch);
  715.                     return $this->redirectToRoute('profile_registered_watch_list');
  716.                 } catch (Exception $e) {
  717.                     $this->addFlash('error''Váratlan hiba történt! Az óra regisztráció sikertelen volt!');
  718.                     $text sprintf("%s\n%s\n\nWeb"$customer->getEmail(), $e->getMessage());
  719.                     $logger->error($text, ['component' => 'watch-register']);
  720.                 }
  721.             } else {
  722.                 $limiter $anonymousApiLimiter->create($request->getClientIp());
  723.                 $data $request->request->all();
  724.                 try {
  725.                     $data['price'] = (float)$data['price'];
  726.                 } catch (Exception $exception) {
  727.                     $text sprintf("Cannot be converted to float\n%s\n%s\n\nWeb"$customer->getEmail(), $exception->getMessage());
  728.                     $logger->error($text, ['component' => 'watch-register']);
  729.                     $data['price'] = 0.0;
  730.                 }
  731.                 $data['placeOfPurchase'] = $data['placeOfPurchase']['shopNameSelect'] ?: ($data['placeOfPurchase']['shopNameText'] ?: 'NA');
  732.                 $isDuplicated $registeredWatchesManager->isDuplicatedError($data$form->getErrors(true), $customer, (bool)$this->getNotMappedValue($form'filePath'), $limiter$regstrationSource);
  733.             }
  734.         }
  735.         $bc = [
  736.             ['title' => 'Főoldal''path' => '/'],
  737.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  738.             ['title' => 'Óra regisztráció''path' => null,]
  739.         ];
  740.         $pl $this->placeholder;
  741.         $pl('breadcrumbNews')->set($bc);
  742.         return $this->render($this->templateConfigurator->findTemplate('Customer/watches_register.html'), [
  743.             'customer' => $customer,
  744.             'form' => $form->createView(),
  745.             'isDuplicated' => $isDuplicated
  746.         ]);
  747.     }
  748.     /**
  749.      * @param Request $request
  750.      * @return Response
  751.      *
  752.      * @Route("/profil/ora-regisztracio/image/{sku}", name="profile_watch_register_image", methods={"GET"})
  753.      */
  754.     public function fetchRegisteredWatchImage(Request $requeststring $sku): Response
  755.     {
  756.         $user $this->getUser();
  757.         if (!$user) {
  758.             return new JsonResponse(['success' => false'message' => 'Unauthorized'], 401);
  759.         }
  760.         $productImage $this->getProductImageBySku($sku);
  761.         if ($productImage instanceof \Pimcore\Model\Asset\Image) {
  762.             return new JsonResponse($productImage->getFullPath());
  763.         }
  764.         return new JsonResponse(""404);
  765.     }
  766.     private function getNotMappedValue(FormInterface $formstring $key): mixed
  767.     {
  768.         if ($form->has($key) && $form->get($key)->getData()) {
  769.             return $form->get($key)->getData();
  770.         }
  771.         return null;
  772.     }
  773.     /**
  774.      * @param Request $request
  775.      * @param PaginatorInterface $paginator
  776.      * @return Response
  777.      * @Route("/profil/regisztralt-orak", name="profile_registered_watch_list")
  778.      */
  779.     public function registeredWatchAction(Request $requestPaginatorInterface $paginatorApplicationLogger $logger): Response
  780.     {
  781.         $this->denySite('prospex');
  782.         $customer $this->getCustomer();
  783.         if (!$customer instanceof CustomerInterface) {
  784.             return $this->redirect('/profil');
  785.         }
  786.         $session $request->getSession();
  787.         $page = (int)$this->getParameterFromRequest($request'page'1);
  788.         $view $this->getParameterFromRequest($request'view'$customer->getSettings(RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_VIEWRegWatch::DEFAULT_LISTING_VIEW));
  789.         if (!in_array($viewRegWatch::VALID_LISTING_VIEWStrue)) {
  790.             $view RegWatch::DEFAULT_LISTING_VIEW;
  791.         }
  792.         $savedSort $customer->getSettings(RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_SORTRegWatch::DEFAULT_LISTING_SORT);
  793.         $sortParsed HelperFunctions::parseSorting($this->getParameterFromRequest($request'sort'$savedSort),
  794.             RegWatch::VALID_LISTING_SORT_VALUES,
  795.             RegWatch::DEFAULT_LISTING_SORT_KEY,
  796.             RegWatch::DEFAULT_LISTING_SORT_DIRECTION
  797.         );
  798.         $sort $sortParsed['sort'];
  799.         if ($savedSort !== $sort) {
  800.             $page 1;
  801.         }
  802.         try {
  803.             $customer->setSettings([
  804.                 RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_VIEW => $view,
  805.                 RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_SORT => $sort
  806.             ]);
  807.         } catch (Exception $e) {
  808.             $logger->info($e->getMessage(), ['component' => 'customer-settings']);
  809.         }
  810.         $session->set(RegWatch::SESSION_REGISTERED_WATCH_PAGE$page);
  811.         $listing RegisteredWatch::getByCustomer($customer);
  812.         $listing->setCondition("(`status` != 'deleted')");
  813.         $listing->setOrder($sortParsed['direction']);
  814.         $listing->setOrderKey($sortParsed['name']);
  815.         $list $paginator->paginate($listing$page20);
  816.         $bc = [
  817.             ['title' => 'Főoldal''path' => '/'],
  818.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  819.             ['title' => 'Regisztrált órák''path' => null,]
  820.         ];
  821.         $pl $this->placeholder;
  822.         $pl('breadcrumbNews')->set($bc);
  823.         return $this->render($this->templateConfigurator->findTemplate('Customer/registered_watches_list.html'), [
  824.             'customer' => $customer,
  825.             'list' => $list->getItems(),
  826.             'paginator' => $list,
  827.             'minDate' => Carbon::parse('2000-01-01'),
  828.             'statusValues' => DataObject\Service::getOptionsForSelectField('Pimcore\Model\DataObject\RegisteredWatch'"status"),
  829.             'clubsite' => $this->isSite('club'),
  830.             'validSortElements' => RegWatch::VALID_LISTING_SORT_VALUES,
  831.             'sortDirection' => $sortParsed['direction'],
  832.             'view' => $view,
  833.             'sort' => $sort,
  834.             'validViews' => RegWatch::VALID_LISTING_VIEWS
  835.         ]);
  836.     }
  837.     /**
  838.      * @param Request $request
  839.      * @param PaginatorInterface $paginator
  840.      * @param RegisteredWatchesManager $registeredWatchesManager
  841.      * @param WatchRepairManager $watchRepairManager
  842.      * @return Response
  843.      *
  844.      * @Route("/profil/regisztralt-orak/{slug}~w{id}", name="profile_registered_watch")
  845.      */
  846.     public function registeredWatchDetailsAction(
  847.         Request                        $request,
  848.         PaginatorInterface             $paginator,
  849.         RegisteredWatchesManager       $registeredWatchesManager,
  850.         FileUploader                   $uploader,
  851.         WatchRepairManager             $watchRepairManager,
  852.         MailerService                  $mailerService,
  853.         RateLimiterFactory             $anonymousApiLimiter,
  854.         RegisteredWatchesLinkGenerator $registeredWatchesLinkGenerator,
  855.         ApplicationLogger              $logger
  856.     ): Response
  857.     {
  858.         $this->denySite('prospex');
  859.         $customer $this->getCustomer();
  860.         if (!$customer instanceof CustomerInterface) {
  861.             return $this->redirect('/profil');
  862.         }
  863.         $watch RegisteredWatch::getById($request->get('id'));
  864.         if (!$watch instanceof RegisteredWatch || $watch->getStatus() === 'deleted') {
  865.             return $this->redirectToRoute('profile_registered_watch_list');
  866.         }
  867.         if ($customer->getId() !== $watch->getCustomer()->getId()) {
  868.             return $this->redirectToRoute('profile_registered_watch_list');
  869.         }
  870.         $product $this->getProductFromWatch($watch);
  871.         $bc = [
  872.             ['title' => 'Főoldal''path' => '/'],
  873.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  874.             ['title' => 'Regisztrált órák''path' => $this->generateUrl('profile_registered_watch_list')],
  875.             ['title' => sprintf("%s - %s"$watch->getSerial(), $watch->getMechanismNumber()), 'path' => null]
  876.         ];
  877.         $pl $this->placeholder;
  878.         $pl('breadcrumbNews')->set($bc);
  879.         //NewUserreport
  880.         $newUserReportForm $this->container->get('form.factory')->createNamed(
  881.             'newuserreportform'UserReportType::class
  882.         );
  883.         $newUserReportForm->handleRequest($request);
  884.         $state = [
  885.             'servicedropdown' => [
  886.                 'opened' => false
  887.             ],
  888.             'newuserreportform' => [
  889.                 'opened' => false
  890.             ]
  891.         ];
  892.         if ($newUserReportForm->isSubmitted()) {
  893.             if ($newUserReportForm->isValid()) {
  894.                 $data $newUserReportForm->getData();
  895.                 $userReport $this->createWatchRepairUserReportSheet($request$uploader$data$watch->getId());
  896.                 $this->updateWatchRepairEvents($userReport$data);
  897.                 if ($userReport instanceof WatchRepairUserReport) {
  898.                     $this->addFlash('success''A bejegyzés sikeresen hozzáadva!');
  899.                     return $this->redirect($registeredWatchesLinkGenerator->generate($watch));
  900.                 }
  901.             }
  902.             if (!$newUserReportForm->isValid()) {
  903.                 $this->addFlash('error''A bejegyzés hozzáadás sikertelen!');
  904.                 $state['servicedropdown']['opened'] = true;
  905.                 $state['newuserreportform']['opened'] = true;
  906.             }
  907.         }
  908.         $combinedList $this->getWatchRepairSheetList($watch->getId());
  909.         $sheet_list $paginator->paginate($combinedList, (int)$request->get('page'1), 10);
  910.         foreach ($sheet_list as $repairSheet) {
  911.             $repairSheet->dateModificatedObject HelperFunctions::getModificationDate($repairSheet);
  912.         }
  913.         $deleteForm $this->container->get('form.factory')->createNamed('watchesinterest'DeleteRegisteredWatchType::class);
  914.         $deleteForm->handleRequest($request);
  915.         if ($deleteForm->isSubmitted() && $deleteForm->isValid() && $deleteForm->get('delete')?->isClicked()) {
  916.             try {
  917.                 $registeredWatchesManager->deleteRegistration($watch);
  918.                 $this->addFlash('success''Óra regisztráció sikeresen törölve.');
  919.             } catch (Exception) {
  920.                 $this->addFlash('error''Hiba történt!');
  921.             }
  922.             return $this->redirectToRoute('profile_registered_watch_list');
  923.         }
  924.         $maxWarrantyFiles $this->maxWarrantyFiles;
  925.         //Delete warranty
  926.         if ($request->getMethod() === "POST" && $warrantyIndex $request->request->get('delWarranty')) {
  927.             if (is_numeric($warrantyIndex)) {
  928.                 $deleteresult $this->deleteWarranty($watch$warrantyIndex);
  929.             }
  930.             $deleteFlashTyle $deleteresult["errors"] === false 'success' 'error';
  931.             $this->addFlash($deleteFlashTyle$deleteresult["message"]);
  932.             header('Location: ' $registeredWatchesLinkGenerator->generate($watch));
  933.             exit;
  934.         }
  935.         //Warranty upload
  936.         if ($request->getMethod() === "POST" && $warrantyFileUploaded $request->files->get('warrantyFile')) {
  937.             $saveresult $this->saveWarranty(
  938.                 $watch,
  939.                 $warrantyFileUploaded,
  940.                 $uploader,
  941.                 ['warrantyMimeValidator' => $this->allowedWarrantyMimeTypes'maxWarrantyValidator' => $maxWarrantyFiles],
  942.                 $logger
  943.             );
  944.             if ($saveresult["errors"] !== false) {
  945.                 $this->addFlash('error'$saveresult["message"]);
  946.             }
  947.             if ($saveresult["errors"] === false) {
  948.                 $limiter $anonymousApiLimiter->create($request->getClientIp());
  949.                 if ($limiter) {
  950.                     if ($limiter->consume(1)->isAccepted()) {
  951.                         $mailerService->sendWarrantyMail($watch$customer);
  952.                     }
  953.                 }
  954.                 $this->addFlash('succes''Az új garancia dokumentumok sikeresen hozzáadva');
  955.             }
  956.             header('Location: ' $registeredWatchesLinkGenerator->generate($watch));
  957.             exit;
  958.         }
  959.         return $this->render($this->templateConfigurator->findTemplate('Customer/registered_watches.html'), array_merge([
  960.             'clubsite' => $this->isSite('club'),
  961.             'customer' => $customer,
  962.             'watch' => $watch,
  963.             'product' => $product,
  964.             'minDate' => Carbon::parse('2000-01-01'),
  965.             'statusValues' => DataObject\Service::getOptionsForSelectField('Pimcore\Model\DataObject\RegisteredWatch'"status"),
  966.             'repair_list' => $sheet_list->getItems(),
  967.             'repairsheet_type_names' => $this->getWatchRepairConstants()['WATCH_REPAIR_SHEET_TYPE_NAMES'],
  968.             'repair_paginator' => $sheet_list,
  969.             'newWatchRepairForm' => $newUserReportForm->createView(),
  970.             'deleteForm' => $deleteForm->createView(),
  971.             'maxWarrantyFiles' => $maxWarrantyFiles,
  972.             'maxWatchRepairFiles' => $this->maxWatchRepairFiles,
  973.             'state' => $state
  974.         ], $watchRepairManager->getWatchRepairEventsAssociative($watch)));
  975.     }
  976.     /**
  977.      * @param Request $request
  978.      * @return Response
  979.      * @Route("/profil/regisztralt-orak/{slug}~w{id}/garancia.pdf", name="profile_registered_watch_warrantypdf")
  980.      */
  981.     public function registeredWatchWarrantyPDFAction(
  982.         Request $request,
  983.                 $slug,
  984.                 $id
  985.     ): Response
  986.     {
  987.         $this->denySite('prospex');
  988.         $customer $this->getCustomer();
  989.         if (!$customer instanceof CustomerInterface) {
  990.             return $this->redirect('/profil');
  991.         }
  992.         $watch RegisteredWatch::getById($request->get('id'));
  993.         if (!$watch instanceof RegisteredWatch || $watch->getStatus() === 'deleted') {
  994.             return $this->redirectToRoute('profile_registered_watch_list');
  995.         }
  996.         if ($customer->getId() !== $watch->getCustomer()->getId()) {
  997.             return $this->redirectToRoute('profile_registered_watch_list');
  998.         }
  999.         $stream $this->warrantyPdfControllerAction(
  1000.             $watch,
  1001.             $this->container->getParameter('app.date_format'),
  1002.             $this->warrantyPDFPath
  1003.         );
  1004.         return new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($stream) {
  1005.             fpassthru($stream);
  1006.         }, 200, [
  1007.             'Content-Type' => 'application/pdf'
  1008.         ]);
  1009.     }
  1010.     /**
  1011.      * @param Request $request
  1012.      * @return Response
  1013.      * @Route("/profil/szerviz/worksheet/{slug}~w{id}", name="profile_watch_repair_detail")
  1014.      */
  1015.     public function watchRepairDetailsAction(
  1016.         Request            $request,
  1017.         FileUploader       $uploader,
  1018.         PaginatorInterface $paginator,
  1019.         int                $id
  1020.     ): Response
  1021.     {
  1022.         $this->denySite('prospex');
  1023.         $customer $this->getCustomer();
  1024.         if (!$customer instanceof CustomerInterface) {
  1025.             return $this->redirect('/profil');
  1026.         }
  1027.         $watchRepair WatchRepair::getById($request->get('id'));
  1028.         if (!$watchRepair instanceof WatchRepair) {
  1029.             return $this->redirectToRoute('profile_watch_repair_list');
  1030.         }
  1031.         $watch $watchRepair->getRegisteredWatch();
  1032.         $watchId $watch->getId();
  1033.         $product $this->getProductFromWatch($watch);
  1034.         //Newremark form
  1035.         $newRemarkForm $this->container->get('form.factory')->createNamed(
  1036.             'newremarkform'RemarkType::class, null, [
  1037.                 'remark-id' => false
  1038.             ]
  1039.         );
  1040.         $newRemarkForm->handleRequest($request);
  1041.         //Update remark form
  1042.         $updateRemarkForm $this->container->get('form.factory')->createNamed(
  1043.             'updateremark'RemarkType::class
  1044.         );
  1045.         $updateRemarkForm->handleRequest($request);
  1046.         //Remark modifications, additions, deletions
  1047.         $remarkActionsValid $this->remarkDesktopActions(
  1048.             $request,
  1049.             $uploader,
  1050.             $newRemarkForm,
  1051.             $updateRemarkForm,
  1052.             $watchId,
  1053.             $id
  1054.         );
  1055.         if ($remarkActionsValid) {
  1056.             return $this->redirect($request->getUri());
  1057.         }
  1058.         $remarks WatchRepairRemark::getByWatchRepairParent($watchRepair);
  1059.         if (!$remarks instanceof \Pimcore\Model\DataObject\WatchRepairRemark\Listing) {
  1060.             return $this->redirectToRoute('profile_registered_watch_list');
  1061.         }
  1062.         $remarks->setOrder('desc')->setOrderKey('oo_id');
  1063.         $remark_list $paginator->paginate(
  1064.             $remarks,
  1065.             (int)$request->get('page'1),
  1066.             $this->getWatchRepairConstants()['REMARK_PER_PAGE']
  1067.         );
  1068.         $remarks = [];
  1069.         foreach ($remark_list as $remark) {
  1070.             $remarks[] = $this->remarkObjectWithAdditions($remark$customer);
  1071.         }
  1072.         $bc = [
  1073.             ['title' => 'Főoldal''path' => '/'],
  1074.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  1075.             ['title' => 'Regisztrált órák''path' => $this->generateUrl('profile_registered_watch_list')],
  1076.             [
  1077.                 'title' => sprintf("%s - %s"$watch->getSerial(), $watch->getMechanismNumber()),
  1078.                 'path' => $this->generateUrl('profile_registered_watch', [
  1079.                     'id' => $watch->getId(),
  1080.                     'slug' => sprintf("%s - %s"$watch->getSerial(), $watch->getMechanismNumber()),
  1081.                 ]),
  1082.             ],
  1083.             ['title' => sprintf("Munkalap %s"$watchRepair->getWorksheetNumber()), 'path' => null]
  1084.         ];
  1085.         $pl $this->placeholder;
  1086.         $pl('breadcrumbNews')->set($bc);
  1087.         return $this->render($this->templateConfigurator->findTemplate('Customer/watch_repair_detail.html'), [
  1088.             'clubsite' => $this->isSite('club'),
  1089.             'customer' => $customer,
  1090.             'minDate' => Carbon::parse('2000-01-01'),
  1091.             'watchRepair' => $watchRepair,
  1092.             'newRemarkForm' => $newRemarkForm->createView(),
  1093.             'updateRemarkForm' => $updateRemarkForm->createView(),
  1094.             'product' => $product,
  1095.             'remarks' => $remarks,
  1096.             'remark_paginator' => $remark_list,
  1097.             'maxWatchRepairFiles' => $this->maxWatchRepairFiles
  1098.         ]);
  1099.     }
  1100.     /**
  1101.      * @param Request $request
  1102.      * @return Response
  1103.      * @Route("/profil/szerviz/userreport/w{id}", name="profile_watch_repair_user_report_detail")
  1104.      */
  1105.     public function watchRepairUserReportDetailsAction(
  1106.         Request            $request,
  1107.         FileUploader       $uploader,
  1108.         PaginatorInterface $paginator,
  1109.         int                $id,
  1110.         WatchRepairManager $watchRepairManager
  1111.     ): Response
  1112.     {
  1113.         $this->denySite('prospex');
  1114.         $customer $this->getCustomer();
  1115.         if (!$customer instanceof CustomerInterface) {
  1116.             return $this->redirect('/profil');
  1117.         }
  1118.         $watchRepairUserReport WatchRepairUserReport::getById($request->get('id'));
  1119.         if (!$watchRepairUserReport instanceof WatchRepairUserReport) {
  1120.             return $this->redirectToRoute('profile_registered_watch_list');
  1121.         }
  1122.         $watch $watchRepairUserReport->getRegisteredWatch();
  1123.         $watchCustomer $watch->getCustomer();
  1124.         if ($watchCustomer->getId() !== $customer->getId()) {
  1125.             return $this->redirectToRoute('profile_registered_watch_list');
  1126.         }
  1127.         $product $this->getProductFromWatch($watch);
  1128.         $watchId $watch->getId();
  1129.         //WatchRepairUserreport updafte form
  1130.         $userReportUpdateForm $this->container->get('form.factory')->createNamed(
  1131.             'userreportupdateform'UserReportType::class, null, [
  1132.                 'image-inputs' => false'remark-text' => false
  1133.             ]
  1134.         );
  1135.         $userReportUpdateForm->handleRequest($request);
  1136.         //UserReport actions
  1137.         $userReportActionValid $this->userReportDesktopActions(
  1138.             $userReportUpdateForm,
  1139.             $watchId,
  1140.             $id
  1141.         );
  1142.         //Newremark form
  1143.         $newRemarkForm $this->container->get('form.factory')->createNamed(
  1144.             'newremarkform'RemarkType::class, null, [
  1145.                 'remark-id' => false
  1146.             ]
  1147.         );
  1148.         $newRemarkForm->handleRequest($request);
  1149.         //Update remark form
  1150.         $updateRemarkForm $this->container->get('form.factory')->createNamed(
  1151.             'updateremark'RemarkType::class
  1152.         );
  1153.         $updateRemarkForm->handleRequest($request);
  1154.         //Remark modifications, additions, deletions
  1155.         $remarkActionValid $this->remarkDesktopActions(
  1156.             $request,
  1157.             $uploader,
  1158.             $newRemarkForm,
  1159.             $updateRemarkForm,
  1160.             $watchId,
  1161.             $id
  1162.         );
  1163.         if ($remarkActionValid || $userReportActionValid) {
  1164.             return $this->redirect($request->getUri());
  1165.         }
  1166.         $remarks WatchRepairRemark::getByWatchRepairParent($watchRepairUserReport);
  1167.         if (!$remarks instanceof \Pimcore\Model\DataObject\WatchRepairRemark\Listing) {
  1168.             return $this->redirectToRoute('profile_registered_watch_list');
  1169.         }
  1170.         $remarks->setOrder('desc')->setOrderKey('oo_id');
  1171.         $remark_list $paginator->paginate(
  1172.             $remarks,
  1173.             (int)$request->get('page'1),
  1174.             $this->getWatchRepairConstants()['REMARK_PER_PAGE']
  1175.         );
  1176.         $remarks = [];
  1177.         foreach ($remark_list as $remark) {
  1178.             $remarks[] = $this->remarkObjectWithAdditions($remark$customer);
  1179.         }
  1180.         $bc = [
  1181.             ['title' => 'Főoldal''path' => '/'],
  1182.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  1183.             ['title' => 'Regisztrált órák''path' => $this->generateUrl('profile_registered_watch_list')],
  1184.             [
  1185.                 'title' => sprintf("%s - %s"$watch->getSerial(), $watch->getMechanismNumber()),
  1186.                 'path' => $this->generateUrl('profile_registered_watch', [
  1187.                     'id' => $watch->getId(),
  1188.                     'slug' => sprintf("%s - %s"$watch->getSerial(), $watch->getMechanismNumber()),
  1189.                 ]),
  1190.             ],
  1191.         ];
  1192.         $pl $this->placeholder;
  1193.         $pl('breadcrumbNews')->set($bc);
  1194.         return $this->render($this->templateConfigurator->findTemplate('Customer/watch_repair_user_report_detail.html'),
  1195.             array_merge([
  1196.                     'clubsite' => $this->isSite('club'),
  1197.                     'customer' => $customer,
  1198.                     'minDate' => Carbon::parse('2000-01-01'),
  1199.                     'watchRepairUserReport' => $watchRepairUserReport,
  1200.                     'userReportUpdateForm' => $userReportUpdateForm->createView(),
  1201.                     'newRemarkForm' => $newRemarkForm->createView(),
  1202.                     'updateRemarkForm' => $updateRemarkForm->createView(),
  1203.                     'product' => $product,
  1204.                     'remarks' => $remarks,
  1205.                     'remark_paginator' => $remark_list,
  1206.                     'maxWatchRepairFiles' => $this->maxWatchRepairFiles
  1207.                 ]
  1208.                 , $watchRepairManager->getWatchRepairEventsAssociative($watch)));
  1209.     }
  1210.     /**
  1211.      * @param Request $request
  1212.      * @param WishListService $wishListService
  1213.      * @return Response
  1214.      * @Route("/profil/megtekintett-orak", name="recent_watches")
  1215.      */
  1216.     public function recentWatchesProfileAction(Request $requestWishListService $wishListService null): Response
  1217.     {
  1218.         $this->denySite('prospex');
  1219.         $customer $this->getCustomer();
  1220.         if (!$customer instanceof CustomerInterface) {
  1221.             return $this->redirect('/profil');
  1222.         }
  1223.         $lastViewedWatches DataObject\LastViewedWatches::getByCustomer($customer)->current();
  1224.         $watches $lastViewedWatches instanceof DataObject\LastViewedWatches $lastViewedWatches->getWatches() : [];
  1225.         $watchesId array_map(function ($watch) {//get ids
  1226.             return $watch->getElementId();
  1227.         }, $watches);
  1228.         $res = [];
  1229.         $wishlist = [];
  1230.         if (!empty($watchesId)) {
  1231.             $entries = new DataObject\CoreShopProduct\Listing();
  1232.             $entries->onCreateQueryBuilder(function (\Doctrine\DBAL\Query\QueryBuilder $queryBuilder) use ($watchesId) {
  1233.                 $queryBuilder->addOrderBy("FIELD(oo_id, " implode(","$watchesId) . ")");
  1234.             });
  1235.             $entries->setCondition("oo_id IN (?)", [$watchesId]);
  1236.             foreach ($entries as $entry) {
  1237.                 $res[] = $entry;
  1238.                 $wishlist[$entry->getId()] = $wishListService->hasItem($entry);
  1239.             }
  1240.         }
  1241.         if ($this->isSite('club')) {
  1242.             return $this->render($this->templateConfigurator->findTemplate('Customer/recentWatches.html'), [
  1243.                 'customer' => $customer,
  1244.                 'watches' => $res,
  1245.                 'clubsite' => $this->isSite('club'),
  1246.                 'boutiquesite' => $this->boutiqueHost,
  1247.             ]);
  1248.         }
  1249.         return $this->render($this->templateConfigurator->findTemplate('Customer/recentWatches.html'), [
  1250.             'customer' => $customer,
  1251.             'watches' => $res,
  1252.             'isWishListed' => $wishlist,
  1253.         ]);
  1254.     }
  1255.     /**
  1256.      * @Route("/regisztracio-megerosites", name="confirm-register")
  1257.      */
  1258.     public function confirmRegisterAction(
  1259.         Request              $request,
  1260.         MaileonService       $maileonService,
  1261.         MessageCenterService $messageCenterService
  1262.     ): Response
  1263.     {
  1264.         $this->denySite('prospex');
  1265.         $customer $this->getCustomer();
  1266.         if ($customer instanceof CustomerInterface) {
  1267.             return $this->redirect('/');
  1268.         }
  1269.         $token $this->getParameterFromRequest($request'token');
  1270.         if (!$token) {
  1271.             return $this->redirect('/');
  1272.         }
  1273.         $customer $this->container->get('coreshop.repository.customer')->findOneBy([
  1274.             'registrationToken' => $token,
  1275.             'pimcore_unpublished' => true
  1276.         ]);
  1277.         if (!$customer instanceof CoreShopCustomer) {
  1278.             return $this->redirect('/');
  1279.         }
  1280.         if ($customer instanceof CustomerInterface) {
  1281.             if ($customer->isPublished()) {
  1282.                 return $this->redirect('/');
  1283.             }
  1284.             $customer->setRegistrationToken(null);
  1285.             $customer->setPublished(true);
  1286.             VersionHelper::useVersioning(function () use ($customer) {
  1287.                 $customer->save();
  1288.             }, false);
  1289.             $triggers $this->container->getParameter('maileon_triggerNames');
  1290.             $messageCenterService->createMessageFromTemplateIfExists($customer'register_success');
  1291.             $maileonService->sendTriggeredMail($triggers[$customer->getMaileonTrigger('register_success')], $customer->getEmail());
  1292.             $this->addFlash('success''Sikeresen megerősítetted a regisztrációd');
  1293.         } else {
  1294.             $this->addFlash('success''A regisztráció megerősítése sikertelen volt');
  1295.         }
  1296.         return $this->redirectToRoute('profil');
  1297.     }
  1298.     /**
  1299.      * @param Request $request
  1300.      * @return Response
  1301.      * @Route("/profil/newsletter", name="coreshop_customer_newsletter")
  1302.      */
  1303.     public function newsletterAction(Request $request): Response
  1304.     {
  1305.         $this->denySite('prospex');
  1306.         $customer $this->getCustomer();
  1307.         if (!$customer instanceof CustomerInterface) {
  1308.             return $this->redirectToRoute('profil');
  1309.         }
  1310.         if ($request->getMethod() == 'POST') {
  1311.             $subscribe $request->request->get('subscribe');
  1312.             if ($subscribe == && !$customer->getNewsletterActive()) {
  1313.                 $customer->setNewsletterActive(true);
  1314.                 $customer->save();
  1315.                 $this->addFlash('success''Sikeresen feliratkoztál a Seiko hírlevelére');
  1316.             }
  1317.             if ($subscribe == && $customer->getNewsletterActive()) {
  1318.                 $customer->setNewsletterActive(false);
  1319.                 $customer->setMagazineSubscribed(false);
  1320.                 $customer->setMagazineSubscriptionDate(null);
  1321.                 $this->addFlash('success''Sikeresen leiratkoztál a Seiko hírelvélről és ezzel együtt a Seiko Magazinról is.');
  1322.                 $customer->save();
  1323.             }
  1324. //            $this->eventDispatcher->dispatch(new GenericEvent($customer, []), 'customer.newsletter.subscription');
  1325.             return $this->redirectToRoute('coreshop_customer_newsletter');
  1326.         }
  1327.         $bc = [
  1328.             [
  1329.                 'title' => 'Főoldal',
  1330.                 'path' => '/'
  1331.             ],
  1332.             [
  1333.                 'title' => 'Profil',
  1334.                 'path' => $this->generateUrl('profil')
  1335.             ],
  1336.             [
  1337.                 'title' => 'Hírlevél',
  1338.                 'path' => null
  1339.             ]
  1340.         ];
  1341.         $pl $this->placeholder;
  1342.         $pl('breadcrumbNews')->set($bc);
  1343.         return $this->render($this->templateConfigurator->findTemplate('Customer/newsletter.html'), [
  1344.             'customer' => $customer,
  1345.         ]);
  1346.     }
  1347.     /**
  1348.      * @param Request $request
  1349.      * @return Response
  1350.      * @Route("/profil/magazin", name="coreshop_customer_magazine")
  1351.      */
  1352.     public function magazineAction(Request $request): Response
  1353.     {
  1354.         return $this->redirectToRoute('profile_subscriptions');
  1355.         $this->denySite('prospex');
  1356.         $customer $this->getCustomer();
  1357.         if (!$customer instanceof CustomerInterface) {
  1358.             return $this->redirectToRoute('profil');
  1359.         }
  1360.         if ($request->getMethod() == 'POST') {
  1361.             $subscribe $request->request->get('subscribe');
  1362.             if ($subscribe == && !$customer->getMagazineSubscribed()) {
  1363.                 $customer->setMagazineSubscribed(true);
  1364.                 $customer->setMagazineSubscriptionDate(new Carbon());
  1365.                 $customer->setNewsletterActive(true);
  1366.                 $customer->save();
  1367.                 $this->addFlash('success''Sikeresen feliratkoztál a Seiko Magazinra');
  1368.             }
  1369.             if ($subscribe == && $customer->getMagazineSubscribed()) {
  1370.                 $customer->setMagazineSubscribed(false);
  1371.                 $customer->setMagazineSubscriptionDate(null);
  1372.                 $customer->save();
  1373.                 $this->addFlash('success''Sikeresen leiratkoztál a Seiko Magazinról és a hírlevélről');
  1374.             }
  1375. //            $this->eventDispatcher->dispatch(new GenericEvent($customer, []), 'customer.magazine.subscription');
  1376.             return $this->redirectToRoute('coreshop_customer_magazine');
  1377.         }
  1378.         $bc = [
  1379.             [
  1380.                 'title' => 'Főoldal',
  1381.                 'path' => '/'
  1382.             ],
  1383.             [
  1384.                 'title' => 'Profil',
  1385.                 'path' => $this->generateUrl('profil')
  1386.             ],
  1387.             [
  1388.                 'title' => 'Magazin',
  1389.                 'path' => null
  1390.             ]
  1391.         ];
  1392.         $pl $this->placeholder;
  1393.         $pl('breadcrumbNews')->set($bc);
  1394.         return $this->render($this->templateConfigurator->findTemplate('Customer/magazine.html'), [
  1395.             'customer' => $customer,
  1396.         ]);
  1397.     }
  1398.     public function addressesAction(): Response
  1399.     {
  1400.         $this->denySite('prospex');
  1401.         if (Site::isSiteRequest()) {
  1402.             throw $this->createNotFoundException('Page not found!');
  1403.         }
  1404.         $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ADDRESSES');
  1405.         $bc = [
  1406.             [
  1407.                 'title' => 'Főoldal',
  1408.                 'path' => '/'
  1409.             ],
  1410.             [
  1411.                 'title' => 'Profil',
  1412.                 'path' => $this->generateUrl('profil')
  1413.             ],
  1414.             [
  1415.                 'title' => 'Személyes adatok',
  1416.                 'path' => null
  1417.             ]
  1418.         ];
  1419.         $pl $this->placeholder;
  1420.         $pl('breadcrumbNews')->set($bc);
  1421.         return $this->redirectToRoute('profile_profiledata');
  1422.     }
  1423.     public function addressAction(Request $request): Response
  1424.     {
  1425.         $this->denySite('prospex');
  1426.         $customer $this->getCustomer();
  1427.         if (!$customer instanceof CustomerInterface) {
  1428.             return $this->redirectToRoute('coreshop_index');
  1429.         }
  1430.         $address $this->container->get('coreshop.repository.address')->find($this->getParameterFromRequest($request'address'));
  1431.         if ($address instanceof AddressInterface) {
  1432.             $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ADDRESS_EDIT');
  1433.         } else {
  1434.             $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ADDRESS_ADD');
  1435.         }
  1436.         $translator $this->container->get('translator');
  1437.         $addressAssignmentManager $this->container->get(AddressAssignmentManagerInterface::class);
  1438.         $addressIdentifierRepository $this->container->get('coreshop.repository.address_identifier');
  1439.         $customerInvoiceAddress $customer->getInvoiceAddress();
  1440.         $customerShippingAddress $customer->getShippingAddress();
  1441.         $customerMagazineAddress $customer->getMagazineAddress();
  1442.         $customerHasInvoiceAddress $customer->hasAddressIdf()['invoice'];
  1443.         $customerHasShippingAddress $customer->hasAddressIdf()['shipping'];
  1444.         $customerHasMagazineAddress $customer->hasAddressIdf()['magazine'];
  1445.         //Calculate the default addressIdf
  1446.         $defaultIdentifier $this->getDefaultAddressIdentifier($customerInvoiceAddress$customerShippingAddress$customerMagazineAddress);
  1447.         $addressIdentifierParam $request->query->get('address_identifier'$defaultIdentifier);
  1448.         if (!in_array($addressIdentifierParam, ['invoice''shipping''magazine'], true)) {
  1449.             $addressIdentifierParam $defaultIdentifier;
  1450.         }
  1451.         $customerHasAddressWithThisAddrIdfParam = (
  1452.             ($addressIdentifierParam === 'invoice' && $customerHasInvoiceAddress) ||
  1453.             ($addressIdentifierParam === 'shipping' && $customerHasShippingAddress) ||
  1454.             ($addressIdentifierParam === 'magazine' && $customerHasMagazineAddress)
  1455.         );
  1456.         $eventType 'update';
  1457.         if (!$address instanceof AddressInterface) {
  1458.             $eventType 'add';
  1459.             if ($customerHasAddressWithThisAddrIdfParam) {
  1460.                 $this->addFlash('error''Csak egy ' strtolower($translator->trans(sprintf('coreshop.ui.%s_address'$addressIdentifierParam))) . ' lehet!');
  1461.             }
  1462.             /** @var AddressInterface $address */
  1463.             $address $this->container->get('coreshop.factory.address')->createNew();
  1464.             $addressIdentifier $addressIdentifierRepository->findByName($addressIdentifierParam);
  1465.             if ($addressIdentifier instanceof AddressIdentifierInterface) {
  1466.                 $address->setAddressIdentifier($addressIdentifier);
  1467.             }
  1468.         }
  1469.         $isNewAddress $eventType === 'add';
  1470.         if ($eventType === 'update' && $addressAssignmentManager->checkAddressAffiliationPermissionForCustomer($customer$address) === false) {
  1471.             return $this->redirectToRoute('profile_profiledata');
  1472.         }
  1473.         $addressFormOptions = [
  1474.             'available_affiliations' => $addressAssignmentManager->getAddressAffiliationTypesForCustomer($customer),
  1475.             'selected_affiliation' => $addressAssignmentManager->detectAddressAffiliationForCustomer($customer$address),
  1476.             'show_address_identifier_choice' => $isNewAddress,
  1477.             'eventType' => $eventType,
  1478.             'customerHasInvoiceAddress' => $customerHasInvoiceAddress,
  1479.             'customerHasShippingAddress' => $customerHasShippingAddress,
  1480.             'customerHasMagazineAddress' => $customerHasMagazineAddress
  1481.         ];
  1482.         if ($isNewAddress) {
  1483.             $this->initializeNewAddress($customer$address);
  1484.         }
  1485.         $form $this->container->get('form.factory')->createNamed('coreshop'AddressType::class, $address$addressFormOptions);
  1486.         if (in_array($request->getMethod(), ['POST''PUT''PATCH'], true)) {
  1487.             $handledForm $form->handleRequest($request);
  1488.             $addressAffiliation $form->has('addressAffiliation') ? $form->get('addressAffiliation')->getData() : null;
  1489.             if ($handledForm->isSubmitted() && $handledForm->isValid()) {
  1490.                 /** @var DataObject\CoreShopAddress $address */
  1491.                 $address $handledForm->getData();
  1492.                 $address->setPublished(true);
  1493.                 $address->setKey(uniqid(more_entropytrue));
  1494.                 $isInvoiceAddress $address->getAddressIdentifier()?->getName() === 'invoice';
  1495.                 $isShippingAddress $address->getAddressIdentifier()?->getName() === 'shipping';
  1496.                 $isMagazineAddress $address->getAddressIdentifier()?->getName() === 'magazine';
  1497.                 if ($isMagazineAddress) {
  1498.                     if ($customerMagazineAddress && $isNewAddress) {
  1499.                         $this->addFlash('error''Csak egy Magazin címe lehet!');
  1500.                         return $this->redirectToRoute('profile_profiledata');
  1501.                     }
  1502.                     $address->setIsCompanyBill(null);
  1503.                     $address->setCompanyName(null);
  1504.                     $address->setCompanyTaxNumber(null);
  1505.                 } else if (!$address->getIsCompanyBill()) {
  1506.                     $address->setCompanyName(null);
  1507.                     $address->setCompanyTaxNumber(null);
  1508.                 }
  1509.                 $phoneNumber HelperFunctions::formatPhoneNumber($address->getPhoneNumber());
  1510.                 if ($phoneNumber !== $address->getPhoneNumber()) {
  1511.                     $address->setPhoneNumber($phoneNumber);
  1512.                 }
  1513.                 if (!$customer->getPhoneNumber()) {
  1514.                     $customer->setPhoneNumber($address->getPhoneNumber());
  1515.                     $customer->save();
  1516.                 }
  1517.                 $address $addressAssignmentManager->allocateAddressByAffiliation($customer$address$addressAffiliation);
  1518.                 $this->fireEvent($request$addresssprintf('%s.%s.%s_post''coreshop''address'$eventType));
  1519.                 //Invoice copy
  1520.                 if (!$isInvoiceAddress && $isNewAddress && $handledForm->get('isInvoiceAddress')->getData()) {
  1521.                     $this->copyAddressToIdentifier(
  1522.                         $request,
  1523.                         $customerHasInvoiceAddress,
  1524.                         $addressIdentifierRepository->findByName('invoice'),
  1525.                         $customerInvoiceAddress,
  1526.                         $address,
  1527.                         $addressAssignmentManager,
  1528.                         $customer,
  1529.                         $addressAffiliation,
  1530.                         $eventType,
  1531.                         $translator->trans('coreshop.ui.customer.address_successfully_added_copied_to_invoice')
  1532.                     );
  1533.                 }
  1534.                 //Shipping copy
  1535.                 if (!$isShippingAddress && $isNewAddress && $handledForm->get('isShippingAddress')->getData()) {
  1536.                     $this->copyAddressToIdentifier(
  1537.                         $request,
  1538.                         $customerHasShippingAddress,
  1539.                         $addressIdentifierRepository->findByName('shipping'),
  1540.                         $customerShippingAddress,
  1541.                         $address,
  1542.                         $addressAssignmentManager,
  1543.                         $customer,
  1544.                         $addressAffiliation,
  1545.                         $eventType,
  1546.                         $translator->trans('coreshop.ui.customer.address_successfully_added_copied_to_shipping')
  1547.                     );
  1548.                 }
  1549.                 //Magazine copy
  1550.                 if (!$isMagazineAddress && $isNewAddress && $handledForm->get('isMagazineAddress')->getData()) {
  1551.                     $this->copyAddressToIdentifier(
  1552.                         $request,
  1553.                         $customerHasMagazineAddress,
  1554.                         $addressIdentifierRepository->findByName('magazine'),
  1555.                         $customerMagazineAddress,
  1556.                         $address,
  1557.                         $addressAssignmentManager,
  1558.                         $customer,
  1559.                         $addressAffiliation,
  1560.                         $eventType,
  1561.                         $translator->trans('coreshop.ui.customer.address_successfully_added_copied_to_magazine')
  1562.                     );
  1563.                 }
  1564.                 $this->addFlash('success'$translator->trans(sprintf('coreshop.ui.customer.address_successfully_%s'$isNewAddress 'added' 'updated')));
  1565.                 return $this->redirect($this->getParameterFromRequest($request'_redirect'$this->generateUrl('profile_profiledata')));
  1566.             }
  1567.         }
  1568.         $title sprintf($isNewAddress "Új %s felvétele" '%s módosítása',
  1569.             strtolower($translator->trans(sprintf('coreshop.ui.%s_address'$address->getAddressIdentifier()?->getName())))
  1570.         );
  1571.         $bc = [
  1572.             ['title' => 'Főoldal''path' => '/'],
  1573.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  1574.             ['title' => 'Személyes adatok''path' => $this->generateUrl('coreshop_customer_addresses')],
  1575.             ['title' => $title'path' => null]
  1576.         ];
  1577.         $pl $this->placeholder;
  1578.         $pl('breadcrumbNews')->set($bc);
  1579.         return $this->render($this->templateConfigurator->findTemplate('Customer/address.html'), [
  1580.             'address' => $address,
  1581.             'customer' => $customer,
  1582.             'title' => $title,
  1583.             'warnInvoiceAddress' => $address->getAddressIdentifier()?->getName() !== 'invoice' && $customerHasInvoiceAddress,
  1584.             'warnShippingAddress' => $address->getAddressIdentifier()?->getName() !== 'shipping' && $customerHasShippingAddress,
  1585.             'warnMagazineAddress' => $address->getAddressIdentifier()?->getName() !== 'magazine' && $customerHasMagazineAddress,
  1586.             'form' => $form->createView(),
  1587.             'customerHasAllAddresses' => $isNewAddress && $customerHasInvoiceAddress && $customerHasShippingAddress && $customerHasMagazineAddress,
  1588.             'customerHasAddressWithThisAddrIdfParam' => $customerHasAddressWithThisAddrIdfParam
  1589.         ]);
  1590.     }
  1591.     private function getDefaultAddressIdentifier($invoice$shipping$magazine): ?string
  1592.     {
  1593.         $allTypes = ['invoice''shipping''magazine'];
  1594.         $available array_filter([
  1595.             'invoice' => $invoice,
  1596.             'shipping' => $shipping,
  1597.             'magazine' => $magazine,
  1598.         ]);
  1599.         $existing array_keys($available);
  1600.         $missing array_values(array_diff($allTypes$existing));
  1601.         return count($existing) < && count($missing) > $missing[0] : null;
  1602.     }
  1603.     private function initializeNewAddress(CustomerInterface $customerAddressInterface $address): void
  1604.     {
  1605.         $address->setFirstname($customer->getFirstname());
  1606.         $address->setLastname($customer->getLastname());
  1607.         if (($phoneNumber $customer->getPhoneNumber())) {
  1608.             $address->setPhoneNumber(HelperFunctions::formatPhoneNumber($phoneNumber));
  1609.         }
  1610.     }
  1611.     private function copyAddressToIdentifier(
  1612.         Request                     $request,
  1613.         bool                        $customerHasAddress,
  1614.         ?AddressIdentifierInterface $identifierType,
  1615.         ?CoreshopAddress            $customerAddress,
  1616.         CoreshopAddress             $address,
  1617.                                     $addressAssignmentManager,
  1618.         CoreShopCustomer            $customer,
  1619.                                     $addressAffiliation,
  1620.         string                      $eventType,
  1621.         string                      $flashMessage
  1622.     ): void
  1623.     {
  1624.         if (!$customerHasAddress) {
  1625.             $customerAddress = new CoreShopAddress();
  1626.             $customerAddress->setPublished(true);
  1627.             $customerAddress->setKey(uniqid(more_entropytrue));
  1628.             $customerAddress->setAddressIdentifier($identifierType);
  1629.         }
  1630.         $customerAddress->setFirstname($address->getFirstname());
  1631.         $customerAddress->setLastname($address->getLastname());
  1632.         $customerAddress->setCountry($address->getCountry());
  1633.         $customerAddress->setPhoneNumber($address->getPhoneNumber());
  1634.         $customerAddress->setPostcode($address->getPostcode());
  1635.         $customerAddress->setCity($address->getCity());
  1636.         $customerAddress->setStreet($address->getStreet());
  1637.         $customerAddress->setNumber($address->getNumber());
  1638.         $customerAddress->setComment($address->getComment());
  1639.         $customerAddress $addressAssignmentManager->allocateAddressByAffiliation($customer$customerAddress$addressAffiliation);
  1640.         $this->fireEvent($request$customerAddresssprintf('%s.%s.%s_post''coreshop''address'$eventType));
  1641.         $this->addFlash('success'$flashMessage);
  1642.     }
  1643.     public function orderListAction(Request $requestPaginatorInterface $paginator): Response
  1644.     {
  1645.         $this->denySite('prospex');
  1646.         $this->denySite('club');
  1647.         $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDERS');
  1648.         $customer $this->getCustomer();
  1649.         if (!$customer instanceof CustomerInterface) {
  1650.             return $this->redirectToRoute('coreshop_index');
  1651.         }
  1652.         $bc = [
  1653.             [
  1654.                 'title' => 'Főoldal',
  1655.                 'path' => '/'
  1656.             ],
  1657.             [
  1658.                 'title' => 'Profil',
  1659.                 'path' => $this->generateUrl('profil')
  1660.             ],
  1661.             [
  1662.                 'title' => 'Rendeléseim',
  1663.                 'path' => null
  1664.             ]
  1665.         ];
  1666.         $pl $this->placeholder;
  1667.         $pl('breadcrumbNews')->set($bc);
  1668.         $orders CoreShopOrder::getByCustomer($customer);
  1669.         $orders->setCondition("orderState NOT IN ('new', 'initialized')");
  1670.         $orders->setOrderKey('o_id');
  1671.         $orders->setOrder('desc');
  1672.         $page = (int)$request->get('page'1);
  1673.         $list $paginator->paginate(
  1674.             $orders,
  1675.             $page,
  1676.             20
  1677.         );
  1678.         $shipmentState = [];
  1679.         foreach ($list->getItems() as $order) {
  1680.             $shipmentState[$order->getId()] = $this->getShipmentStateByOrder($order);
  1681.         }
  1682.         return $this->render($this->templateConfigurator->findTemplate('Customer/orders.html'), [
  1683.             'customer' => $customer,
  1684.             'list' => $list->getItems(),
  1685.             'shipmentState' => $shipmentState,
  1686.             'paginator' => $list,
  1687.         ]);
  1688.     }
  1689.     public function orderDetailsAction(Request $request): Response
  1690.     {
  1691.         $this->denySite('prospex');
  1692.         $this->denySite('club');
  1693.         $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDER_DETAIL');
  1694.         $orderId $this->getParameterFromRequest($request'order');
  1695.         $customer $this->getCustomer();
  1696.         if (!$customer instanceof CustomerInterface) {
  1697.             return $this->redirectToRoute('coreshop_index');
  1698.         }
  1699.         $order $this->get('coreshop.repository.order')->find($orderId);
  1700.         if (!$order instanceof CoreShopOrder) {
  1701.             return $this->redirectToRoute('coreshop_customer_orders');
  1702.         }
  1703.         if (!$order->getCustomer() instanceof CustomerInterface || $order->getCustomer()->getId() !== $customer->getId()) {
  1704.             return $this->redirectToRoute('coreshop_customer_orders');
  1705.         }
  1706.         $shipments $this->orderShipmentRepository->getDocuments($order);
  1707.         $shipmentButtons array_filter(
  1708.             array_map(function ($shipment) {
  1709.                 $carrierIdentifier $shipment->getCarrier()->getIdentifier();
  1710.                 $trackingCode $shipment->getTrackingCode();
  1711.                 if (!is_string($carrierIdentifier) || !is_string($trackingCode)
  1712.                 ) {
  1713.                     return null;
  1714.                 }
  1715.                 if (!in_array($carrierIdentifier$this->carrier['tracking']['allowedcarriers']) || $shipment->getState() !== 'shipped') {
  1716.                     return null;
  1717.                 }
  1718.                 $trackingUrlPrefix $this->carrier['tracking']['urls'][$carrierIdentifier] ?? null;
  1719.                 return $trackingUrlPrefix && $trackingCode ? ['trackingCode' => $trackingCode'url' => $trackingUrlPrefix] : null;
  1720.             }, $shipments)
  1721.         );
  1722.         $shipment = ['buttons' => $shipmentButtons'state' => $this->getShipmentStateByOrder($order)];
  1723.         $bc = [
  1724.             [
  1725.                 'title' => 'Főoldal',
  1726.                 'path' => '/'
  1727.             ],
  1728.             [
  1729.                 'title' => 'Profil',
  1730.                 'path' => $this->generateUrl('profil')
  1731.             ],
  1732.             [
  1733.                 'title' => 'Rendeléseim',
  1734.                 'path' => $this->generateUrl('coreshop_customer_orders')
  1735.             ],
  1736.             [
  1737.                 'title' => 'Rendelés megtekintése',
  1738.                 'path' => null
  1739.             ]
  1740.         ];
  1741.         $pl $this->placeholder;
  1742.         $pl('breadcrumbNews')->set($bc);
  1743.         $noteList = new Note\Listing();
  1744.         $noteList->addConditionParam('type = ?'Notes::NOTE_ORDER_COMMENT);
  1745.         $noteList->addConditionParam('cid = ?'$order->getId());
  1746.         $noteList->setOrderKey('date');
  1747.         $noteList->setOrder('desc');
  1748.         $comments = [];
  1749.         foreach ($noteList as $note) {
  1750.             if (!empty($note->getData()['submitAsEmail']['data'])) {
  1751.                 $comments[] = $note->getDescription();
  1752.             }
  1753.         }
  1754.         CoreShopProduct::setHideUnpublished(false);
  1755.         return $this->render($this->templateConfigurator->findTemplate('Customer/order_detail.html'), [
  1756.             'customer' => $customer,
  1757.             'order' => $order,
  1758.             'shipment' => $shipment,
  1759.             'comments' => array_filter($comments),
  1760.             'orderHistory' => true,
  1761.         ]);
  1762.     }
  1763.     /**
  1764.      * @Route("/profil/cim_torles/{name}~a{addressId}", name="customer_delete_address", requirements={"name"=".+"})
  1765.      */
  1766.     public function deleteAddress(Request $requestint $addressId): Response
  1767.     {
  1768.         $this->denySite('prospex');
  1769.         $customer $this->getCustomer();
  1770.         if (!$customer instanceof CustomerInterface) {
  1771.             return $this->redirectToRoute('coreshop_index');
  1772.         }
  1773.         $address CoreShopAddress::getById($addressId);
  1774.         if (!$address instanceof CoreShopAddress) {
  1775.             throw $this->createNotFoundException('Page not found!');
  1776.         }
  1777.         $found false;
  1778.         foreach ($customer->getAddresses() as $a) {
  1779.             if ($address->getId() === $a->getId()) {
  1780.                 $found true;
  1781.                 break;
  1782.             }
  1783.         }
  1784.         if (!$found) {
  1785.             throw $this->createNotFoundException('Page not found!');
  1786.         }
  1787.         $defaultRedirect 'profile_profiledata';
  1788.         $redirect $request->get('_redirect'$defaultRedirect);
  1789.         if (!in_array($redirect, ['profile_profiledata''profile_subscriptions'], true)) {
  1790.             $redirect $defaultRedirect;
  1791.         }
  1792.         $identifierTrans $this->container->get('translator')->trans(sprintf('coreshop.ui.%s_address'$address->getAddressIdentifier()?->getName()));
  1793.         $prevTitle 'Személyes adatok';
  1794.         $title "$identifierTrans törlése";
  1795.         if ($redirect === 'profile_subscriptions') {
  1796.             $prevTitle 'Feliratkozásaim';
  1797.         }
  1798.         $form $this->container->get('form.factory')->createNamed('deleteAccount'DeleteAccountType::class);
  1799.         $form->handleRequest($request);
  1800.         if ($form->isSubmitted() && $form->isValid() && $form->get('submit')?->isClicked()) {
  1801.             try {
  1802.                 if ($address->getAddressIdentifier()?->getName() === 'magazine') {
  1803.                     $customer->setMagazineSubscribed(false);
  1804.                     $customer->setMagazineIsActuallyNeed(false);
  1805.                     $customer->setMagazineSubscriptionDate(null);
  1806.                     $customer->save();
  1807.                 }
  1808.                 $address->delete();
  1809.                 $this->addFlash('success'sprintf("%se sikeresen törlésre került!"$identifierTrans));
  1810.             } catch (Exception) {
  1811.                 $this->addFlash('error''Hiba történt!');
  1812.             }
  1813.             return $this->redirectToRoute($redirect);
  1814.         }
  1815.         $bc = [
  1816.             ['title' => 'Főoldal''path' => '/'],
  1817.             ['title' => 'Profil''path' => $this->generateUrl('profil')],
  1818.             ['title' => $prevTitle'path' => $this->generateUrl($redirect)],
  1819.             ['title' => $title'path' => null]
  1820.         ];
  1821.         $pl $this->placeholder;
  1822.         $pl('breadcrumbNews')->set($bc);
  1823.         return $this->render($this->templateConfigurator->findTemplate('Customer/delete_address.html'), [
  1824.             'customer' => $customer,
  1825.             'address' => $address,
  1826.             'form' => $form->createView(),
  1827.             '_redirect' => $redirect
  1828.         ]);
  1829.     }
  1830. }