<?php
declare(strict_types=1);
namespace App\Controller;
use App\Helpers\Timezone\MskDiff;
use App\Model\Domain\Easuz\Notice\UseCase\CreateDraft\Message;
use App\Model\User\Entity\User\UserRepository;
use App\ReadModel\Admin\Settings\SettingsFetcher;
use App\ReadModel\Admin\Settings\TimeZone\TimeZoneFetcher;
use App\ReadModel\Certificate\CertificateFetcher;
use App\ReadModel\Profile\ProfileFetcher;
use App\ReadModel\User\UserJoin\UserJoinFetcher;
use App\Security\UserIdentity;
use App\Services\HandBook\ApiClient;
use App\Services\Notice\NoticeSenderService;
use DateTimeZone;
use Doctrine\DBAL\Exception;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
* @method null|UserIdentity getUser()
*/
class HomeController extends AbstractController
{
/**
* @var CertificateFetcher
*/
private $certificateFetcher;
/**
* @var SettingsFetcher
*/
private SettingsFetcher $settingsFetcher;
// Редирект в "Мои сертификаты" для этих ролей
private $roles = [
'ROLE_USER',
'ROLE_ORGANIZER',
'ROLE_PARTICIPANT'
];
public function __construct(
CertificateFetcher $certificateFetcher,
SettingsFetcher $settingsFetcher
) {
$this->certificateFetcher = $certificateFetcher;
$this->settingsFetcher = $settingsFetcher;
}
/**
* @param ProfileFetcher $profileFetcher
* @return Response
* @throws Exception
* @Route("/", name="home")
*/
public function home(ProfileFetcher $profileFetcher): Response
{
$user = $this->getUser();
if ($user === null) {
return $this->redirect('login');
} else {
if ($pId = $user->getProfileId()) {
$profile = $profileFetcher->find($pId);
if (!$profile->getStatus()->isActive()) {
return $this->redirectToRoute('profile', ['profile_id' => $pId]);
}
return $this->redirectToRoute('procedures');
}
}
if (in_array($user->getRole(), $this->roles)) {
return $this->redirectToRoute('certificates', ['user_id' => $user->getId()]);
}
return $this->render('app/home.html.twig');
}
/**
* @return Response
* @Route("/health", name="health_check")
*/
public function health(): Response
{
return new Response('OK', 200);
}
/**
* @Route("/api/auth/session", name="api.auth.session", methods={"GET"})
*/
public function authSession(
Request $request,
ProfileFetcher $profileFetcher,
TimeZoneFetcher $timeZoneFetcher,
MskDiff $mskDiffHelper,
ApiClient $apiClient,
JWTEncoderInterface $jwtEncoder,
UserJoinFetcher $userJoinFetcher
) {
$timeZonesDict = [
'Europe/London',
'Europe/Berlin',
'Europe/Kaliningrad',
'Europe/Moscow',
'Europe/Samara',
'Asia/Yekaterinburg',
'Asia/Omsk',
'Asia/Krasnoyarsk', 'Asia/Irkutsk', 'Asia/Yakutsk', 'Asia/Vladivostok', 'Asia/Sakhalin', 'Asia/Anadyr'];
$clientTimeZoneValue = $request->query->get('timezone_value', null);
if ($clientTimeZoneValue !== null) {
$clientTimeZoneValue = (int)$clientTimeZoneValue;
}
/** @var UserIdentity $session */
$session = $this->getUser();
$profile = null;
if (!$session or !$session->getProfileId()) {
throw new UnauthorizedHttpException("Unathorized");
}
$profileId = $session->getProfileId();
$profile = $profileFetcher->find($profileId);
$profileTimeZoneValue = $profile->getTimeZoneValue();
if ($profileTimeZoneValue !== null) {
$profileTimeZoneValue = array_flip($timeZonesDict)[$profileTimeZoneValue];
}
$clientTimeZone = $timeZoneFetcher->findByValue($clientTimeZoneValue);
$clientTimeZoneValueFormatted = '';
if ($clientTimeZoneValue >= 0) {
$clientTimeZoneValueFormatted = "+$clientTimeZoneValue";
} elseif ($clientTimeZoneValue < 0) {
$clientTimeZoneValueFormatted = "-$clientTimeZoneValue";
}
$clientTimeZoneTitle = $clientTimeZone ? $clientTimeZone['title'] : null;
$clientTimeZoneDate = new \DateTimeImmutable();
$clientTimeZoneDate = $clientTimeZoneDate->setTimezone(new DateTimeZone($clientTimeZoneValueFormatted));
$clientTimeZoneMskDiff = $mskDiffHelper->getDiffOffset($clientTimeZoneDate);
$clientTimeZoneMskDiff = $mskDiffHelper->mskFormatter($clientTimeZoneMskDiff);
$clientTimeZoneText = $clientTimeZoneValue;
if ($clientTimeZoneValue <= 10 || $clientTimeZoneValue >= -10) {
$clientTimeZoneText = '0' . $clientTimeZoneValue;
}
if ($clientTimeZoneValue >= 0) {
$clientTimeZoneText = '+' . $clientTimeZoneText;
} elseif ($clientTimeZoneValue < 0) {
$clientTimeZoneText = '-' . $clientTimeZoneText;
}
$clientTimeZoneText = $clientTimeZoneText . ':00';
$profileTimeZone = $timeZoneFetcher->findByValue($profileTimeZoneValue);
if ($profileTimeZoneValue >= 0) {
$profileTimeZoneValueFormatted = "+$profileTimeZoneValue";
} elseif ($profileTimeZone < 0) {
$profileTimeZoneValueFormatted = "-$profileTimeZoneValue";
}
$profileTimeZoneTitle = $profileTimeZone ? $profileTimeZone['title'] : null;
$profileTimeZoneDate = new \DateTimeImmutable();
$profileTimeZoneDate = $profileTimeZoneDate->setTimezone(new DateTimeZone($profileTimeZoneValueFormatted));
$profileTimeZoneMskDiff = $mskDiffHelper->getDiffOffset($profileTimeZoneDate);
$profileTimeZoneMskDiff = $mskDiffHelper->mskFormatter($profileTimeZoneMskDiff);
$profileTimeZoneText = $profileTimeZoneValue;
if (abs($profileTimeZoneValue) < 10) {
$profileTimeZoneText = '0' . abs($profileTimeZoneValue);
} else {
$profileTimeZoneText = abs($profileTimeZoneValue);
}
if ($profileTimeZoneValue >= 0) {
$profileTimeZoneText = '+' . $profileTimeZoneText;
} else {
$profileTimeZoneText = '-' . $profileTimeZoneText;
}
$profileTimeZoneText = $profileTimeZoneText . ':00';
if (!$session) {
return new JsonResponse(["session" => null]);
}
$userId = $session->getId();
$cert = $this->certificateFetcher->findDetailByUserId($userId);
$certificateThumbprint = $cert === null ? null : $cert->thumbprint ?? null;
$permissions = $session->getPermissions();
if ($profileId !== null) {
$findJoinUser = $userJoinFetcher->findByUserIdAndProfileId($userId, $profileId);
if ($findJoinUser !== null) {
$permissions = $findJoinUser->permissions;
}
}
return new JsonResponse([
"session" => [
"user_id" => $session->getId(),
"profile_id" => $profileId,
"cert_thumbprint" => $certificateThumbprint,
"email" => $session->getEmail(),
"role" => $session->getRole(),
"permissions" => $permissions,
"role_profile_value" => $profile === null ? null : $profile->role_constant,
"role_profile_name" => $profile === null ? null : $profile->role_name,
"profile_type" => $profile === null ? null : $profile->type_profile,
"client_time_zone_value" => $clientTimeZoneValue,
"client_time_zone_text" => $clientTimeZoneText,
"client_time_zone_title" => $clientTimeZoneTitle,
'client_time_zone_msk_diff' => $clientTimeZoneMskDiff,
"profile_time_zone_value" => $profileTimeZoneValue,
"profile_time_zone_text" => $profileTimeZoneText,
"profile_time_zone_title" => $profileTimeZoneTitle,
'profile_time_zone_msk_diff' => $profileTimeZoneMskDiff,
'handbook_url' => $apiClient->getEndpointWithoutApi(),
'profileTimeZone' => $mskDiffHelper->getDiffOffset($profileTimeZoneDate),
'organizationInn' => $profile->getInn(),
]
]);
}
/**
* @Route("/api/sentry", name="api.sentry.get", methods={"GET"})
*/
public function apiSentry(Request $request): JsonResponse
{
$dsn = $_ENV['SENTRY_DSN'] ?? null;
return new JsonResponse(['SENTRY_DSN' => $dsn]);
}
/**
* @param Request $request
* @return Response
* @Route("/api/settings/frontend-info", name="api.frontend.info", methods="GET")
*/
public function apiSettingsFrontendInfo(Request $request)
{
$data = $this->settingsFetcher->allArray();
return new JsonResponse([
"ORGANIZATION_FULL_NAME" => $data['KEY_FULL_NAME_ORGANIZATION'],
// ["ORGANIZATION_SHORT_NAME" => $data['KEY_SHORT_NAME_ORGANIZATION']],
"ORGANIZATION_INN" => $data['KEY_INN_ORGANIZATION'],
"ORGANIZATION_KPP" => $data['KEY_KPP_ORGANIZATION'],
"ORGANIZATION_OGRN" => $data['KEY_OGRN_ORGANIZATION'],
"ORGANIZATION_PAYMENT_ACCOUNT" => $data['KEY_BANK_CHECKING_ACCOUNT_ORGANIZATION'],
"ORGANIZATION_CORRESPONDENT_ACCOUNT" => $data['KEY_CORRESPONDENT_ACCOUNT_ORGANIZATION'],
"ORGANIZATION_BANK_NAME" => $data['KEY_BANK_NAME_ORGANIZATION'],
"ORGANIZATION_BANK_BIC" => $data['KEY_BANK_BIK_ORGANIZATION'],
"ORGANIZATION_EMAIL" => $data['KEY_EMAIL_SERVICE'],
"ORGANIZATION_PHONE" => $data['KEY_PHONE_SERVICE'],
"ORGANIZATION_FACT_ADDRESS=" => $data['KEY_FACT_ADDRESS_ORGANIZATION'],
"ORGANIZATION_LEGAL_ADDRESS=" => $data['KEY_LEGAL_ADDRESS_ORGANIZATION'],
"PLATFORM_EMAIL_INFO" => $data['KEY_EMAIL_SERVICE'],
"KEY_NAME_SERVICE" => $data['KEY_NAME_SERVICE'],
// "PLATFORM_EMAIL_SUPPORT" => $data['KEY_EMAIL_SERVICE'],
// "LK_DOMAIN" => $data[""],
"PLATFORM_DOMAIN" => "",
]);
// $data = $this->settingsFetcher->
}
/**
* @param string $email
* @return JsonResponse
* @Route("/test-mail/{email}", name="test-mail", methods="GET")
*/
public function testMail(Environment $twig, string $email, MailerInterface $mailer)
{
try {
$emailMessage = (new Email())
->from(new Address("no-reply@rftorgi.ru", "ЭТП РфТорги"))
->to($email)
->subject("Сообщения")
->text("Тестовое сообщение");
// ->html($content);
// $headers = new Headers();
$headers = $emailMessage->getHeaders();
$headers->addTextHeader('List-Unsubscribe', '<https://lk.rftorgi.ru/unsubscribe>, <mailto:' . $email . '>');
$emailMessage->setHeaders($headers);
$mailer->send($emailMessage);
return new JsonResponse(["status" => "ok"]);
} catch (LoaderError $e) {
echo $e->getMessage();
} catch (RuntimeError $e) {
echo $e->getMessage();
} catch (SyntaxError $e) {
echo $e->getMessage();
} catch (TransportExceptionInterface $e) {
echo $e->getMessage();
}
}
}