src/FlexApp/Service/WelcomeInfoDataGenerator.php line 169

Open in your IDE?
  1. <?php
  2. /** @noinspection PhpDocSignatureInspection */
  3. namespace FlexApp\Service;
  4. use Doctrine\ORM\NonUniqueResultException;
  5. use Exception;
  6. use FlexApp\Entity\ChatB;
  7. use FlexApp\Entity\ConsultantEntity;
  8. use FlexApp\Events\Style43\GeneralErrorEvent;
  9. use FlexApp\Repository\ConsultantRepository;
  10. use FlexApp\Repository\CountryAndLangSpecificDataRepository;
  11. use Psr\Cache\InvalidArgumentException;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use Twig\Environment;
  15. use Twig\Error\LoaderError;
  16. use Twig\Error\RuntimeError;
  17. use Twig\Error\SyntaxError;
  18. use WebBundle\Entity\User;
  19. use WebBundle\Helper\PortalHelper;
  20. use WebBundle\Helper\UserHelper;
  21. use WebBundle\Repository\ListCountryRepository;
  22. use WebBundle\Repository\UserRepository;
  23. class WelcomeInfoDataGenerator
  24. {
  25.     const DEFAULT_CONS_PORTAL_LOGIN 'tkonyukhova';
  26.     const DEFAULT_COUNTRY 'gb';
  27.     /**
  28.      * @var Environment
  29.      */
  30.     private $twig;
  31.     /**
  32.      * @var PortalHelper
  33.      */
  34.     private $portalHelper;
  35.     /**
  36.      * @var ParametersProvider
  37.      */
  38.     private $parametersProvider;
  39.     public $welcomeCons;
  40.     /**
  41.      * @var ListCountryRepository
  42.      */
  43.     private $listCountryRepository;
  44.     /**
  45.      * @var EventDispatcherInterface
  46.      */
  47.     private $eventDispatcher;
  48.     /**
  49.      * @var ConsSchedule
  50.      */
  51.     private $consSchedule;
  52.     /**
  53.      * @var ConsultantRepository
  54.      */
  55.     private $consultantRepository;
  56.     /**
  57.      * @var ConsDefiner
  58.      */
  59.     private $consDefiner;
  60.     /**
  61.      * @var UserRepository
  62.      */
  63.     private $userRepository;
  64.     /**
  65.      * @var TranslatorInterface
  66.      */
  67.     private $translator;
  68.     /**
  69.      * @var AliasByConsLoginProvider
  70.      */
  71.     private AliasByConsLoginProvider $aliasByConsLoginProvider;
  72.     /** @required */
  73.     public TimeFormatTransformer $timeFormatTransformer;
  74.     /** @required */
  75.     public CountryAndLangSpecificDataRepository $countryAndLangSpecificDataRepository;
  76.     public function __construct(
  77.         Environment $twig,
  78.         PortalHelper $portalHelper,
  79.         ParametersProvider $parametersProvider,
  80.         ListCountryRepository $listCountryRepository,
  81.         EventDispatcherInterface $eventDispatcher,
  82.         ConsSchedule $consSchedule,
  83.         ConsultantRepository $consultantRepository,
  84.         ConsDefiner $consDefiner,
  85.         UserRepository $userRepository,
  86.         TranslatorInterface $translator,
  87.         AliasByConsLoginProvider $aliasByConsLoginProvider
  88.     ) {
  89.         $this->twig $twig;
  90.         $this->portalHelper $portalHelper;
  91.         $this->parametersProvider $parametersProvider;
  92.         $this->listCountryRepository $listCountryRepository;
  93.         $this->consSchedule $consSchedule;
  94.         $this->consultantRepository $consultantRepository;
  95.         $this->consDefiner $consDefiner;
  96.         $this->userRepository $userRepository;
  97.         $this->eventDispatcher $eventDispatcher;
  98.         $this->translator $translator;
  99.         $this->aliasByConsLoginProvider $aliasByConsLoginProvider;
  100.     }
  101.     /**
  102.      * @return array|string
  103.      *
  104.      * @throws InvalidArgumentException
  105.      * @throws LoaderError
  106.      * @throws NonUniqueResultException
  107.      * @throws RuntimeError
  108.      * @throws SyntaxError
  109.      */
  110.     public function generate(ChatB $chatbool $asHtml true)
  111.     {
  112.         /** @var User $user */
  113.         $user $this->userRepository->findOneBy(['token' => $chat->getToken()]);
  114.         $cons $this->consDefiner->getCons(
  115.             $chat->getCurrentLocale(),
  116.             $chat->getCurrentCountry(),
  117.             $user,
  118.             UserHelper::getInstance()->getToken()
  119.         );
  120.         $this->addExtraInfoToSingleLevelConsArray($cons$chat);
  121.         $this->addConsWorkHoursAndWorkDaysAndUTCOffset($cons$chat);
  122.         $translationLang $this->getTranslationLangForWelcomeMessage($chat);
  123.         if ($asHtml) {
  124.             return $this->twig->render('ChatB/welcome_info.html.twig', [
  125.                 'cons'            => $cons,
  126.                 'wiLocale'        => $chat->getCurrentLocale(),
  127.                 'translationLang' => $translationLang,
  128.             ]);
  129.         }
  130.         $cons['timezone'] = $this->translator->trans($cons['timezone'], [], null$chat->getCurrentLocale());
  131.         $consultantWord $this->translator->trans($cons['consWordKey'], [], null$translationLang);
  132.         $discussSchedule $this->translator->trans('discuss.schedule', [], 'messages',
  133.                 $chat->getCurrentLocale()) . ' ' $cons['work_hours'] . " ({$cons['timezone']}). {$cons['work_days']}.";
  134.         $discussionHelloOnlineLong $this->translator->trans('discussion.hello.online.long', [
  135.             '%consWord%'        => $consultantWord,
  136.             '%name%'            => $cons['name'],
  137.             '%contact_details%' => $cons['contact_details'],
  138.             '%work_hours%'      => $cons['work_hours'] . ' ' $cons['timezone'],
  139.         ], 'messages'$translationLang);
  140.         return [
  141.             'cons'  => $cons,
  142.             'trans' => [
  143.                 'discussSchedule'           => $discussSchedule,
  144.                 'discussionHelloOnlineLong' => $discussionHelloOnlineLong,
  145.             ],
  146.         ];
  147.     }
  148.     /**
  149.      * @throws NonUniqueResultException
  150.      * @throws Exception
  151.      */
  152.     public function addExtraInfoToSingleLevelConsArray(array &$consChatB $chat)
  153.     {
  154.         $countryString $chat->getCurrentCountry();
  155.         if ('en' === $countryString) {
  156.             $countryString $chat->getCurrentCountryByIp();
  157.             if ('en' === $countryString) {
  158.                 $countryString self::DEFAULT_COUNTRY;
  159.             }
  160.         }
  161.         $countryEntity $this->listCountryRepository->getCountry($countryString);
  162.         if (null === $countryEntity) {
  163.             //TODO нужно добавлять автоматом просьбу на Игоря в этом случае, чтоб он добавил страну
  164.             $this->eventDispatcher->dispatch(new GeneralErrorEvent(new Exception("Не удалось найти в БД сущность по стране '{$countryString}' в таблице consultant. Добавьте соответствующую запись в таблицу list_country.")));
  165.             $countryEntity $this->listCountryRepository->getCountry(self::DEFAULT_COUNTRY);
  166.             if (!$countryEntity) {//Произойдет, только если из таблицы удалят страну self::DEFAULT_COUNTRY
  167.                 throw new Exception(sprintf('Не найдена дефолтная страна с кодом %s в таблице list_country. Необходимо добавить эту страну в таблицу list_country в ручном режиме.',
  168.                     self::DEFAULT_COUNTRY));
  169.             }
  170.         }
  171.         /** @var ConsultantEntity $consultant */
  172.         //1. Ищем запись по логину
  173.         $consultant $this->consultantRepository->findOneBy(['portalLogin' => $cons['login']]);
  174.         if (!$consultant) {//Если не нашли
  175.             //2. Уведомляем, что нет записи с таким логином и добавляем в ручную
  176.             $this->eventDispatcher->dispatch(new GeneralErrorEvent(new Exception("Не удалось найти консультанта в БД в таблице consultant для login: '{$cons['login']}'. Необходимо добавить в ручную.")));
  177.             //и ищем по дефолтному логину
  178.             $consultant $this->consultantRepository->findOneBy(['portalLogin' => self::DEFAULT_CONS_PORTAL_LOGIN]);
  179.             if (!$consultant) {//Если не нашли и по дефолтному
  180.                 //3. Выкидываем Exception
  181.                 throw new Exception('Не нашли консультанта в базе данных даже по дефолтному логину');
  182.             }
  183.         }
  184.         $dataEntity $this->countryAndLangSpecificDataRepository->getDataEntityByCountryAndLang($countryEntity$chat->getCurrentLocale());
  185.         $cons['name'] = $this->aliasByConsLoginProvider->getAlias($cons['login'] ?? '');
  186.         $cons['contact_details'] = $consultant->getEmail() . ', ' $dataEntity->getPhone();
  187.         $cons['contact_email'] = $consultant->getEmail();
  188.         $cons['contact_phone'] = $dataEntity->getPhone();
  189.         $cons['consWordKey'] = $consultant->getSex() ? 'consWordMale' 'consWordFemale';
  190.         $cons['ava'] = "https://img.tile.expert/img_lb/_consults/prew/{$consultant->getAvaFileName()}";
  191.     }
  192.     /**
  193.      * @throws InvalidArgumentException
  194.      */
  195.     public function addConsWorkHoursAndWorkDaysAndUTCOffset(array &$consChatB $chat)
  196.     {
  197.         $schedule $this->consSchedule->getScheduleByConsLoginAndCountry($cons['login'], $chat->getCurrentCountry(), $chat->getCurrentCountryByIp(),
  198.             $chat->getCurrentLocale());
  199.         $cons['work_hours'] = $this->timeFormatTransformer->transform($schedule['work_hours_string'], $chat->getCurrentCountry(),
  200.             $chat->getCurrentLocale());
  201.         $cons['work_days'] = $schedule['work_days_string'];
  202.         $cons['timezone'] = $schedule['timezone_string'];
  203.     }
  204.     private function getTranslationLangForWelcomeMessage(ChatB $chat)
  205.     {
  206.         if (in_array($chat->getCurrentLocale(), [
  207.             'fi',
  208.             'sv',
  209.             'no'
  210.             /*, 'pt'*/
  211.         ])) { //Для португальского языка просили оставить приветствие на португальском: https://te.remote.team/#/discus/B768BCC7-9553-9FDA-5032-10EE0ED53479/
  212.             // https://te.remote.team/#/discus/D306518B-5ECB-65DF-B691-3EF49ADFA0D9
  213.             return 'en';
  214.         }
  215.         return $chat->getCurrentLocale();
  216.     }
  217. }