src/FlexApp/Service/WelcomeInfoDataGenerator.php line 173

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.     public const DEFAULT_CONS_PORTAL_LOGIN 'tkonyukhova';
  26.     public 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(
  133.             'discuss.schedule',
  134.             [],
  135.             'messages',
  136.             $chat->getCurrentLocale()
  137.         ) . ' ' $cons['work_hours'] . " ({$cons['timezone']}). {$cons['work_days']}.";
  138.         $discussionHelloOnlineLong $this->translator->trans('discussion.hello.online.long', [
  139.             '%consWord%'        => $consultantWord,
  140.             '%name%'            => $cons['name'],
  141.             '%contact_details%' => $cons['contact_details'],
  142.             '%work_hours%'      => $cons['work_hours'] . ' ' $cons['timezone'],
  143.         ], 'messages'$translationLang);
  144.         return [
  145.             'cons'  => $cons,
  146.             'trans' => [
  147.                 'discussSchedule'           => $discussSchedule,
  148.                 'discussionHelloOnlineLong' => $discussionHelloOnlineLong,
  149.             ],
  150.         ];
  151.     }
  152.     /**
  153.      * @throws NonUniqueResultException
  154.      * @throws Exception
  155.      */
  156.     public function addExtraInfoToSingleLevelConsArray(array &$consChatB $chat)
  157.     {
  158.         $countryString $chat->getCurrentCountry();
  159.         if ('en' === $countryString) {
  160.             $countryString $chat->getCurrentCountryByIp();
  161.             if ('en' === $countryString) {
  162.                 $countryString self::DEFAULT_COUNTRY;
  163.             }
  164.         }
  165.         $countryEntity $this->listCountryRepository->getCountry($countryString);
  166.         if (null === $countryEntity) {
  167.             //TODO нужно добавлять автоматом просьбу на Игоря в этом случае, чтоб он добавил страну
  168.             $this->eventDispatcher->dispatch(new GeneralErrorEvent(new Exception("Не удалось найти в БД сущность по стране '{$countryString}' в таблице consultant. Добавьте соответствующую запись в таблицу list_country.")));
  169.             $countryEntity $this->listCountryRepository->getCountry(self::DEFAULT_COUNTRY);
  170.             if (!$countryEntity) {//Произойдет, только если из таблицы удалят страну self::DEFAULT_COUNTRY
  171.                 throw new Exception(sprintf(
  172.                     'Не найдена дефолтная страна с кодом %s в таблице list_country. Необходимо добавить эту страну в таблицу list_country в ручном режиме.',
  173.                     self::DEFAULT_COUNTRY
  174.                 ));
  175.             }
  176.         }
  177.         /** @var ConsultantEntity $consultant */
  178.         //1. Ищем запись по логину
  179.         $consultant $this->consultantRepository->findOneBy(['portalLogin' => $cons['login']]);
  180.         if (!$consultant) {//Если не нашли
  181.             //2. Уведомляем, что нет записи с таким логином и добавляем в ручную
  182.             $this->eventDispatcher->dispatch(new GeneralErrorEvent(new Exception("Не удалось найти консультанта в БД в таблице consultant для login: '{$cons['login']}'. Необходимо добавить в ручную.")));
  183.             //и ищем по дефолтному логину
  184.             $consultant $this->consultantRepository->findOneBy(['portalLogin' => self::DEFAULT_CONS_PORTAL_LOGIN]);
  185.             if (!$consultant) {//Если не нашли и по дефолтному
  186.                 //3. Выкидываем Exception
  187.                 throw new Exception('Не нашли консультанта в базе данных даже по дефолтному логину');
  188.             }
  189.         }
  190.         $dataEntity $this->countryAndLangSpecificDataRepository->getDataEntityByCountryAndLang($countryEntity$chat->getCurrentLocale());
  191.         $cons['name'] = $this->aliasByConsLoginProvider->getAlias($cons['login'] ?? '');
  192.         $cons['contact_details'] = $consultant->getEmail() . ', ' $dataEntity->getPhone();
  193.         $cons['contact_email'] = $consultant->getEmail();
  194.         $cons['contact_phone'] = $dataEntity->getPhone();
  195.         $cons['consWordKey'] = $consultant->getSex() ? 'consWordMale' 'consWordFemale';
  196.         $cons['ava'] = "https://img.tile.expert/img_lb/_consults/prew/{$consultant->getAvaFileName()}";
  197.     }
  198.     /**
  199.      * @throws InvalidArgumentException
  200.      */
  201.     public function addConsWorkHoursAndWorkDaysAndUTCOffset(array &$consChatB $chat)
  202.     {
  203.         $schedule $this->consSchedule->getScheduleByConsLoginAndCountry(
  204.             $cons['login'],
  205.             $chat->getCurrentCountry(),
  206.             $chat->getCurrentCountryByIp(),
  207.             $chat->getCurrentLocale()
  208.         );
  209.         $cons['work_hours'] = $this->timeFormatTransformer->transform(
  210.             $schedule['work_hours_string'],
  211.             $chat->getCurrentCountry(),
  212.             $chat->getCurrentLocale()
  213.         );
  214.         $cons['work_days'] = $schedule['work_days_string'];
  215.         $cons['timezone'] = $schedule['timezone_string'];
  216.     }
  217.     private function getTranslationLangForWelcomeMessage(ChatB $chat)
  218.     {
  219.         if (
  220.             in_array($chat->getCurrentLocale(), [
  221.             'fi',
  222.             'sv',
  223.             'no'
  224.             /*, 'pt'*/
  225.             ])
  226.         ) { //Для португальского языка просили оставить приветствие на португальском: https://te.remote.team/#/discus/B768BCC7-9553-9FDA-5032-10EE0ED53479/
  227.             // https://te.remote.team/#/discus/D306518B-5ECB-65DF-B691-3EF49ADFA0D9
  228.             return 'en';
  229.         }
  230.         return $chat->getCurrentLocale();
  231.     }
  232. }