<?php
/**
* Elements DeMI
*
* This source file is available under the elements DeMI license version 1
*
* @copyright Copyright (c) elements.at New Media Solutions GmbH (https://www.elements.at/)
* @license elements DeMI Lizenz Version 1 (https://www.elements.at/de/demi-lizenz)
*/
namespace Elements\Bundle\DemiFrontendBundle\Controller;
use Elements\Bundle\CDMUserManagerBundle\Templating\Helper\CDMPasswordHelper;
use Elements\Demi\Accommodation\Search\Parameter;
use Elements\Demi\Frontend\Service\Configuration;
use Elements\Bundle\DemiFrontendBundle\Service\Customer;
use Elements\Bundle\DemiFrontendBundle\Service\Newsletter;
use Elements\Bundle\DemiFrontendBundle\Service\SavingRequest;
use Elements\Demi\AbstractSavingRequest;
use Elements\Demi\CustomerFactory;
use Elements\Demi\DataObject\AbstractCustomer;
use Elements\Demi\Deskline\SavingRequest\GroupRequest;
use Elements\Demi\Deskline\SavingRequest\RequestPool;
use Elements\Demi\Deskline\SavingRequest\ServiceProviderRequest;
use Elements\Demi\Model\Region;
use Elements\Demi\Model\Town;
use Elements\Demi\SavingRequest\RequestPoolSettings;
use Elements\Demi\SavingRequest\ServiceProviderRequestSettings;
use ErrorException;
use Exception;
use Pimcore;
use Pimcore\File;
use Pimcore\Model\DataObject\Folder;
use Pimcore\Model\Document;
use Pimcore\Model\Document\Email;
use Pimcore\Tool\DeviceDetector;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
class SavingRequestController extends AbstractDemiController
{
public function __construct(Configuration $configuration, protected SavingRequest $savingRequest, protected CustomerFactory $customerFactory,
protected Customer $customerHelper, protected RequestPool $requestPool, protected GroupRequest $groupRequest, protected ServiceProviderRequest $serviceProviderRequest, protected Newsletter $newsletterHandler, protected ?CDMPasswordHelper $CDMPasswordHelper)
{
$this->setConfiguration($configuration);
}
public function savingRequestAction(Request $request, array $viewParams = null, UserInterface $user = null, bool $useFilter = true): RedirectResponse|bool|Response
{
if (empty($this->configuration->getCurrentDocument())) {
$this->configuration->setDocument($this->document ?? $request->attributes->get('contentDocument'));
}
$listDoc = $this->configuration->getAccoParentDocument();
$enabledFilters = $this->configuration->getFilterBlockItems();
if ($useFilter) {
$documentFilterSnippet = $this->document->getEditable('requestFilterSnippet');
if ($documentFilterSnippet !== null &&!$documentFilterSnippet->isEmpty()) {
$elementArray = $this->savingRequest->getSavingRequestElementsFromFilter($documentFilterSnippet, $request, $enabledFilters);
} else {
$elementArray = $listDoc ? $this->savingRequest->getSavingRequestElementsFromFilter($listDoc->getEditable('filterSnippet'), $request, $enabledFilters) :
$this->savingRequest->getSavingRequestElements($request);
}
$viewParams['stars'] = $elementArray['stars'];
$viewParams['countries'] = $elementArray['countries'];
$viewParams['salutations'] = $elementArray['salutations'];
$viewParams['roomFacilities'] = $elementArray['roomFacilities'];
$viewParams['facilities'] = $elementArray['facilities'];
$viewParams['categories'] = $elementArray['categories'];
$viewParams['marketingGroups'] = $elementArray['marketingGroups'];
$viewParams['holidayThemes'] = $elementArray['holidayThemes'];
$viewParams['mealTypes'] = $elementArray['mealTypes'];
$viewParams['towns'] = $elementArray['towns'];
$viewParams['regions'] = $elementArray['regions'];
$viewParams['user'] = $user;
}
if ($request->get('submitRequest')) {
$pp = $request->get('savingRequestTypeService') === 'groupRequest' ? trim($this->configuration->getPrivacyPolicyGroup()) :
trim($this->configuration->getPrivacyPolicyPool());
//privacy policy is no longer a checkbox
/*
$checkPp = !empty($pp);
if ($checkPp && !$request->get('pp')) {
$viewParams['error'] = 'demi.saving-request.fail.privacy-policy';
}
*/
if ($user && $request->get('mergeToAccount')) {
$customer = $this->customerHelper->updateCustomerFromRequest($request, $user)['customer'];
} else {
if ($request->get('createAccount') === 'on' && !$this->customerHelper->validateCustomerAccount($request)) {
$viewParams['error'] = 'demi.saving-request.fail-reload';
}
$tmpCustomer = $request->get('createAccount') === 'on' ? $this->customerFactory->createCustomer() : $this->customerHelper->getInactiveCustomerByMail($request->get('email'));
$customer = $this->customerHelper->createCustomerFromRequest($request, $tmpCustomer);
}
/**
* @var mixed $ignoreCountry
* legacy issue - can be null | true | false
*/
$ignoreCountry = null;
$service = $request->query->get('savingRequestTypeService');
$customOriginator = $this->document->getProperty('demi_customOriginator');
if($customOriginator){
$customer->setProperty('demi_customOriginator', 'text', $customOriginator);
}
$savingRequest = $this->$service;
$savingRequest->setCustomOriginator($customOriginator);
if ($request->get('contactType') || $request->get('maxTickets')) {
$savingRequest->setRequestPoolSettings(new RequestPoolSettings(
$request->get('contactType'), $request->get('maxTickets')
));
}
if ($request->get('enquire')) {
$savingRequest->setServiceProviderRequestSettings(new ServiceProviderRequestSettings(
$request->get('accoIds'),
$request->get('productId')
));
$ignoreCountry = true;
}
$this->customerHelper->transferToExternalSystem($customer, $ignoreCountry);
$savingRequest->setComment($request->get('comment'));
$savingRequest->setCustomer($customer);
if ($this->document->getProperty('demi_linkkey')) {
$savingRequest->setLinkKey($this->document->getProperty('demi_linkkey'));
}
$searchParams = $this->savingRequest->createSearchParams($request);
if (empty($searchParams->getTowns()) && empty($searchParams->getRegions()) && empty($searchParams->getDistricts())) {
$regionIds = [];
$townIds = [];
if (empty($elementArray['regions']) && empty($elementArray['towns'])) {
//default set all regions if no configured towns or regions in filter, one of the parameters needs to be set!
$demiRegions = Region::getBySystemIdentifier('Deskline');
foreach ($demiRegions as $region) {
$regionIds[] = $region->getId();
}
if (empty($regionIds)) {
$demiTowns = Town::getBySystemIdentifier('Deskline');
foreach ($demiTowns as $demiTown) {
$townIds[] = $demiTown->getId();
}
}
} else {
if(!empty($elementArray['regions'])){
//set all regions available in filter if none selected by user
foreach ($elementArray['regions'] as $region) {
$regionIds[] = $region->getId();
}
}
if(!empty($elementArray['towns'])){
//set all towns available in filter if none selected by user
foreach ($elementArray['towns'] as $town) {
$townIds[] = $town->getId();
}
}
}
if (!empty($townIds)) {
$searchParams->setTowns($townIds);
} else {
$searchParams->setRegions($regionIds);
}
}
$savingRequest->setSearchParams($searchParams);
try {
$savingRequest->save();
$this->handleCustomerCreation($request, $customer, $request->get('createAccount') === 'on');
if ($this->newsletterHandler && $request->get('newsletter') === 'on') {
try {
//handle newsletter subscripton
$modifiedCustomer = $this->newsletterHandler->addRecipient($customer->getEmail(), $customer->getFirstname(), $customer->getLastname(), ['request' => $request], $user, $customer);
$modifiedCustomer->save();
} catch (Exception $exception) {
if (Pimcore::inDebugMode()) {
//silently ignore newsletter subscription errors in live mode, show them in debug
throw $exception;
}
}
}
if (!($savingRequest instanceof ServiceProviderRequest)) {
$this->addResponseHeader('X-Robots-Tag', 'noindex,nofollow');
return $this->redirect($request->query->get('thxPage'));
}
} catch (Exception $exception) {
if (!($savingRequest instanceof ServiceProviderRequest)) {
$viewParams['error'] = 'demi.saving-request.fail';
} else {
throw $exception;
}
}
if ($savingRequest instanceof ServiceProviderRequest) {
return true;
}
}
$deviceDetector = DeviceDetector::getInstance();
return $this->renderTemplate('@ElementsDemiFrontend/SavingRequest/saving-request.'.($deviceDetector->isPhone() ? 'mobile' : 'desktop').'.html.twig', $viewParams);
}
/**
* @param Request $request
* @param AbstractCustomer $customer
* @param $createAccount
*
* @throws Exception
*/
protected function handleCustomerCreation(Request $request, AbstractCustomer $customer, bool $createAccount): void
{
if (empty($customer->getKey())) {
$customer->setParent(Folder::getByPath($this->customerFactory->getCustomerParent()));
$customer->setPublished(true);
$customer->setKey(Pimcore\Model\Element\Service::getValidKey(uniqid($customer->getEmail() . '_'), 'object'));
}
$customer->save();
if ($createAccount) {
try {
$emailDoc = $this->configuration->getCreatePasswordDocument();
if ($this->CDMPasswordHelper && method_exists($this->CDMPasswordHelper, 'initPassword') && $customer instanceof \Pimcore\Model\DataObject\Customer && $emailDoc && $emailDoc instanceof Email) {
$this->CDMPasswordHelper->initPassword($customer, $emailDoc);
}
} catch (Exception $exception) { /* this should actually not happen if a valid $emailDoc is set */
}
}
}
public function poolRequestAction(Request $request, UserInterface $user = null): RedirectResponse|bool|Response
{
if (empty($this->configuration->getCurrentDocument())) {
$this->configuration->setDocument($this->document ?? $request->attributes->get('contentDocument'));
}
if (!$this->editmode && !$this->configuration->getPoolRequestThxPage()) {
throw new ErrorException('Pool Request thx page is not configured in demiConfig');
}
if ($this->configuration->getPoolRequestThxPage() instanceof Document) {
if ($request->request->get('affiliate')) {
$request->query->set('thxPage', $this->configuration->getPoolRequestThxPage()->getFullPath() . '?affiliate=1');
} else {
$request->query->set('thxPage', $this->configuration->getPoolRequestThxPage()->getFullPath());
}
}
$request->query->set('savingRequestTypeService', 'requestPool');
$viewParams["possibleNights"] = $this->configuration->getPoolRequestPossibleNights();
$viewParams["possibleAdults"] = $this->configuration->getPoolRequestPossibleAdults();
$viewParams["possibleChildren"] = $this->configuration->getPoolRequestPossibleChildren();
return $this->savingRequestAction($request, $viewParams, $user);
}
/**
* @param Request $request
* @param UserInterface|null $user
*
* @return Response
*
* @throws ErrorException
*/
public function groupRequestAction(Request $request, UserInterface $user = null)
{
if (empty($this->configuration->getCurrentDocument())) {
$this->configuration->setDocument($this->document ?? $request->attributes->get('contentDocument'));
}
if (!$this->editmode && !$this->configuration->getGroupRequestThxPage()) {
throw new ErrorException('Group Request thx page is not configured in demiConfig');
}
$viewParams["isGroupRequest"] = true;
if ($this->configuration->getGroupRequestThxPage() instanceof Document) {
if ($request->request->get('affiliate')) {
$request->query->set('thxPage', $this->configuration->getGroupRequestThxPage()->getFullPath() . '?affiliate=1');
} else {
$request->query->set('thxPage', $this->configuration->getGroupRequestThxPage()->getFullPath());
}
}
$request->query->set('savingRequestTypeService', 'groupRequest');
$viewParams["possibleNights"] = $this->configuration->getGroupRequestPossibleNights();
$viewParams["possibleAdults"] = $this->configuration->getGroupRequestPossibleAdults();
$viewParams["possibleChildren"] = $this->configuration->getGroupRequestPossibleChildren();
return $this->savingRequestAction($request, $viewParams, $user);
}
public function serviceProviderRequestAction(Request $request, UserInterface $user = null): bool
{
$request->query->set('savingRequestTypeService', 'serviceProviderRequest');
if ($request->get('u0') === null) {
$request->query->set('u0', '1');
$request->query->set('a0', '1');
}
return $this->savingRequestAction($request, [], $user, false);
}
}