<?php
namespace WebBundle\Controller;
use AdmBundle\Helper\Adm;
use Exception;
use FlexApp\Helper\GeoHelper;
use FlexApp\Helper\MetaHelper;
use FlexApp\Repository\CountryAndLangSpecificDataRepository;
use FlexApp\Service\CalendarService;
use FlexApp\Service\CommentablePageDataProvider;
use FlexApp\Service\ConsDataForContactsPageProvider;
use FlexApp\Service\TimeFormatTransformer;
use FlexApp\Service\TimezoneManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use WebBundle\Entity\Factory;
use WebBundle\Entity\IdeasShare;
use WebBundle\Entity\ListCountry;
use WebBundle\Helper\App;
use WebBundle\Helper\ArrHelper;
use WebBundle\Helper\CalendarHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\TwilioHelper;
use WebBundle\Helper\UserHelper;
use WebBundle\Repository\FactoryRepository;
use WebBundle\Repository\IdeasShareRepository;
use WebBundle\Repository\ListCountryRepository;
use WebBundle\Repository\StaticPageRepository;
class PageController extends ExtendedController
{
/** @required */
public ListCountryRepository $listCountryRepository;
/** @required */
public StaticPageRepository $staticPageRepository;
/** @required */
public IdeasShareRepository $ideasShareRepository;
/** @required */
public CountryAndLangSpecificDataRepository $countryAndLangSpecificDataRepository;
/** @required */
public FactoryRepository $factoryRepository;
/**
* @param string $url
* @param null $type
*
* @return Response
*
* @throws Exception
*/
public function indexAction(string $url, $type = null)
{
$lc = App::getCurLocale();
$cn = App::getCurCountry();
// логика под варианты с группами стран. Редиректим от прямых ссылок
// https://te2.remote.team/discus/5E802239-CA11-A3D8-6A54-C25E8F7C58A5
if (preg_match('#(.*)-(rf|eu|eact|usca|new)$#isUu', $url, $m)) {
return new RedirectResponse(App::generateUrl('app_page', ['url' => $m[1]]), 301);
}
$rfCns = ['ru'];
// проставляем префикс для тематических страниц
$urlAlt = null;
if (in_array($cn, $rfCns) and in_array($url, ['payment', 'conditions', 'policy-personal-data-process'])) {
$urlAlt = $url . '-rf';
}
// переадрессовал на переделанную страницу оплаты и доставки
if ($url == 'payment') {
$urlAlt = 'payment-new';
}
if (null !== $type and 'career' == $type) {
$lc = 'ru';
$cn = 'ru';
$indexHtml = '@Web/Vacancy/Page/index.html.twig';
} else {
$indexHtml = '@Web/Page/index.html.twig';
}
$page = null;
// ищем сначала тематическую страницу
if ($urlAlt) {
$page = $this->staticPageRepository->getPage($urlAlt, $lc, $cn);
}
// отдаем стандартную страницу для если тематическая не готова
if (!$page) {
$page = $this->staticPageRepository->getPage($url, $lc, $cn);
}
if (!$page) {
throw new NotFoundHttpException('Not found.');
}
$page['body'] = LocaleHelper::fixLink($page['body']);
$metaManager = MetaHelper::getManager($page);
$this->addIdAndUnidOfStaticPageToReact($page);
return $this->render($indexHtml, [
'page' => $page,
'_country' => $cn,
'linkEdit' => Adm::linkEdit('adm.static.page.edit', $page['id']),
'meta' => [
'title' => $metaManager->getTitle($lc),
'description' => $metaManager->getDescription($lc),
'keywords' => $metaManager->getKeywords($lc),
],
]);
}
/**
* @deprecated
*/
public function saveClickIdeaShareToSocialAction(Request $request): Response
{
$response = [
'link' => $request->request->get('link', null),
'url' => $request->request->get('url', null),
'soc' => $request->request->get('social', null),
'ideaId' => $request->request->get('ideaId', null),
'token' => UserHelper::getInstance()->getToken(),
];
$share = new IdeasShare($response);
$this->ideasShareRepository->save($share);
$clickIdeaShareToSocialCount = $this->ideasShareRepository->getClickIdeaShareToSocialCount($response);
return new Response($clickIdeaShareToSocialCount ?: 'nodata');
}
public function contactsAction(): Response
{
$localeNames = LocaleHelper::$localesName;
// available and sorted locales
$locales = LocaleHelper::getListCode();
$locale = App::getCurLocale();
$locale = in_array($locale, $locales) ? $locale : 'en';
$locales = array_diff($locales, [$locale => $locale]);
$data = compact('localeNames', 'locale', 'locales');
$data['showChat'] = 1;
$countries = $this->listCountryRepository->getListForLocalize();
$data['country'] = $this->translate('country.other');
$data['countryEntity'] = App::getCurCountryEntity();
$countryEntity = $data['countryEntity'];
if (!$countryEntity) {
throw new Exception(sprintf('Не найдена страна "%s" в базе', App::getCountryCode()));
}
$userCountry = $countryEntity->getCode();
/** @var ListCountry $country */
foreach ($countries as $country) {
if ($country['code'] == $userCountry) {
$data['country'] = $this->translate($country['alias']);
break;
}
}
//для выпадающего списка смены страны
$countryList = App::getCountryList();
//Сортируем страны по имени в текущей локали
uasort($countryList, function ($a, $b) {
return $a['name'] <=> $b['name'];
});
$data['countryList'] = $countryList;
$code = App::getCurCountry();
$availableLanguages = ArrHelper::get($data['countryList'], "{$code}.localesArr");
if (false === array_search('en', $availableLanguages ?? [])) {
$availableLanguages[] = 'en';
}
$data['availableLanguages'] = $data['countryList'][App::getCurCountry()]['localesArr'] ?? ['en'];
// определяем потдержку браузером WebRTC
$data['xRPC'] = TwilioHelper::detectWebRTC();
// =========================
$data['calendar'] = CalendarHelper::findClosestHolidaysInCalendar();
$data['capital'] = GeoHelper::country()->getCurCapital() ?: '';
$data['lang'] = App::getCurLocale();
$data['countryCode'] = App::getCurCountry();
$dataEntity = $this
->countryAndLangSpecificDataRepository
->getDataEntityByCountryAndLang($countryEntity, App::getCurLocale());
$data['phone'] = $dataEntity->getPhone();
$data['email'] = $dataEntity->getEmail();
$data['startDay'] = $dataEntity->getStartDay();
$data['endDay'] = $dataEntity->getEndDay();
$data['startHour'] = $dataEntity->getStartHour() . ':00';
$data['endHour'] = $dataEntity->getEndHour() . ':00';
$data['twilioId'] = $dataEntity->getTwilioId();
$data['time'] = $data['startHour'] . ' - ' . $data['endHour'];
$monday = 1;
$saturday = 6;
/** @var TimezoneManager $timezoneManager */
$timezoneManager = App::getContainer()->get(TimezoneManager::class);
$data['workDaysTime'] = $timezoneManager->getTimeWithDiff($dataEntity->getTime($monday, 'start')) . ' - ' . $timezoneManager->getTimeWithDiff($dataEntity->getTime($monday, 'end'));
$data['weekendDaysTime'] = $timezoneManager->getTimeWithDiff($dataEntity->getTime($saturday, 'start')) . ' - ' . $timezoneManager->getTimeWithDiff($dataEntity->getTime($saturday, 'end'));
$data['weekendIsOnline'] = isset($dataEntity->getWorkDays()[$saturday]);
$data['isUnionWorkDaysAndWeekend'] = ($data['workDaysTime'] === $data['weekendDaysTime']) && $data['weekendIsOnline'];
if ($data['isUnionWorkDaysAndWeekend']) {
$data['unionTime'] = $timezoneManager->getTimeWithDiff($dataEntity->getTime($monday, 'start')) . ' - ' . $timezoneManager->getTimeWithDiff($dataEntity->getTime($saturday, 'end'));
}
/** @var TimeFormatTransformer $timeFormatTransformer */
$timeFormatTransformer = $this->container->get(TimeFormatTransformer::class);
$data['time'] = $timeFormatTransformer->transform($data['time'], App::getCurCountry(), App::getCurLocale());
/** @var ConsDataForContactsPageProvider $consDataProvider */
$consDataProvider = $this->container->get(ConsDataForContactsPageProvider::class);
$data['avapath'] = $consDataProvider->getAvaUrl();
$data['consAlias'] = $consDataProvider->getAlias();
$metaManager = MetaHelper::getManager($data);
$data['meta'] = [
'title' => $metaManager->getTitle(),
'description' => $metaManager->getDescription(),
'keywords' => $metaManager->getKeywords(),
];
$calendarService = $this->get(CalendarService::class);
$holidays = [
'holidaysString' => $calendarService->getHolidaysString(CalendarHelper::HOLIDAY_TYPE),
'halfHolidaysString' => $calendarService->getHolidaysString(CalendarHelper::HALF_HOLIDAY_TYPE),
];
return $this->render('contacts/contacts.html.twig', array_merge($data, $holidays));
}
/**
* Вывод всех фабрик со статусами для портала или 1с
*
* @return JsonResponse
*/
public function getAllFactoryAction(): JsonResponse
{
$factories = $this->factoryRepository->findAll();
$arr = [];
/** @var Factory $factor */
foreach ($factories as $factor) {
$arr[] = [
'id' => $factor->getId(),
'name' => $factor->getName(),
'status' => $factor->getStatus(),
];
}
$response = new JsonResponse($arr);
$response->setCache([
'max_age' => 600,
's_maxage' => 600,
'public' => true,
]);
return $response;
}
/**
* @param $page
* @throws Exception
*/
private function addIdAndUnidOfStaticPageToReact($page): void
{
$commentablePageDataProvider = App::getContainer()->get(CommentablePageDataProvider::class);
$commentablePageDataProvider->setStaticPageId($page['id']);
$commentablePageDataProvider->setStaticPageUnid($page['unid']);
}
}