<?php
namespace App\Ecommerce\Controller;
use App\Form\Type\ChangeNameType;
use App\Form\Type\ChangePasswordType;
use App\Form\Type\DeleteAccountType;
use App\Form\Type\DeleteRegisteredWatchType;
use App\Form\Type\NotificationsFilterType;
use App\Form\Type\WatchesInterestType;
use App\Form\Type\WatchRegisterType;
use App\Form\Type\UserReportType;
use App\Form\Type\RemarkType;
use CoreShop\Component\Order\Notes;
use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3Validator;
use Pimcore\Model\Element\Note;
use App\Helpers\HelperFunctions;
use App\Maileon\MaileonService;
use App\Model\DataObject\RegisteredWatch as RegWatch;
use App\Service\AccountDeleteManager;
use App\Service\FileUploader;
use App\Service\MailerService;
use App\Service\MessageCenterService;
use App\Service\RegisteredWatchesManager;
use App\Service\WatchRepairManager;
use App\Service\WishListService;
use App\Traits\NotificationHelper;
use App\Traits\ExceptionHandlerTrait;
use App\Traits\GeneralTrait;
use App\Traits\OrderTrait;
use App\Traits\SiteAware;
use App\Traits\WatchWarranty;
use App\Traits\WatchRepairTrait;
use App\Traits\RegisteredWatch as RegisteredWatchTrait;
use App\Traits\Validator as ValidatorTrait;
use App\Traits\PDFTrait;
use App\Website\LinkGenerator\RegisteredWatchesLinkGenerator;
use Carbon\Carbon;
use CoreShop\Bundle\AddressBundle\Form\Type\AddressType;
use CoreShop\Bundle\FrontendBundle\Controller\CustomerController as BaseCustomerController;
use CoreShop\Component\Address\Model\AddressIdentifierInterface;
use CoreShop\Component\Address\Model\AddressInterface;
use CoreShop\Component\Core\Customer\Address\AddressAssignmentManagerInterface;
use CoreShop\Component\Core\Model\CustomerInterface;
use CoreShop\Component\Order\Repository\OrderShipmentRepositoryInterface;
use CoreShop\Component\Pimcore\DataObject\VersionHelper;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NativeQuery;
use Doctrine\ORM\Query\ResultSetMapping;
use Exception;
use Knp\Component\Pager\PaginatorInterface;
use Pimcore\Log\ApplicationLogger;
use Pimcore\Mail;
use Pimcore\Model\Asset;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\CoreShopAddress;
use Pimcore\Model\DataObject\CoreShopCustomer;
use Pimcore\Model\DataObject\CoreShopOrder;
use Pimcore\Model\DataObject\CoreShopProduct;
use Pimcore\Model\DataObject\CoreShopUser;
use Pimcore\Model\DataObject\Message;
use Pimcore\Model\DataObject\MessageCustomer;
use Pimcore\Model\DataObject\News;
use Pimcore\Model\DataObject\RegisteredWatch;
use Pimcore\Model\DataObject\WatchRepair;
use Pimcore\Model\DataObject\WatchRepairUserReport;
use Pimcore\Model\DataObject\WatchRepairRemark;
use Pimcore\Model\DataObject\Service;
use Pimcore\Model\Site;
use Pimcore\Twig\Extension\Templating\Placeholder;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Pimcore\Model\DataObject\Contact;
class CustomerController extends BaseCustomerController
{
use SiteAware;
use \App\Traits\ProductTrait;
use RegisteredWatchTrait;
use NotificationHelper;
use WatchWarranty;
use WatchRepairTrait;
use ValidatorTrait;
use ExceptionHandlerTrait;
use GeneralTrait;
use PDFTrait;
use OrderTrait;
protected $site;
public $maxWarrantyFiles;
public $maxWatchRepairFiles;
public $allowedWarrantyMimeTypes;
private string $warrantyPDFPath;
public $apiSettings;
public $carrier;
private const FILTER_ID = 'notificationsFilter';
private string $boutiqueHost;
private readonly OrderShipmentRepositoryInterface $orderShipmentRepository;
public function __construct(
private readonly Placeholder $placeholder,
private readonly EventDispatcherInterface $eventDispatcher,
$maxWarrantyFiles,
$maxWatchRepairFiles,
$allowedWarrantyMimeTypes,
string $warrantyPDFPath,
$apiSettings,
$carrier,
OrderShipmentRepositoryInterface $orderShipmentRepository,
private readonly MaileonService $maileonService
)
{
$this->maxWarrantyFiles = $maxWarrantyFiles;
$this->maxWatchRepairFiles = $maxWatchRepairFiles;
$this->allowedWarrantyMimeTypes = $allowedWarrantyMimeTypes;
$this->warrantyPDFPath = $warrantyPDFPath;
$this->apiSettings = $apiSettings;
$this->carrier = $carrier;
$this->orderShipmentRepository = $orderShipmentRepository;
// $this->site = \Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite() : null;
}
public function setBoutiqueHost(string $host): void
{
$this->boutiqueHost = $host;
}
/**
* @param Request $request
* @param Recaptcha3Validator $recaptcha3Validator
* @param ApplicationLogger $logger
* @return Response
* @Route("/watches_interest/{sku}", name="watches_modal")
*/
public function watchesinterestAction(Request $request, Recaptcha3Validator $recaptcha3Validator, ApplicationLogger $logger): Response
{
if (!$request->isXmlHttpRequest()) {
throw new AccessDeniedHttpException('Ez az útvonal csak XHR kéréseket fogad.');
}
if (Site::isSiteRequest()) {
throw $this->createNotFoundException('Page not found!');
}
$customer = $this->getCustomer();
$success = false;
$formData = new Contact();
$formData->setSubject($request->get('sku'));
if ($customer instanceof CustomerInterface) {
$formData->setFirstname($customer->getFirstname());
$formData->setLastname($customer->getLastname());
$formData->setEmail($customer->getEmail());
}
$form = $this->container->get('form.factory')->createNamed('watchesinterest', WatchesInterestType::class, $formData);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/* @var $data Contact */
$data = $form->getData();
$data->setPlatform('web');
try {
$data->save();
if (!$this->maileonService->getContactByEmail($data->getEmail())) {
$this->maileonService->insertOrUpdateContact([
'created' => date('Y-m-d H:i:s'),
'email' => $data->getEmail(),
'lastname' => $data->getLastname(),
'firstname' => $data->getFirstname(),
'permission' => 1
]);
}
$maileonData = $data->getMaileonData();
$maileonData['subject'] = sprintf("Érdeklődés: %s", $data->getSubject());
$this->maileonService->sendTriggeredMail('Watchesinterest', $data->getEmail(), $maileonData);
$mailConfig = $this->container->getParameter('mailingConfig');
foreach ($mailConfig['watches_interest']['addresses'] as $address) {
$this->maileonService->sendTriggeredMail('Watchesinterest', $address, $maileonData);
}
} catch (\Exception $e) {
$logger->error($e->getMessage(), ['component' => 'web-watches-intereset']);
}
$logger->info('Contact mail successfully sent', ['component' => 'watches-interest', 'relatedObject' => $data->getId()]);
$success = true;
}
return $this->render($this->templateConfigurator->findTemplate('Customer/watches_interest.html'), [
'form' => $form->createView(),
'success' => $success
]);
}
/**
* @param Request $request
* @param Recaptcha3Validator $recaptcha3Validator
* @param ApplicationLogger $logger
* @return Response
* @Route("/watches_modify/{id}", name="watches_modify_modal")
*/
public function watchesModifyAction(Request $request, Recaptcha3Validator $recaptcha3Validator, ApplicationLogger $logger): Response
{
if (!$request->isXmlHttpRequest()) {
throw new AccessDeniedHttpException('Ez az útvonal csak XHR kéréseket fogad.');
}
$this->denySite('prospex');
$customer = $this->getCustomer();
$success = false;
$watchId = $request->get('id');
$watch = RegisteredWatch::getById($watchId);
$formData = new Contact();
if ($watch instanceof RegisteredWatch) {
$formData->setSubject('Regisztrált óra - ' . $watch->getReference() . ' ' . $watch->getSerial() . ' ' . $watch->getMechanismNumber());
}
if ($customer instanceof CustomerInterface) {
$formData->setFirstname($customer->getFirstname());
$formData->setLastname($customer->getLastname());
$formData->setEmail($customer->getEmail());
}
$form = $this->container->get('form.factory')->createNamed('watchesinterest', WatchesInterestType::class, $formData);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/* @var $data Contact */
$data = $form->getData();
$textFormat = "Adatmódosítási kérelem érkezett\n\n";
$textFormat .= "Óra link: %s\n\n";
$textFormat .= "Óra: %s\n\n";
$textFormat .= "Név: %s %s\n";
$textFormat .= "E-mail: %s\n";
$textFormat .= "Telefon: %s\n";
$textFormat .= "Üzenet: %s\n\n";
$textFormat .= "Dátum: " . date("Y-m-d H:i:s") . "\n";
$text = sprintf($textFormat,
$this->boutiqueHost . "/seiko-bejelentkezo-oldal?deeplink=object_" . $watchId . "_object",
$data->getSubject(),
$customer->getLastname(),
$customer->getFirstname(),
$customer->getEmail(),
$data->getMobile() ?? 'N/A',
$data->getMessage() ?? 'N/A',
);
$mail = new Mail();
$mailConfig = $this->container->getParameter('mailingConfig');
foreach ($mailConfig['watches_modify']['addresses'] as $address) {
$mail->addTo($address);
}
if ($mailConfig['watches_modify']['subject']) {
$mail->subject($mailConfig['watches_modify']['subject']);
}
$mail->text($text);
$mail->disableLogging();
$mail->send();
$logger->info($text, ['component' => 'watches-modify']);
$success = true;
}
return $this->render($this->templateConfigurator->findTemplate('Customer/watches_modify.html'), [
'form' => $form->createView(),
'success' => $success
]);
}
/**
* @Route("/profil", name="profil")
*/
public function profileAction(?Request $request = null): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
$session = $request->getSession();
if ($loginRedirect = $request->get('login_redirect')) {
$session->set('login_redirect', $loginRedirect);
}
if (!$customer instanceof CustomerInterface) {
if ($loginRedirect) {
$this->addFlash('warning', 'Kérlek jelentkezz be a kosár használatához!');
}
return $this->forward('CoreShop\Bundle\FrontendBundle\Controller\RegisterController::registerAction');
}
if ($loginRedirect = $session->remove('login_redirect')) {
return $this->redirect($loginRedirect);
}
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
// return $this->redirectToRoute('profile_messages');
return $this->redirectToRoute('profile_profiledata');
}
/**
* @param Request $request
* @param AccountDeleteManager $manager
* @return Response
* @Route("/profil/fiokadatok", name="profile_profiledata")
*/
public function profiledataAction(Request $request, AccountDeleteManager $manager): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$defaultAddressIdentifier = $this->container->get('coreshop.repository.address_identifier')->findByName('invoice');
$addresses = $customer->getAddresses();
foreach ($addresses as $idx => $address) {
$save = false;
if (!$address->getAddressIdentifier() instanceof AddressIdentifierInterface) {
$address->setAddressIdentifier($defaultAddressIdentifier);
$save = true;
}
$phoneNumber = HelperFunctions::formatPhoneNumber($address->getPhoneNumber());
if (strlen($phoneNumber)) {
if ($phoneNumber !== $address->getPhoneNumber()) {
$address->setPhoneNumber($phoneNumber);
$save = true;
}
if ($save) {
$address->save();
}
} else {
if ($address->getAddressIdentifier()->getName() !== 'magazine') {
$address->delete();
unset($addresses[$idx]);
}
}
}
if (count($addresses) !== count($customer->getAddresses())) {
$customer->setAddresses($addresses);
$customer->save();
}
$passwordForm = $this->container->get('form.factory')->createNamed('changepassword', ChangePasswordType::class, $customer);
$nameForm = $this->container->get('form.factory')->createNamed('changename', ChangeNameType::class, $customer);
$passwordForm->handleRequest($request);
$nameForm->handleRequest($request);
if ($passwordForm->isSubmitted() && $passwordForm->isValid()) {
try {
/** @var CoreShopCustomer $customer */
$customer = $passwordForm->getData();
/** @var CoreShopUser $user */
$user = $customer->getUser();
$user->setPassword($user->getPlainPassword());
$user->save();
$customer->setUser($user);
$customer->save();
$this->addFlash('success', 'Sikeres jelszó változtatás!');
} catch (Exception $e) {
$this->addFlash('error', 'Hiba történt jelszó változtatás közben!');
}
return $this->redirectToRoute('profile_profiledata');
}
if ($nameForm->isSubmitted() && $nameForm->isValid()) {
try {
$customer = $nameForm->getData();
$customer->save();
$this->addFlash('success', 'Sikeres adat változtatás!');
} catch (Exception $e) {
$this->addFlash('error', 'Hiba történt adat változtatás közben!');
}
return $this->redirectToRoute('profile_profiledata');
}
$deleteForm = $this->container->get('form.factory')->createNamed(
'deleteAccount', DeleteAccountType::class
);
$deleteForm->handleRequest($request);
if ($deleteForm->isSubmitted() && $deleteForm->isValid() && $deleteForm->get('submit')?->isClicked()) {
try {
$this->container->get('security.token_storage')->setToken(null);
$manager->deleteAccount($customer);
$request->getSession()->invalidate(0);
return $this->redirectToRoute('coreshop_index');
} catch (Exception $e) {
$this->addFlash('error', 'Hiba történt!');
return $this->redirectToRoute('coreshop_index');
}
}
return $this->render($this->templateConfigurator->findTemplate('Customer/profile_data.html'), [
'customer' => $customer,
'passwordForm' => $passwordForm->createView(),
'nameForm' => $nameForm->createView(),
'deleteForm' => $deleteForm->createView()
]);
}
/**
* @param Request $request
* @param PaginatorInterface $paginator
* @param EntityManagerInterface $entityManager
* @param MessageCenterService $messageCenterService
* @param RouterInterface $router
* @return Response
*
* @Route("/profil/uzenetek", name="profile_messages")
*/
public function messagesAction(Request $request, PaginatorInterface $paginator, EntityManagerInterface $entityManager, MessageCenterService $messageCenterService, RouterInterface $router): Response
{
$session = $request->getSession();
if (!$session->has(self::FILTER_ID)) {
$session->set(self::FILTER_ID, ['status' => 'all', 'topic' => 'all']);
}
$filterData = $session->get(self::FILTER_ID);
if ($request->isMethod('POST')) {
$status = $request->get('status');
if ($status) {
$filterData['status'] = $status;
}
$topic = $request->get('topic');
if ($topic) {
$filterData['topic'] = $topic;
}
$session->set(self::FILTER_ID, $filterData);
return $this->redirectToRoute('profile_messages');
}
$topic = $filterData['topic'] === 'all' ? null : [$filterData['topic']];
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
// $dao = (new MessageCustomer\Listing())->getDao();
// $queryBuilder = new QueryBuilder($dao->db);
// $queryBuilder->from($dao->getTableName());
// $queryBuilder->orderBy('o16.sendTime', 'DESC');
// $queryBuilder->andWhere(sprintf('%s.customer__id = %u', $dao->getTableName(), $customer->getId()));
// $queryBuilder->innerJoin('object_17', 'object_16', 'o16', 'o16.oo_id = object_17.message__id');
// $queryBuilder->leftJoin('o16', 'object_12', 'o12', 'o12.oo_id = o16.topic__id');
// $queryBuilder->addSelect($dao->getTableName() . '.oo_id');
// $queryBuilder->addSelect('o16.image');
// $queryBuilder->addSelect('o16.title');
// $queryBuilder->addSelect('o16.text');
// $queryBuilder->addSelect('o16.sendTime');
// $queryBuilder->addSelect('object_17.read');
// $queryBuilder->addSelect('o12.topic');
//
// switch ($filterData['status']) {
// case 'readed' :
// $queryBuilder->andWhere('object_17.read = 1');
// break;
// case '1' :
// $queryBuilder->andWhere('(object_17.read IS NULL OR object_17.read = 0 OR object_17.read = -1)');
// break;
// }
//
// if (is_array($topic) && !empty($topic)) {
// $topicWhere[] = $queryBuilder->expr()->in('o12.topic', array_map(function ($item) {
// return "'" . $item . "'";
// }, $topic));
//
// if (in_array('system', $topic)) {
// $topicWhere[] = $queryBuilder->expr()->isNull('o16.topic__id');
// }
//
// $queryBuilder->andWhere(implode(' OR ', $topicWhere));
// }
$rsm = new ResultSetMapping();
$rsm->addScalarResult('oo_id', 'oo_id');
$rsm->addScalarResult('image', 'image');
$rsm->addScalarResult('title', 'title');
$rsm->addScalarResult('text', 'text');
$rsm->addScalarResult('sendTime', 'sendTime');
$rsm->addScalarResult('o_className', 'o_className');
$rsm->addScalarResult('o_id', 'o_id');
$rsm->addScalarResult('topic', 'topic');
$query = new NativeQuery($entityManager);
$query->setResultSetMapping($rsm);
$query->setSQL(sprintf(
"SELECT * FROM (%s UNION %s) a order by a.sendTime DESC",
$messageCenterService->getMessageQuery($customer, $filterData['status'] ?? null, $filterData['topic'] != 'all' ? [$filterData['topic']] : null)->getSQL(),
$messageCenterService->getMessageCustomerQuery($customer, $filterData['status'] ?? null, $filterData['topic'] != 'all' ? [$filterData['topic']] : null)->getSQL()
));
$result = $query->getResult();
$page = (int)$request->get('page', 1);
try {
$list = $paginator->paginate(
$result,
$page,
10
);
} catch (Exception $e) {
}
$cache = [];
if ($list->getItems()) {
$listing = new MessageCustomer\Listing();
$listing->setCondition(sprintf("message__id IN (%s) AND customer__id = %u", implode(', ', array_map(function ($item) {
return $item['oo_id'];
}, (array)$list->getItems())), $customer->getId()));
$cache = $listing->getData();
}
$notifications = [];
foreach ($list as $item) {
$date = '';
try {
$carbon = Carbon::createFromTimestamp($item['sendTime']);
if ($carbon instanceof Carbon) {
$date = $carbon->format('Y. m. d. H:i');
}
} catch (Exception) {
}
$notifications[] = [
'id' => $item['oo_id'],
'image' => Asset::getById($item['image']),
'title' => $item['title'],
'text' => $item['text'],
'date' => $date,
'read' => $messageCenterService->getMessageRead($item['oo_id'], $cache),
'topic' => $item['topic'],
'link' => $this->getMessageWebLink($item)
];
}
$form = $this->container->get('form.factory')->createNamed(
self::FILTER_ID, NotificationsFilterType::class,
$filterData
);
return $this->render($this->templateConfigurator->findTemplate('Customer/profile_messages.html'), [
'customer' => $customer,
'paginator' => $list,
'notifications' => $notifications,
'notiFilterForm' => $form->createView(),
]);
}
protected function getMessageWebLink($item): null|string
{
if (!empty($item['o_id']) && !empty($item['o_className'])) {
$redirect = $this->boutiqueHost . "/profil?login_redirect=";
switch ($item['o_className']) {
case 'News':
return $this->container->get('App\Website\LinkGenerator\NewsLinkGenerator')->generate(News::getById($item['o_id']));
case 'RegisteredWatch':
return $redirect . $this->container->get('App\Website\LinkGenerator\RegisteredWatchesLinkGenerator')->generate(RegisteredWatch::getById($item['o_id']));
case 'WatchRepair':
return $redirect . $this->container->get('App\Website\LinkGenerator\WatchRepairsLinkGenerator')->generate(WatchRepair::getById($item['o_id']));
}
}
return null;
}
/**
* @param Request $request
* @param MessageCenterService $messageCenterService
* @return Response
*
* @Route("/fetch-notification", name="fetch_notification", methods={"POST"})
*/
public function fetchNotificationAction(Request $request, MessageCenterService $messageCenterService): Response
{
$message = Message::getById($request->request->get('id'));
$html = $this->render($this->templateConfigurator->findTemplate('Customer/_notificationRowOpened.html'), [
'notification' => $message,
'date' => $message->getSendTime()?->format('Y. m. d. H:i') ?? '',
])->getContent();
$customer = $this->getUser()->getCustomer();
$message = Message::getById($request->get('id'));
if (!$message instanceof Message) {
return new JsonResponse(null, 400);
}
$listing = new MessageCustomer\Listing();
$listing->setCondition(sprintf("message__id = %u AND customer__id = %u", $request->get('id'), $customer->getId()));
// if ($action == 'read') {
if ($listing->count() === 0) {
try {
$messageCenterService->markMessageRead($customer, $message);
} catch (Exception $e) {
return new JsonResponse($e->getMessage(), 400);
}
}
// }
// else if ($action == 'unread') {
// if ($listing->count() > 0) {
// foreach ($listing as $item) {
// try {
// $item->delete();
// } catch (\Exception $e) {
// return new JsonResponse($e->getMessage(), 400);
// }
// }
// } else {
// return new JsonResponse(null, 400);
// }
// }
return new JsonResponse(['success' => true, 'html' => $html, 'link' => $this->getMessageWebLink([
'o_id' => $message->getContent()?->getId(),
'o_className' => $message->getContent()?->getClassName()
])]);
}
/**
* @param Request $request
* @param PaginatorInterface $paginator
* @return Response
* @Route("/profil/feliratkozasaim", name="profile_subscriptions")
*/
public function profileSubscriptionsAction(Request $request, PaginatorInterface $paginator): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('profil');
}
if ($request->getMethod() == 'POST') {
$subscribeNewsletter = $request->request->get('subscribe-newsletter');
if ($subscribeNewsletter == 1 && !$customer->getNewsletterActive()) {
$customer->setNewsletterActive(true);
$customer->save();
$this->addFlash('success', 'Sikeresen feliratkoztál a Seiko hírlevelére');
}
if ($subscribeNewsletter === "0" && $customer->getNewsletterActive()) {
$customer->setNewsletterActive(false);
$customer->setMagazineSubscribed(false);
$customer->setMagazineSubscriptionDate(null);
$this->addFlash('success', 'Sikeresen leiratkoztál a Seiko hírelvélről és ezzel együtt a Seiko Magazinról is.');
$customer->save();
}
$subscribeMagazine = $request->request->get('subscribe-magazine');
if ($subscribeMagazine == 1 && !$customer->getMagazineSubscribed()) {
$customer->setMagazineSubscribed(true);
$customer->setMagazineSubscriptionDate(new Carbon());
$customer->setNewsletterActive(true);
$customer->save();
$this->addFlash('success', 'Sikeresen feliratkoztál a Seiko Magazinra');
}
if ($subscribeMagazine == 0 && $customer->getMagazineSubscribed()) {
$customer->setMagazineSubscribed(false);
$customer->setMagazineSubscriptionDate(null);
$customer->save();
$this->addFlash('success', 'Sikeresen leiratkoztál a Seiko Magazinról és a hírlevélről');
}
return $this->redirectToRoute('profile_subscriptions');
}
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => $this->generateUrl('profil')
],
[
'title' => 'Feliratkozásaim',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
//GetTopic list
$topicList = $this->getTopicSubscriptionList($customer);
return $this->render($this->templateConfigurator->findTemplate('Customer/profile_subscriptions.html'), [
'customer' => $customer,
'topics' => $topicList
]);
}
/**
* @param Request $request
* @return Response
*
* @Route("/profil/feliratkozasaim/topicsubscriptions", name="topicsubscriptions", methods={"POST"})
*/
public function fetchTopicSubscriptions(Request $request): Response
{
$user = $this->getUser();
if (!$user) {
return new JsonResponse(['success' => false, 'message' => 'Unauthorized'], 401);
}
$customer = $user->getCustomer();
$req = $request->request->all();
if (isset($req['action'])) {
$action = $req['action'];
return $this->topicMarkAllProcess($this->getUser()->getCustomer(), $action);
}
return $this->topicSubscribeProcess($req, $customer);
}
/**
* @param Request $request
* @param RegisteredWatchesManager $registeredWatchesManager
* @param FileUploader $uploader
* @param MailerService $mailerService
* @param ApplicationLogger $logger
* @return Response
*
* @throws Exception
* @Route("/profil/ora-regisztracio", name="profile_watch_register")
*/
public function registerWatchAction(Request $request, RegisteredWatchesManager $registeredWatchesManager, FileUploader $uploader, MailerService $mailerService, ApplicationLogger $logger, RateLimiterFactory $anonymousApiLimiter): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$isDuplicated = false;
$regstrationSource = $this->isSite('club') ? 'app' : 'web';
$form = $this->container->get('form.factory')->createNamed('registerwatch', WatchRegisterType::class, new RegisteredWatch());
if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)) {
$form = $form->handleRequest($request);
if ($form->isValid()) {
$watch = $form->getData();
$path = '/RegisteredWatches';
$watch->setParent(Service::createFolderByPath($path));
$watch->setStatus('pending');
$watch->setCustomer($customer);
$watch->setRegisteredAt(Carbon::now());
$watch->setRegistrationSource($regstrationSource);
$warrantyFile = null;
$path = $this->getNotMappedValue($form, 'filePath');
if ($path !== null) {
$filename = basename($path);
$path = $this->container->getParameter('kernel.project_dir') . '/public' . $path;
$mimeType = mime_content_type($path);
if ($filename &&
in_array($mimeType, ['image/jpeg', 'image/jpg', 'application/pdf', 'application/x-pdf'], true) &&
file_exists($path)
) {
$warrantyFile = $uploader->upload(new UploadedFile($path, $filename, $mimeType));
}
}
try {
$registeredWatchesManager->persistWatch($watch, $warrantyFile);
$this->addFlash('success', 'Sikeres óra regisztráció!');
$mailerService->sendRegisteredWatchMail($watch);
return $this->redirectToRoute('profile_registered_watch_list');
} catch (Exception $e) {
$this->addFlash('error', 'Váratlan hiba történt! Az óra regisztráció sikertelen volt!');
$text = sprintf("%s\n%s\n\nWeb", $customer->getEmail(), $e->getMessage());
$logger->error($text, ['component' => 'watch-register']);
}
} else {
$limiter = $anonymousApiLimiter->create($request->getClientIp());
$data = $request->request->all();
try {
$data['price'] = (float)$data['price'];
} catch (Exception $exception) {
$text = sprintf("Cannot be converted to float\n%s\n%s\n\nWeb", $customer->getEmail(), $exception->getMessage());
$logger->error($text, ['component' => 'watch-register']);
$data['price'] = 0.0;
}
$data['placeOfPurchase'] = $data['placeOfPurchase']['shopNameSelect'] ?: ($data['placeOfPurchase']['shopNameText'] ?: 'NA');
$isDuplicated = $registeredWatchesManager->isDuplicatedError($data, $form->getErrors(true), $customer, (bool)$this->getNotMappedValue($form, 'filePath'), $limiter, $regstrationSource);
}
}
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => 'Óra regisztráció', 'path' => null,]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/watches_register.html'), [
'customer' => $customer,
'form' => $form->createView(),
'isDuplicated' => $isDuplicated
]);
}
/**
* @param Request $request
* @return Response
*
* @Route("/profil/ora-regisztracio/image/{sku}", name="profile_watch_register_image", methods={"GET"})
*/
public function fetchRegisteredWatchImage(Request $request, string $sku): Response
{
$user = $this->getUser();
if (!$user) {
return new JsonResponse(['success' => false, 'message' => 'Unauthorized'], 401);
}
$productImage = $this->getProductImageBySku($sku);
if ($productImage instanceof \Pimcore\Model\Asset\Image) {
return new JsonResponse($productImage->getFullPath());
}
return new JsonResponse("", 404);
}
private function getNotMappedValue(FormInterface $form, string $key): mixed
{
if ($form->has($key) && $form->get($key)->getData()) {
return $form->get($key)->getData();
}
return null;
}
/**
* @param Request $request
* @param PaginatorInterface $paginator
* @return Response
* @Route("/profil/regisztralt-orak", name="profile_registered_watch_list")
*/
public function registeredWatchAction(Request $request, PaginatorInterface $paginator, ApplicationLogger $logger): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$session = $request->getSession();
$page = (int)$this->getParameterFromRequest($request, 'page', 1);
$view = $this->getParameterFromRequest($request, 'view', $customer->getSettings(RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_VIEW, RegWatch::DEFAULT_LISTING_VIEW));
if (!in_array($view, RegWatch::VALID_LISTING_VIEWS, true)) {
$view = RegWatch::DEFAULT_LISTING_VIEW;
}
$savedSort = $customer->getSettings(RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_SORT, RegWatch::DEFAULT_LISTING_SORT);
$sortParsed = HelperFunctions::parseSorting($this->getParameterFromRequest($request, 'sort', $savedSort),
RegWatch::VALID_LISTING_SORT_VALUES,
RegWatch::DEFAULT_LISTING_SORT_KEY,
RegWatch::DEFAULT_LISTING_SORT_DIRECTION
);
$sort = $sortParsed['sort'];
if ($savedSort !== $sort) {
$page = 1;
}
try {
$customer->setSettings([
RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_VIEW => $view,
RegWatch::CUSTOMER_SETTINGS__REGISTERED_WATCH_SORT => $sort
]);
} catch (Exception $e) {
$logger->info($e->getMessage(), ['component' => 'customer-settings']);
}
$session->set(RegWatch::SESSION_REGISTERED_WATCH_PAGE, $page);
$listing = RegisteredWatch::getByCustomer($customer);
$listing->setCondition("(`status` != 'deleted')");
$listing->setOrder($sortParsed['direction']);
$listing->setOrderKey($sortParsed['name']);
$list = $paginator->paginate($listing, $page, 20);
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => 'Regisztrált órák', 'path' => null,]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/registered_watches_list.html'), [
'customer' => $customer,
'list' => $list->getItems(),
'paginator' => $list,
'minDate' => Carbon::parse('2000-01-01'),
'statusValues' => DataObject\Service::getOptionsForSelectField('Pimcore\Model\DataObject\RegisteredWatch', "status"),
'clubsite' => $this->isSite('club'),
'validSortElements' => RegWatch::VALID_LISTING_SORT_VALUES,
'sortDirection' => $sortParsed['direction'],
'view' => $view,
'sort' => $sort,
'validViews' => RegWatch::VALID_LISTING_VIEWS
]);
}
/**
* @param Request $request
* @param PaginatorInterface $paginator
* @param RegisteredWatchesManager $registeredWatchesManager
* @param WatchRepairManager $watchRepairManager
* @return Response
*
* @Route("/profil/regisztralt-orak/{slug}~w{id}", name="profile_registered_watch")
*/
public function registeredWatchDetailsAction(
Request $request,
PaginatorInterface $paginator,
RegisteredWatchesManager $registeredWatchesManager,
FileUploader $uploader,
WatchRepairManager $watchRepairManager,
MailerService $mailerService,
RateLimiterFactory $anonymousApiLimiter,
RegisteredWatchesLinkGenerator $registeredWatchesLinkGenerator,
ApplicationLogger $logger
): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$watch = RegisteredWatch::getById($request->get('id'));
if (!$watch instanceof RegisteredWatch || $watch->getStatus() === 'deleted') {
return $this->redirectToRoute('profile_registered_watch_list');
}
if ($customer->getId() !== $watch->getCustomer()->getId()) {
return $this->redirectToRoute('profile_registered_watch_list');
}
$product = $this->getProductFromWatch($watch);
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => 'Regisztrált órák', 'path' => $this->generateUrl('profile_registered_watch_list')],
['title' => sprintf("%s - %s", $watch->getSerial(), $watch->getMechanismNumber()), 'path' => null]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
//NewUserreport
$newUserReportForm = $this->container->get('form.factory')->createNamed(
'newuserreportform', UserReportType::class
);
$newUserReportForm->handleRequest($request);
$state = [
'servicedropdown' => [
'opened' => false
],
'newuserreportform' => [
'opened' => false
]
];
if ($newUserReportForm->isSubmitted()) {
if ($newUserReportForm->isValid()) {
$data = $newUserReportForm->getData();
$userReport = $this->createWatchRepairUserReportSheet($request, $uploader, $data, $watch->getId());
$this->updateWatchRepairEvents($userReport, $data);
if ($userReport instanceof WatchRepairUserReport) {
$this->addFlash('success', 'A bejegyzés sikeresen hozzáadva!');
return $this->redirect($registeredWatchesLinkGenerator->generate($watch));
}
}
if (!$newUserReportForm->isValid()) {
$this->addFlash('error', 'A bejegyzés hozzáadás sikertelen!');
$state['servicedropdown']['opened'] = true;
$state['newuserreportform']['opened'] = true;
}
}
$combinedList = $this->getWatchRepairSheetList($watch->getId());
$sheet_list = $paginator->paginate($combinedList, (int)$request->get('page', 1), 10);
foreach ($sheet_list as $repairSheet) {
$repairSheet->dateModificatedObject = HelperFunctions::getModificationDate($repairSheet);
}
$deleteForm = $this->container->get('form.factory')->createNamed('watchesinterest', DeleteRegisteredWatchType::class);
$deleteForm->handleRequest($request);
if ($deleteForm->isSubmitted() && $deleteForm->isValid() && $deleteForm->get('delete')?->isClicked()) {
try {
$registeredWatchesManager->deleteRegistration($watch);
$this->addFlash('success', 'Óra regisztráció sikeresen törölve.');
} catch (Exception) {
$this->addFlash('error', 'Hiba történt!');
}
return $this->redirectToRoute('profile_registered_watch_list');
}
$maxWarrantyFiles = $this->maxWarrantyFiles;
//Delete warranty
if ($request->getMethod() === "POST" && $warrantyIndex = $request->request->get('delWarranty')) {
if (is_numeric($warrantyIndex)) {
$deleteresult = $this->deleteWarranty($watch, $warrantyIndex);
}
$deleteFlashTyle = $deleteresult["errors"] === false ? 'success' : 'error';
$this->addFlash($deleteFlashTyle, $deleteresult["message"]);
header('Location: ' . $registeredWatchesLinkGenerator->generate($watch));
exit;
}
//Warranty upload
if ($request->getMethod() === "POST" && $warrantyFileUploaded = $request->files->get('warrantyFile')) {
$saveresult = $this->saveWarranty(
$watch,
$warrantyFileUploaded,
$uploader,
['warrantyMimeValidator' => $this->allowedWarrantyMimeTypes, 'maxWarrantyValidator' => $maxWarrantyFiles],
$logger
);
if ($saveresult["errors"] !== false) {
$this->addFlash('error', $saveresult["message"]);
}
if ($saveresult["errors"] === false) {
$limiter = $anonymousApiLimiter->create($request->getClientIp());
if ($limiter) {
if ($limiter->consume(1)->isAccepted()) {
$mailerService->sendWarrantyMail($watch, $customer);
}
}
$this->addFlash('succes', 'Az új garancia dokumentumok sikeresen hozzáadva');
}
header('Location: ' . $registeredWatchesLinkGenerator->generate($watch));
exit;
}
return $this->render($this->templateConfigurator->findTemplate('Customer/registered_watches.html'), array_merge([
'clubsite' => $this->isSite('club'),
'customer' => $customer,
'watch' => $watch,
'product' => $product,
'minDate' => Carbon::parse('2000-01-01'),
'statusValues' => DataObject\Service::getOptionsForSelectField('Pimcore\Model\DataObject\RegisteredWatch', "status"),
'repair_list' => $sheet_list->getItems(),
'repairsheet_type_names' => $this->getWatchRepairConstants()['WATCH_REPAIR_SHEET_TYPE_NAMES'],
'repair_paginator' => $sheet_list,
'newWatchRepairForm' => $newUserReportForm->createView(),
'deleteForm' => $deleteForm->createView(),
'maxWarrantyFiles' => $maxWarrantyFiles,
'maxWatchRepairFiles' => $this->maxWatchRepairFiles,
'state' => $state
], $watchRepairManager->getWatchRepairEventsAssociative($watch)));
}
/**
* @param Request $request
* @return Response
* @Route("/profil/regisztralt-orak/{slug}~w{id}/garancia.pdf", name="profile_registered_watch_warrantypdf")
*/
public function registeredWatchWarrantyPDFAction(
Request $request,
$slug,
$id
): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$watch = RegisteredWatch::getById($request->get('id'));
if (!$watch instanceof RegisteredWatch || $watch->getStatus() === 'deleted') {
return $this->redirectToRoute('profile_registered_watch_list');
}
if ($customer->getId() !== $watch->getCustomer()->getId()) {
return $this->redirectToRoute('profile_registered_watch_list');
}
$stream = $this->warrantyPdfControllerAction(
$watch,
$this->container->getParameter('app.date_format'),
$this->warrantyPDFPath
);
return new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($stream) {
fpassthru($stream);
}, 200, [
'Content-Type' => 'application/pdf'
]);
}
/**
* @param Request $request
* @return Response
* @Route("/profil/szerviz/worksheet/{slug}~w{id}", name="profile_watch_repair_detail")
*/
public function watchRepairDetailsAction(
Request $request,
FileUploader $uploader,
PaginatorInterface $paginator,
int $id
): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$watchRepair = WatchRepair::getById($request->get('id'));
if (!$watchRepair instanceof WatchRepair) {
return $this->redirectToRoute('profile_watch_repair_list');
}
$watch = $watchRepair->getRegisteredWatch();
$watchId = $watch->getId();
$product = $this->getProductFromWatch($watch);
//Newremark form
$newRemarkForm = $this->container->get('form.factory')->createNamed(
'newremarkform', RemarkType::class, null, [
'remark-id' => false
]
);
$newRemarkForm->handleRequest($request);
//Update remark form
$updateRemarkForm = $this->container->get('form.factory')->createNamed(
'updateremark', RemarkType::class
);
$updateRemarkForm->handleRequest($request);
//Remark modifications, additions, deletions
$remarkActionsValid = $this->remarkDesktopActions(
$request,
$uploader,
$newRemarkForm,
$updateRemarkForm,
$watchId,
$id
);
if ($remarkActionsValid) {
return $this->redirect($request->getUri());
}
$remarks = WatchRepairRemark::getByWatchRepairParent($watchRepair);
if (!$remarks instanceof \Pimcore\Model\DataObject\WatchRepairRemark\Listing) {
return $this->redirectToRoute('profile_registered_watch_list');
}
$remarks->setOrder('desc')->setOrderKey('oo_id');
$remark_list = $paginator->paginate(
$remarks,
(int)$request->get('page', 1),
$this->getWatchRepairConstants()['REMARK_PER_PAGE']
);
$remarks = [];
foreach ($remark_list as $remark) {
$remarks[] = $this->remarkObjectWithAdditions($remark, $customer);
}
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => 'Regisztrált órák', 'path' => $this->generateUrl('profile_registered_watch_list')],
[
'title' => sprintf("%s - %s", $watch->getSerial(), $watch->getMechanismNumber()),
'path' => $this->generateUrl('profile_registered_watch', [
'id' => $watch->getId(),
'slug' => sprintf("%s - %s", $watch->getSerial(), $watch->getMechanismNumber()),
]),
],
['title' => sprintf("Munkalap %s", $watchRepair->getWorksheetNumber()), 'path' => null]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/watch_repair_detail.html'), [
'clubsite' => $this->isSite('club'),
'customer' => $customer,
'minDate' => Carbon::parse('2000-01-01'),
'watchRepair' => $watchRepair,
'newRemarkForm' => $newRemarkForm->createView(),
'updateRemarkForm' => $updateRemarkForm->createView(),
'product' => $product,
'remarks' => $remarks,
'remark_paginator' => $remark_list,
'maxWatchRepairFiles' => $this->maxWatchRepairFiles
]);
}
/**
* @param Request $request
* @return Response
* @Route("/profil/szerviz/userreport/w{id}", name="profile_watch_repair_user_report_detail")
*/
public function watchRepairUserReportDetailsAction(
Request $request,
FileUploader $uploader,
PaginatorInterface $paginator,
int $id,
WatchRepairManager $watchRepairManager
): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$watchRepairUserReport = WatchRepairUserReport::getById($request->get('id'));
if (!$watchRepairUserReport instanceof WatchRepairUserReport) {
return $this->redirectToRoute('profile_registered_watch_list');
}
$watch = $watchRepairUserReport->getRegisteredWatch();
$watchCustomer = $watch->getCustomer();
if ($watchCustomer->getId() !== $customer->getId()) {
return $this->redirectToRoute('profile_registered_watch_list');
}
$product = $this->getProductFromWatch($watch);
$watchId = $watch->getId();
//WatchRepairUserreport updafte form
$userReportUpdateForm = $this->container->get('form.factory')->createNamed(
'userreportupdateform', UserReportType::class, null, [
'image-inputs' => false, 'remark-text' => false
]
);
$userReportUpdateForm->handleRequest($request);
//UserReport actions
$userReportActionValid = $this->userReportDesktopActions(
$userReportUpdateForm,
$watchId,
$id
);
//Newremark form
$newRemarkForm = $this->container->get('form.factory')->createNamed(
'newremarkform', RemarkType::class, null, [
'remark-id' => false
]
);
$newRemarkForm->handleRequest($request);
//Update remark form
$updateRemarkForm = $this->container->get('form.factory')->createNamed(
'updateremark', RemarkType::class
);
$updateRemarkForm->handleRequest($request);
//Remark modifications, additions, deletions
$remarkActionValid = $this->remarkDesktopActions(
$request,
$uploader,
$newRemarkForm,
$updateRemarkForm,
$watchId,
$id
);
if ($remarkActionValid || $userReportActionValid) {
return $this->redirect($request->getUri());
}
$remarks = WatchRepairRemark::getByWatchRepairParent($watchRepairUserReport);
if (!$remarks instanceof \Pimcore\Model\DataObject\WatchRepairRemark\Listing) {
return $this->redirectToRoute('profile_registered_watch_list');
}
$remarks->setOrder('desc')->setOrderKey('oo_id');
$remark_list = $paginator->paginate(
$remarks,
(int)$request->get('page', 1),
$this->getWatchRepairConstants()['REMARK_PER_PAGE']
);
$remarks = [];
foreach ($remark_list as $remark) {
$remarks[] = $this->remarkObjectWithAdditions($remark, $customer);
}
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => 'Regisztrált órák', 'path' => $this->generateUrl('profile_registered_watch_list')],
[
'title' => sprintf("%s - %s", $watch->getSerial(), $watch->getMechanismNumber()),
'path' => $this->generateUrl('profile_registered_watch', [
'id' => $watch->getId(),
'slug' => sprintf("%s - %s", $watch->getSerial(), $watch->getMechanismNumber()),
]),
],
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/watch_repair_user_report_detail.html'),
array_merge([
'clubsite' => $this->isSite('club'),
'customer' => $customer,
'minDate' => Carbon::parse('2000-01-01'),
'watchRepairUserReport' => $watchRepairUserReport,
'userReportUpdateForm' => $userReportUpdateForm->createView(),
'newRemarkForm' => $newRemarkForm->createView(),
'updateRemarkForm' => $updateRemarkForm->createView(),
'product' => $product,
'remarks' => $remarks,
'remark_paginator' => $remark_list,
'maxWatchRepairFiles' => $this->maxWatchRepairFiles
]
, $watchRepairManager->getWatchRepairEventsAssociative($watch)));
}
/**
* @param Request $request
* @param WishListService $wishListService
* @return Response
* @Route("/profil/megtekintett-orak", name="recent_watches")
*/
public function recentWatchesProfileAction(Request $request, WishListService $wishListService = null): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirect('/profil');
}
$lastViewedWatches = DataObject\LastViewedWatches::getByCustomer($customer)->current();
$watches = $lastViewedWatches instanceof DataObject\LastViewedWatches ? $lastViewedWatches->getWatches() : [];
$watchesId = array_map(function ($watch) {//get ids
return $watch->getElementId();
}, $watches);
$res = [];
$wishlist = [];
if (!empty($watchesId)) {
$entries = new DataObject\CoreShopProduct\Listing();
$entries->onCreateQueryBuilder(function (\Doctrine\DBAL\Query\QueryBuilder $queryBuilder) use ($watchesId) {
$queryBuilder->addOrderBy("FIELD(oo_id, " . implode(",", $watchesId) . ")");
});
$entries->setCondition("oo_id IN (?)", [$watchesId]);
foreach ($entries as $entry) {
$res[] = $entry;
$wishlist[$entry->getId()] = $wishListService->hasItem($entry);
}
}
if ($this->isSite('club')) {
return $this->render($this->templateConfigurator->findTemplate('Customer/recentWatches.html'), [
'customer' => $customer,
'watches' => $res,
'clubsite' => $this->isSite('club'),
'boutiquesite' => $this->boutiqueHost,
]);
}
return $this->render($this->templateConfigurator->findTemplate('Customer/recentWatches.html'), [
'customer' => $customer,
'watches' => $res,
'isWishListed' => $wishlist,
]);
}
/**
* @Route("/regisztracio-megerosites", name="confirm-register")
*/
public function confirmRegisterAction(
Request $request,
MaileonService $maileonService,
MessageCenterService $messageCenterService
): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if ($customer instanceof CustomerInterface) {
return $this->redirect('/');
}
$token = $this->getParameterFromRequest($request, 'token');
if (!$token) {
return $this->redirect('/');
}
$customer = $this->container->get('coreshop.repository.customer')->findOneBy([
'registrationToken' => $token,
'pimcore_unpublished' => true
]);
if (!$customer instanceof CoreShopCustomer) {
return $this->redirect('/');
}
if ($customer instanceof CustomerInterface) {
if ($customer->isPublished()) {
return $this->redirect('/');
}
$customer->setRegistrationToken(null);
$customer->setPublished(true);
VersionHelper::useVersioning(function () use ($customer) {
$customer->save();
}, false);
$triggers = $this->container->getParameter('maileon_triggerNames');
$messageCenterService->createMessageFromTemplateIfExists($customer, 'register_success');
$maileonService->sendTriggeredMail($triggers[$customer->getMaileonTrigger('register_success')], $customer->getEmail());
$this->addFlash('success', 'Sikeresen megerősítetted a regisztrációd');
} else {
$this->addFlash('success', 'A regisztráció megerősítése sikertelen volt');
}
return $this->redirectToRoute('profil');
}
/**
* @param Request $request
* @return Response
* @Route("/profil/newsletter", name="coreshop_customer_newsletter")
*/
public function newsletterAction(Request $request): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('profil');
}
if ($request->getMethod() == 'POST') {
$subscribe = $request->request->get('subscribe');
if ($subscribe == 1 && !$customer->getNewsletterActive()) {
$customer->setNewsletterActive(true);
$customer->save();
$this->addFlash('success', 'Sikeresen feliratkoztál a Seiko hírlevelére');
}
if ($subscribe == 0 && $customer->getNewsletterActive()) {
$customer->setNewsletterActive(false);
$customer->setMagazineSubscribed(false);
$customer->setMagazineSubscriptionDate(null);
$this->addFlash('success', 'Sikeresen leiratkoztál a Seiko hírelvélről és ezzel együtt a Seiko Magazinról is.');
$customer->save();
}
// $this->eventDispatcher->dispatch(new GenericEvent($customer, []), 'customer.newsletter.subscription');
return $this->redirectToRoute('coreshop_customer_newsletter');
}
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => $this->generateUrl('profil')
],
[
'title' => 'Hírlevél',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/newsletter.html'), [
'customer' => $customer,
]);
}
/**
* @param Request $request
* @return Response
* @Route("/profil/magazin", name="coreshop_customer_magazine")
*/
public function magazineAction(Request $request): Response
{
return $this->redirectToRoute('profile_subscriptions');
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('profil');
}
if ($request->getMethod() == 'POST') {
$subscribe = $request->request->get('subscribe');
if ($subscribe == 1 && !$customer->getMagazineSubscribed()) {
$customer->setMagazineSubscribed(true);
$customer->setMagazineSubscriptionDate(new Carbon());
$customer->setNewsletterActive(true);
$customer->save();
$this->addFlash('success', 'Sikeresen feliratkoztál a Seiko Magazinra');
}
if ($subscribe == 0 && $customer->getMagazineSubscribed()) {
$customer->setMagazineSubscribed(false);
$customer->setMagazineSubscriptionDate(null);
$customer->save();
$this->addFlash('success', 'Sikeresen leiratkoztál a Seiko Magazinról és a hírlevélről');
}
// $this->eventDispatcher->dispatch(new GenericEvent($customer, []), 'customer.magazine.subscription');
return $this->redirectToRoute('coreshop_customer_magazine');
}
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => $this->generateUrl('profil')
],
[
'title' => 'Magazin',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/magazine.html'), [
'customer' => $customer,
]);
}
public function addressesAction(): Response
{
$this->denySite('prospex');
if (Site::isSiteRequest()) {
throw $this->createNotFoundException('Page not found!');
}
$this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ADDRESSES');
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => $this->generateUrl('profil')
],
[
'title' => 'Személyes adatok',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->redirectToRoute('profile_profiledata');
}
public function addressAction(Request $request): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('coreshop_index');
}
$address = $this->container->get('coreshop.repository.address')->find($this->getParameterFromRequest($request, 'address'));
if ($address instanceof AddressInterface) {
$this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ADDRESS_EDIT');
} else {
$this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ADDRESS_ADD');
}
$translator = $this->container->get('translator');
$addressAssignmentManager = $this->container->get(AddressAssignmentManagerInterface::class);
$addressIdentifierRepository = $this->container->get('coreshop.repository.address_identifier');
$customerInvoiceAddress = $customer->getInvoiceAddress();
$customerShippingAddress = $customer->getShippingAddress();
$customerMagazineAddress = $customer->getMagazineAddress();
$customerHasInvoiceAddress = $customer->hasAddressIdf()['invoice'];
$customerHasShippingAddress = $customer->hasAddressIdf()['shipping'];
$customerHasMagazineAddress = $customer->hasAddressIdf()['magazine'];
//Calculate the default addressIdf
$defaultIdentifier = $this->getDefaultAddressIdentifier($customerInvoiceAddress, $customerShippingAddress, $customerMagazineAddress);
$addressIdentifierParam = $request->query->get('address_identifier', $defaultIdentifier);
if (!in_array($addressIdentifierParam, ['invoice', 'shipping', 'magazine'], true)) {
$addressIdentifierParam = $defaultIdentifier;
}
$customerHasAddressWithThisAddrIdfParam = (
($addressIdentifierParam === 'invoice' && $customerHasInvoiceAddress) ||
($addressIdentifierParam === 'shipping' && $customerHasShippingAddress) ||
($addressIdentifierParam === 'magazine' && $customerHasMagazineAddress)
);
$eventType = 'update';
if (!$address instanceof AddressInterface) {
$eventType = 'add';
if ($customerHasAddressWithThisAddrIdfParam) {
$this->addFlash('error', 'Csak egy ' . strtolower($translator->trans(sprintf('coreshop.ui.%s_address', $addressIdentifierParam))) . ' lehet!');
}
/** @var AddressInterface $address */
$address = $this->container->get('coreshop.factory.address')->createNew();
$addressIdentifier = $addressIdentifierRepository->findByName($addressIdentifierParam);
if ($addressIdentifier instanceof AddressIdentifierInterface) {
$address->setAddressIdentifier($addressIdentifier);
}
}
$isNewAddress = $eventType === 'add';
if ($eventType === 'update' && $addressAssignmentManager->checkAddressAffiliationPermissionForCustomer($customer, $address) === false) {
return $this->redirectToRoute('profile_profiledata');
}
$addressFormOptions = [
'available_affiliations' => $addressAssignmentManager->getAddressAffiliationTypesForCustomer($customer),
'selected_affiliation' => $addressAssignmentManager->detectAddressAffiliationForCustomer($customer, $address),
'show_address_identifier_choice' => $isNewAddress,
'eventType' => $eventType,
'customerHasInvoiceAddress' => $customerHasInvoiceAddress,
'customerHasShippingAddress' => $customerHasShippingAddress,
'customerHasMagazineAddress' => $customerHasMagazineAddress
];
if ($isNewAddress) {
$this->initializeNewAddress($customer, $address);
}
$form = $this->container->get('form.factory')->createNamed('coreshop', AddressType::class, $address, $addressFormOptions);
if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)) {
$handledForm = $form->handleRequest($request);
$addressAffiliation = $form->has('addressAffiliation') ? $form->get('addressAffiliation')->getData() : null;
if ($handledForm->isSubmitted() && $handledForm->isValid()) {
/** @var DataObject\CoreShopAddress $address */
$address = $handledForm->getData();
$address->setPublished(true);
$address->setKey(uniqid(more_entropy: true));
$isInvoiceAddress = $address->getAddressIdentifier()?->getName() === 'invoice';
$isShippingAddress = $address->getAddressIdentifier()?->getName() === 'shipping';
$isMagazineAddress = $address->getAddressIdentifier()?->getName() === 'magazine';
if ($isMagazineAddress) {
if ($customerMagazineAddress && $isNewAddress) {
$this->addFlash('error', 'Csak egy Magazin címe lehet!');
return $this->redirectToRoute('profile_profiledata');
}
$address->setIsCompanyBill(null);
$address->setCompanyName(null);
$address->setCompanyTaxNumber(null);
} else if (!$address->getIsCompanyBill()) {
$address->setCompanyName(null);
$address->setCompanyTaxNumber(null);
}
$phoneNumber = HelperFunctions::formatPhoneNumber($address->getPhoneNumber());
if ($phoneNumber !== $address->getPhoneNumber()) {
$address->setPhoneNumber($phoneNumber);
}
if (!$customer->getPhoneNumber()) {
$customer->setPhoneNumber($address->getPhoneNumber());
$customer->save();
}
$address = $addressAssignmentManager->allocateAddressByAffiliation($customer, $address, $addressAffiliation);
$this->fireEvent($request, $address, sprintf('%s.%s.%s_post', 'coreshop', 'address', $eventType));
//Invoice copy
if (!$isInvoiceAddress && $isNewAddress && $handledForm->get('isInvoiceAddress')->getData()) {
$this->copyAddressToIdentifier(
$request,
$customerHasInvoiceAddress,
$addressIdentifierRepository->findByName('invoice'),
$customerInvoiceAddress,
$address,
$addressAssignmentManager,
$customer,
$addressAffiliation,
$eventType,
$translator->trans('coreshop.ui.customer.address_successfully_added_copied_to_invoice')
);
}
//Shipping copy
if (!$isShippingAddress && $isNewAddress && $handledForm->get('isShippingAddress')->getData()) {
$this->copyAddressToIdentifier(
$request,
$customerHasShippingAddress,
$addressIdentifierRepository->findByName('shipping'),
$customerShippingAddress,
$address,
$addressAssignmentManager,
$customer,
$addressAffiliation,
$eventType,
$translator->trans('coreshop.ui.customer.address_successfully_added_copied_to_shipping')
);
}
//Magazine copy
if (!$isMagazineAddress && $isNewAddress && $handledForm->get('isMagazineAddress')->getData()) {
$this->copyAddressToIdentifier(
$request,
$customerHasMagazineAddress,
$addressIdentifierRepository->findByName('magazine'),
$customerMagazineAddress,
$address,
$addressAssignmentManager,
$customer,
$addressAffiliation,
$eventType,
$translator->trans('coreshop.ui.customer.address_successfully_added_copied_to_magazine')
);
}
$this->addFlash('success', $translator->trans(sprintf('coreshop.ui.customer.address_successfully_%s', $isNewAddress ? 'added' : 'updated')));
return $this->redirect($this->getParameterFromRequest($request, '_redirect', $this->generateUrl('profile_profiledata')));
}
}
$title = sprintf($isNewAddress ? "Új %s felvétele" : '%s módosítása',
strtolower($translator->trans(sprintf('coreshop.ui.%s_address', $address->getAddressIdentifier()?->getName())))
);
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => 'Személyes adatok', 'path' => $this->generateUrl('coreshop_customer_addresses')],
['title' => $title, 'path' => null]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/address.html'), [
'address' => $address,
'customer' => $customer,
'title' => $title,
'warnInvoiceAddress' => $address->getAddressIdentifier()?->getName() !== 'invoice' && $customerHasInvoiceAddress,
'warnShippingAddress' => $address->getAddressIdentifier()?->getName() !== 'shipping' && $customerHasShippingAddress,
'warnMagazineAddress' => $address->getAddressIdentifier()?->getName() !== 'magazine' && $customerHasMagazineAddress,
'form' => $form->createView(),
'customerHasAllAddresses' => $isNewAddress && $customerHasInvoiceAddress && $customerHasShippingAddress && $customerHasMagazineAddress,
'customerHasAddressWithThisAddrIdfParam' => $customerHasAddressWithThisAddrIdfParam
]);
}
private function getDefaultAddressIdentifier($invoice, $shipping, $magazine): ?string
{
$allTypes = ['invoice', 'shipping', 'magazine'];
$available = array_filter([
'invoice' => $invoice,
'shipping' => $shipping,
'magazine' => $magazine,
]);
$existing = array_keys($available);
$missing = array_values(array_diff($allTypes, $existing));
return count($existing) < 3 && count($missing) > 0 ? $missing[0] : null;
}
private function initializeNewAddress(CustomerInterface $customer, AddressInterface $address): void
{
$address->setFirstname($customer->getFirstname());
$address->setLastname($customer->getLastname());
if (($phoneNumber = $customer->getPhoneNumber())) {
$address->setPhoneNumber(HelperFunctions::formatPhoneNumber($phoneNumber));
}
}
private function copyAddressToIdentifier(
Request $request,
bool $customerHasAddress,
?AddressIdentifierInterface $identifierType,
?CoreshopAddress $customerAddress,
CoreshopAddress $address,
$addressAssignmentManager,
CoreShopCustomer $customer,
$addressAffiliation,
string $eventType,
string $flashMessage
): void
{
if (!$customerHasAddress) {
$customerAddress = new CoreShopAddress();
$customerAddress->setPublished(true);
$customerAddress->setKey(uniqid(more_entropy: true));
$customerAddress->setAddressIdentifier($identifierType);
}
$customerAddress->setFirstname($address->getFirstname());
$customerAddress->setLastname($address->getLastname());
$customerAddress->setCountry($address->getCountry());
$customerAddress->setPhoneNumber($address->getPhoneNumber());
$customerAddress->setPostcode($address->getPostcode());
$customerAddress->setCity($address->getCity());
$customerAddress->setStreet($address->getStreet());
$customerAddress->setNumber($address->getNumber());
$customerAddress->setComment($address->getComment());
$customerAddress = $addressAssignmentManager->allocateAddressByAffiliation($customer, $customerAddress, $addressAffiliation);
$this->fireEvent($request, $customerAddress, sprintf('%s.%s.%s_post', 'coreshop', 'address', $eventType));
$this->addFlash('success', $flashMessage);
}
public function orderListAction(Request $request, PaginatorInterface $paginator): Response
{
$this->denySite('prospex');
$this->denySite('club');
$this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDERS');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('coreshop_index');
}
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => $this->generateUrl('profil')
],
[
'title' => 'Rendeléseim',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
$orders = CoreShopOrder::getByCustomer($customer);
$orders->setCondition("orderState NOT IN ('new', 'initialized')");
$orders->setOrderKey('o_id');
$orders->setOrder('desc');
$page = (int)$request->get('page', 1);
$list = $paginator->paginate(
$orders,
$page,
20
);
$shipmentState = [];
foreach ($list->getItems() as $order) {
$shipmentState[$order->getId()] = $this->getShipmentStateByOrder($order);
}
return $this->render($this->templateConfigurator->findTemplate('Customer/orders.html'), [
'customer' => $customer,
'list' => $list->getItems(),
'shipmentState' => $shipmentState,
'paginator' => $list,
]);
}
public function orderDetailsAction(Request $request): Response
{
$this->denySite('prospex');
$this->denySite('club');
$this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDER_DETAIL');
$orderId = $this->getParameterFromRequest($request, 'order');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('coreshop_index');
}
$order = $this->get('coreshop.repository.order')->find($orderId);
if (!$order instanceof CoreShopOrder) {
return $this->redirectToRoute('coreshop_customer_orders');
}
if (!$order->getCustomer() instanceof CustomerInterface || $order->getCustomer()->getId() !== $customer->getId()) {
return $this->redirectToRoute('coreshop_customer_orders');
}
$shipments = $this->orderShipmentRepository->getDocuments($order);
$shipmentButtons = array_filter(
array_map(function ($shipment) {
$carrierIdentifier = $shipment->getCarrier()->getIdentifier();
$trackingCode = $shipment->getTrackingCode();
if (!is_string($carrierIdentifier) || !is_string($trackingCode)
) {
return null;
}
if (!in_array($carrierIdentifier, $this->carrier['tracking']['allowedcarriers']) || $shipment->getState() !== 'shipped') {
return null;
}
$trackingUrlPrefix = $this->carrier['tracking']['urls'][$carrierIdentifier] ?? null;
return $trackingUrlPrefix && $trackingCode ? ['trackingCode' => $trackingCode, 'url' => $trackingUrlPrefix] : null;
}, $shipments)
);
$shipment = ['buttons' => $shipmentButtons, 'state' => $this->getShipmentStateByOrder($order)];
$bc = [
[
'title' => 'Főoldal',
'path' => '/'
],
[
'title' => 'Profil',
'path' => $this->generateUrl('profil')
],
[
'title' => 'Rendeléseim',
'path' => $this->generateUrl('coreshop_customer_orders')
],
[
'title' => 'Rendelés megtekintése',
'path' => null
]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
$noteList = new Note\Listing();
$noteList->addConditionParam('type = ?', Notes::NOTE_ORDER_COMMENT);
$noteList->addConditionParam('cid = ?', $order->getId());
$noteList->setOrderKey('date');
$noteList->setOrder('desc');
$comments = [];
foreach ($noteList as $note) {
if (!empty($note->getData()['submitAsEmail']['data'])) {
$comments[] = $note->getDescription();
}
}
CoreShopProduct::setHideUnpublished(false);
return $this->render($this->templateConfigurator->findTemplate('Customer/order_detail.html'), [
'customer' => $customer,
'order' => $order,
'shipment' => $shipment,
'comments' => array_filter($comments),
'orderHistory' => true,
]);
}
/**
* @Route("/profil/cim_torles/{name}~a{addressId}", name="customer_delete_address", requirements={"name"=".+"})
*/
public function deleteAddress(Request $request, int $addressId): Response
{
$this->denySite('prospex');
$customer = $this->getCustomer();
if (!$customer instanceof CustomerInterface) {
return $this->redirectToRoute('coreshop_index');
}
$address = CoreShopAddress::getById($addressId);
if (!$address instanceof CoreShopAddress) {
throw $this->createNotFoundException('Page not found!');
}
$found = false;
foreach ($customer->getAddresses() as $a) {
if ($address->getId() === $a->getId()) {
$found = true;
break;
}
}
if (!$found) {
throw $this->createNotFoundException('Page not found!');
}
$defaultRedirect = 'profile_profiledata';
$redirect = $request->get('_redirect', $defaultRedirect);
if (!in_array($redirect, ['profile_profiledata', 'profile_subscriptions'], true)) {
$redirect = $defaultRedirect;
}
$identifierTrans = $this->container->get('translator')->trans(sprintf('coreshop.ui.%s_address', $address->getAddressIdentifier()?->getName()));
$prevTitle = 'Személyes adatok';
$title = "$identifierTrans törlése";
if ($redirect === 'profile_subscriptions') {
$prevTitle = 'Feliratkozásaim';
}
$form = $this->container->get('form.factory')->createNamed('deleteAccount', DeleteAccountType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid() && $form->get('submit')?->isClicked()) {
try {
if ($address->getAddressIdentifier()?->getName() === 'magazine') {
$customer->setMagazineSubscribed(false);
$customer->setMagazineIsActuallyNeed(false);
$customer->setMagazineSubscriptionDate(null);
$customer->save();
}
$address->delete();
$this->addFlash('success', sprintf("%se sikeresen törlésre került!", $identifierTrans));
} catch (Exception) {
$this->addFlash('error', 'Hiba történt!');
}
return $this->redirectToRoute($redirect);
}
$bc = [
['title' => 'Főoldal', 'path' => '/'],
['title' => 'Profil', 'path' => $this->generateUrl('profil')],
['title' => $prevTitle, 'path' => $this->generateUrl($redirect)],
['title' => $title, 'path' => null]
];
$pl = $this->placeholder;
$pl('breadcrumbNews')->set($bc);
return $this->render($this->templateConfigurator->findTemplate('Customer/delete_address.html'), [
'customer' => $customer,
'address' => $address,
'form' => $form->createView(),
'_redirect' => $redirect
]);
}
}