<?php
namespace App\Controller\Security;
use App\Controller\API\ApiTrait;
use App\Entity\Client;
use App\Entity\Notary;
use App\Entity\Order;
use App\Entity\ServiceForm;
use App\Enum\FormAssessmentType;
use App\Enum\OrderStatus;
use App\Form\ClientType;
use App\Form\ForgotPasswordType;
use App\Form\NotaryClientType;
use App\Form\NotaryType;
use App\Form\RequestConsultationType;
use App\Message\NotaryRegisterMessage;
use App\Service\Merchant\Exception\MerchantException;
use App\Service\Merchant\MerchantBalanceServiceInterface;
use App\Service\Merchant\MerchantPaymentInterface;
use App\Service\Merchant\MerchantTransactionInterface;
use App\Service\Notary\RegistrationEnvironmentResolver;
use App\Service\ServiceForm\Pipeline\ServiceFormPipeline;
use App\Service\ServiceForm\Context\ServiceFormContext;
use App\ValueObject\ShopHost;
use App\Repository\NotaryRepository;
use App\Repository\OrderRepository;
use App\Repository\ServiceFormRepository;
use App\Repository\ServiceSectionGroupRepository;
use App\Repository\ServiceSectionRepository;
use App\Security\LoginFormAuthenticator;
use App\Service\CallbackService\EmailCallbackService;
use App\Service\CallbackService\Exception\TooOftenSendingException;
use App\Service\CheckEmailService;
use App\Service\ClientService;
use App\Service\Notary\NotaryRegisterService;
use App\Service\NotaryCodeService;
use App\Service\OrderSaveManager;
use App\Service\PaperCopyService;
use App\Service\RecoveryPassword;
use App\Service\VinParserManager;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
class PagesController extends AbstractController
{
use ApiTrait;
public function __construct(
private readonly ParameterBagInterface $parameterBag,
private readonly Security $security,
private readonly ClientService $clientService,
) {
}
/**
* @Route("/recovery-password", name="recovery-password", methods={"GET", "POST"})
*/
public function recoveryPassword(Request $request, RecoveryPassword $recoveryPassword): Response
{
$isAjax = $request->isXmlHttpRequest() || $request->headers->get('X-Requested-With') === 'XMLHttpRequest';
if ($isAjax) {
return $this->recoveryPasswordAjax($request, $recoveryPassword);
}
$form = $this->createForm(ForgotPasswordType::class, ['email' => null]);
$form->handleRequest($request);
$email = '';
if ($form->isSubmitted() && $form->isValid()) {
$email = (string) $form->get('email')->getData();
}
$resultText = '';
if ($email) {
$resultText = $recoveryPassword->recoveryPassword($email);
}
return $this->render('security/recoveryPassword.html.twig', [
'form' => $form->createView(),
'resultText' => $resultText,
]);
}
private function recoveryPasswordAjax(Request $request, RecoveryPassword $recoveryPassword): Response
{
$form = $this->createForm(ForgotPasswordType::class, ['email' => null]);
$form->handleRequest($request);
if (!$form->isSubmitted()) {
return $this->response(['error' => 'Форма не была отправлена'], 400);
}
if (!$form->isValid()) {
$errors = [];
foreach ($form->getErrors(true) as $error) {
$errors[] = $error->getMessage();
}
return $this->response(['error' => implode(', ', $errors)], 400);
}
$email = (string)$form->get('email')->getData();
if (empty($email)) {
return $this->response(['error' => 'Email не указан'], 400);
}
$resultText = $recoveryPassword->recoveryPassword($email);
if (str_contains($resultText, 'не существует')) {
return $this->response(['error' => $resultText], 400);
}
return $this->response([
'success' => true,
'message' => $resultText
]);
}
/**
* @Route("/client-registry", name="clientRegistry")
*/
public function clientRegistry(Request $request,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordEncoder,
NotaryCodeService $codeService,
NotaryRepository $notaryRepository,
CheckEmailService $checkEmailService,
LoginFormAuthenticator $login,
UserAuthenticatorInterface $authenticator
): Response
{
//Закрыт ЛК ФЛ
throw $this->createNotFoundException('Страница не найдена');
$client = new Client();
$form = $this->createForm(ClientType::class, $client);
$newEmail = $request->request->get('client') ? $request->request->get('client')['email'] : null;
if ($newEmail) {
if ($checkEmailService->isEmailFree(0, $newEmail)) {
$form->handleRequest($request);
} else {
$form->get('email')->addError(new FormError('Нельзя использовать этот адрес электронной почты '));
}
}
if ($form->isSubmitted() && $form->isValid()) {
if ($notaryCode = $form->get('notaryCode')->getData()) {
if ($notaryId = $codeService->getNotaryCodeFromString($notaryCode)) {
if ($notary = $notaryRepository->find($notaryId)) {
$client->setNotary($notary);
}
}
}
//
// $plainPassword = $client->getPassword();
//
// $a = '0123456789abcdef';
// $secret = '';
// for ($i = 0; $i < 32; $i++) {
// $secret .= $a[rand(0, 15)];
// }
//
// $plainPassword = !empty($plainPassword) ? $plainPassword : $secret;
// $client->setPassword(
// $passwordEncoder->hashPassword($client, $plainPassword)
// );
//
// $client->setRoles(['ROLE_CLIENT']);
$entityManager->persist($client);
$entityManager->flush();
return $authenticator->authenticateUser($client, $login, $request);
}
return $this->render('area/client/forms/registry.html.twig', [
'client' => $client,
'form' => $form->createView(),
]);
}
/**
* Регистрация нотариуса, будущего рефовода. Не отправляем два красных уведомления
*
* @Route("/refovod-partner-registry", name="refovodNotaryRegistry")
*/
public function refovodNotaryRegistry(
Request $request,
LoginFormAuthenticator $login,
UserAuthenticatorInterface $authenticator,
LoggerInterface $logger,
NotaryRegisterService $notaryRegisterService,
RegistrationEnvironmentResolver $registrationEnvironmentResolver,
): Response
{
$notary = new Notary();
$form = $this->createForm(NotaryType::class, $notary);
$form->remove('payLinkReferralEnabled');
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$notary = $notaryRegisterService->register(
$notary,
$registrationEnvironmentResolver->resolveByHost($request->getHost()),
[3]
);
return $authenticator->authenticateUser($notary, $login, $request);
}
foreach ($form->getErrors(true) ?? [] as $error) {
$logger->error("[Ошибка формы регистрации] ". $error->getOrigin()->getName() . " - " . $error->getMessage() . " - " . current($error->getMessageParameters()));
}
return $this->render('area/notary/forms/registry.html.twig', [
'client' => $notary,
'form' => $form->createView(),
]);
}
/**
* @Route("/services-client", name="publicServicesListClient")
*/
public function servicesListClient(
ServiceFormRepository $serviceFormRepository,
ServiceSectionRepository $serviceSectionRepository,
): Response
{
$sections = $serviceSectionRepository->getList();
$serviceForms = $serviceFormRepository->getFormsList();
foreach ($serviceForms as $form) {
$sectionId = $form->getServiceSection()->getId();
$sections[$sectionId]['forms'][] = $form;
}
return $this->render('publicPages/servicesList.html.twig', [
'controller_name' => 'Услуги',
'isClientPage' => true,
'sections' => $sections,
]);
}
/**
* @Route("/services", name="publicServicesList")
*/
public function servicesList(
ServiceFormRepository $serviceFormRepository,
ServiceSectionRepository $serviceSectionRepository,
): Response
{
$sections = $serviceSectionRepository->getList();
$serviceForms = $serviceFormRepository->getFormsList();
foreach ($serviceForms as $form) {
$sectionId = $form->getServiceSection()?->getId();
if(!$sectionId) {
continue;
}
$sections[$sectionId]['forms'][] = $form;
}
return $this->render('publicPages/servicesList.html.twig', [
'controller_name' => 'Услуги',
'isClientPage' => false,
'sections' => $sections,
]);
}
/**
* @Route("/our-contacts",
* host="%public_form_domain%",
* name="publicContactsOldLogo")
*/
public function publicContactsOldLogo()
{
return $this->render('publicPages/contactsOldLogo.html.twig', [
'controller_name' => 'Контакты',
]);
}
/**
* Успешная оплата на стороне банка
*
* @Route("/pay-public/payment-success", name="successPaymentPublicOld")
*/
public function successPaymentPublicOld(Request $request, MerchantTransactionInterface $merchantService): Response
{
$transactionUuid = $request->query->get('trans');
$isSuccess = $merchantService->successOrderByTransactionUuid($transactionUuid, 'successPaymentPublicOld', $this->isGranted('ROLE_WORKER'), true);
return $this->render('publicPages/old/pays/payResult.html.twig', [
'controller_name' => 'Заказ оплачен',
'message' => $isSuccess
]);
}
/**
* @Route("/pay-public/payment-success-callback", name="paymentSuccessCallback")
*/
public function paymentSuccessCallback(
Request $request,
MerchantTransactionInterface $merchantService,
MerchantBalanceServiceInterface $merchantBalanceService,
): Response
{
// todo нужна проверка ip адреса
$requestData = json_decode($request->getContent(), true);
if ($requestData['event'] !== 'payment.succeeded') {
return new Response(sprintf('Event %s not supported', $requestData['event']), 400);
}
if (array_key_exists('transaction_uuid', $requestData['object']['metadata'])) {
$merchantService->successOrderByTransactionUuid(
$requestData['object']['metadata']['transaction_uuid'],
'paymentSuccessCallback',
isWorker: $this->isGranted('ROLE_WORKER'),
isPublicForm: true,
skipStatusReCheck: true,
);
return new Response();
}
if (array_key_exists('operation_uuid', $requestData['object']['metadata'])) {
$merchantBalanceService->successTopUp(
$requestData['object']['metadata']['operation_uuid'],
skipStatusReCheck: true,
);
return new Response();
}
if (array_key_exists('trans', $requestData)) {
$merchantService->successOrderByTransactionUuid(
$requestData['trans'],
'paymentSuccessCallback',
isWorker: $this->isGranted('ROLE_WORKER'),
isPublicForm: true,
skipStatusReCheck: true,
);
return new Response();
}
return new Response('Not supported object type', 400);
}
#[Route(path:"/our-contacts", name:"publicOurContacts")]
#[Route(path:"/contacts", name:"publicContacts")]
public function publicContacts()
{
return $this->render('publicPages/contacts.html.twig', [
'controller_name' => 'Контакты',
'hideSpb' => false
]);
}
#[Route(path:"/about", name:"publicAbout")]
public function publicAbout(Request $request): Response
{
$form = $this->createForm(RequestConsultationType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
}
return $this->render('publicPages/about.html.twig', [
'controller_name' => 'О компании',
'requestConsultationForm' => $form->createView(),
]);
}
/**
* Загрузить файл из директории documents/common
*
* @Route("/downloadCommonFile/{filename}", name="downloadCommonFile")
*
* @param string $filename
* @return Response
*/
public function downloadCommonFile(string $filename)
{
return $this->getFileResponse($filename, 'common/');
}
/**
* Посмотреть файл из директории documents/common
*
* @Route("/public-docs/{filename}", name="seeCommonFile")
*
* @param string $filename
* @return Response
*/
public function seeCommonFile(string $filename)
{
return $this->redirect('/documents/' . 'common/' . $filename);
}
/**
* @Route("/send-phone", name="sendPhoneFromLandingPage")
*/
public function sendPhoneFromLandingPage(Request $request, EmailCallbackService $callbackService): JsonResponse
{
$messageText = $request->get('phone', null);
if (!$messageText) {
return new JsonResponse();
}
try {
$callbackService->sendCallback($messageText);
} catch (TooOftenSendingException $e) {
return $this->response(['error' => $e->getMessage()], 400);
}
return $this->response(['success' => 'Мы скоро свяжемся с вами!'], 200);
}
/**
* @Route("/welcome", name="welcome")
*
* @param ServiceSectionGroupRepository $serviceSectionGroupRepository
* @param Request $request
* @param EntityManagerInterface $entityManager
* @param UserPasswordHasherInterface $passwordEncoder
* @param LoginFormAuthenticator $login
* @param UserAuthenticatorInterface $authenticator
* @param ServiceFormRepository $serviceFormRepository
* @return RedirectResponse|Response
* @throws \Exception
*/
public function welcome(ServiceSectionGroupRepository $serviceSectionGroupRepository,
Request $request,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordEncoder,
LoginFormAuthenticator $login,
UserAuthenticatorInterface $authenticator,
ServiceFormRepository $serviceFormRepository
)
{
$notary = new Notary();
$form = $this->createForm(NotaryType::class, $notary);
$form->remove('payLinkReferralEnabled');
$form->handleRequest($request);
$groupsWithSections = $serviceSectionGroupRepository->getList();
$services = [];
foreach ($serviceFormRepository->findAll() ?: [] as $service) {
/**
* @var ServiceForm $service
*/
$services[$service->getId()] = $service;
}
/**
* @var array<int, mixed> $groupsWithSections
*/
foreach ($groupsWithSections as $key => &$group) {
foreach ($group['sections'] as $sectionKey => &$section) {
foreach ($section['serviceForms'] ?? [] as $serviceForm) {
if($services[$serviceForm['id']]->getIcon() === 'paper-copy') {
//Отдельно отчет
$paperCopy = $services[$serviceForm['id']];
continue;
}
$groupsWithSections[$key]['sections'][$sectionKey]['forms'][] = $services[$serviceForm['id']];
}
}
$group['sections'] = array_reverse($group['sections']);
}
if ($form->isSubmitted() && $form->isValid()) {
$plainPassword = $notary->getPassword();
if (!$plainPassword) {
$plainPassword = $data['password'] = substr(sha1(random_bytes(10)), 0, 10);
}
$notary->setPassword(
$passwordEncoder->hashPassword($notary, $plainPassword)
);
$notary->setRoles(['ROLE_NOTARY']);
$notary->setMoneyBalance(0);
$notary->setBonusBalance(0);
$notary->setRegistrationDateTime(new \DateTimeImmutable());
$notary->setUndrawableBonusBalance(Notary::START_BONUS_BALANCE);
$notary->setNotaryNumber('');
$entityManager->persist($notary);
$entityManager->flush();
$this->dispatchMessage(new NotaryRegisterMessage($notary));
return $authenticator->authenticateUser($notary, $login, $request);
}
return $this->render('publicPages/notaryLandingPage.html.twig', [
'controller_name' => 'Регистрация партнера',
'client' => $notary,
'form' => $form->createView(),
'group' => $groupsWithSections[0],
'paperCopy' => $paperCopy,
'is_login' => true,
]);
}
/**
* @Route("/welcome-client", name="welcomeForCLients")
*
* @param Request $request
* @param EntityManagerInterface $entityManager
* @param UserPasswordHasherInterface $passwordEncoder
* @param LoginFormAuthenticator $login
* @param UserAuthenticatorInterface $authenticator
* @param CheckEmailService $checkEmailService
* @param NotaryCodeService $codeService
* @param NotaryRepository $notaryRepository
* @return Response|null
* @throws \Exception
*/
public function welcomeForCLients(Request $request,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordEncoder,
LoginFormAuthenticator $login,
UserAuthenticatorInterface $authenticator,
CheckEmailService $checkEmailService,
NotaryCodeService $codeService,
NotaryRepository $notaryRepository
)
{
//Закрыт ЛК ФЛ
throw $this->createNotFoundException('Страница не найдена');
$client = new Client();
$form = $this->createForm(ClientType::class, $client);
$form->remove('notaryCode');
$newEmail = $request->request->get('client') ? $request->request->get('client')['email'] : null;
if ($newEmail) {
if ($checkEmailService->isEmailFree(0, $newEmail)) {
$form->handleRequest($request);
} else {
$form->get('email')->addError(new FormError('Нельзя использовать этот адрес электронной почты '));
}
}
if ($form->isSubmitted() && $form->isValid()) {
// if ($notaryCode = $form->get('notaryCode')->getData()) {
// if ($notaryId = $codeService->getNotaryCodeFromString($notaryCode)) {
// if ($notary = $notaryRepository->find($notaryId)) {
// $client->setNotary($notary);
// }
// }
// }
$plainPassword = $client->getPassword();
if (!$plainPassword) {
$plainPassword = $data['password'] = substr(sha1(random_bytes(10)), 0, 10);
}
// $client->setPassword(
// $passwordEncoder->hashPassword($client, $plainPassword)
// );
//
// $client->setRoles(['ROLE_CLIENT']);
$entityManager->persist($client);
$entityManager->flush();
return $authenticator->authenticateUser($client, $login, $request);
}
return $this->render('publicPages/newRegistrationClient.html.twig', [
'client' => $client,
'form' => $form->createView(),
]);
}
/**
* Загрузить файл из директории documents
*
* @Route("/download/{filename}/{orderId}", name="downloadFile")
*
* @param string $filename
* @param int|null $orderId
* @return Response
*/
public function downloadFile(string $filename, int $orderId = null)
{
return $this->getFileResponse($filename);
}
/**
* Обновить статус просмотра заказа
*
* @Route("/setOrderViewed", name="setOrderViewed")
*
* @param Request $request
* @return Response
*/
public function setOrderViewed(Request $request)
{
return $this->json($this->clientService->updateViewedStatusByOrderId($request->get('orderId')));
}
/**
* Обновить статус просмотра заказа
*
* @Route("/setClientViewed", name="setClientViewed")
*
* @param Request $request
* @return Response
*/
public function setClientViewed(Request $request)
{
return $this->json($this->clientService->updateClientViewedStatus($request->get('clientId')));
}
/**
* Публичная страница для оплаты по ссылке
*
* @Route("/p/{orderId}", name="publicPay")
* @param int $orderId
* @param OrderRepository $orderRepository
* @return Response
*/
public function publicPay(int $orderId, OrderRepository $orderRepository): Response
{
$order = $orderRepository->find($orderId);
if (!$order) {
throw $this->createNotFoundException('Ссылка на заказ не найдена');
}
if ($order->getStatus() === Order::STATUS_DRAFT) {
throw $this->createNotFoundException('Ссылка на заказ не найдена');
}
if ($order->getStatus() !== Order::STATUS_NEW) {
return $this->redirectToRoute('publicForm', ['id' => $orderId]);
}
return $this->render('publicPages/pays/payOrder.html.twig', [
'controller_name' => 'Оплата заказа №' . $order->getId() . ' - ' . $order->getOrderName(),
'order' => $order,
]);
}
/**
* Ссылка для создания платежа в банк
*
* @Route("/pay/createPayment/{id}", name="createPaymentPublic")
*/
public function createPaymentPublic(
int $id,
Request $request,
MerchantPaymentInterface $merchantService,
OrderRepository $orderRepository,
): Response
{
$order = $orderRepository->find($id);
if (!$order) {
return $this->render('publicPages/pays/payResult.html.twig', [
'controller_name' => 'Заказ не существует',
'message' => 'Запрашиваемый заказ не существует',
]);
}
if ($order->isStatusPaid()) {
return $this->render('publicPages/pays/payResult.html.twig', [
'controller_name' => 'Заказ оплачен',
'message' => 'Оплата завершена' . "Мы приступили к выполнению вашего заказа №{$order->getId()} «{$order->getOrderName()}»",
]);
}
$successLink = $this->generateUrl('successPaymentPublic', [], UrlGeneratorInterface::ABSOLUTE_URL);
try {
$client = $order->getRealClient();
if(!$client) {
throw new \LogicException("В заказе #{$id} не заполнен клиент");
}
if(!$client instanceof \App\Entity\Client && !$client instanceof \App\Entity\Client\Client2) {
throw new \LogicException("В заказе #{$id} указан клиент не известного типа");
}
$payment = $merchantService->createPayment(
shopHost: ShopHost::fromString($request->getHost()),
order: $order,
returnUrl: $successLink,
payer: $client,
);
} catch (MerchantException $e) {
return $this->render('publicPages/pays/payResult.html.twig', [
'controller_name' => 'Произошла ошибка',
'message' => 'Попробуйте позже',
]);
}
return $this->redirect($payment->confirmationUrl);
}
/**
* Успешная оплата на стороне банка
*
* @Route("/pay/payment-success", name="successPaymentPublic")
*/
public function successPayment(
Request $request,
MerchantTransactionInterface $merchantService,
): Response
{
$transactionUuid = $request->query->get('trans');
$isSuccess = $merchantService->successOrderByTransactionUuid($transactionUuid, 'successPaymentPublic', $this->isGranted('ROLE_WORKER'), true);
return $this->render('publicPages/pays/payResult.html.twig', [
'controller_name' => 'Заказ оплачен',
'message' => $isSuccess ? 'Оплата завершена' : 'Возникла проблема, попробуйте еще раз',
]);
}
/**
* @Route("/area/partner/successBalanceOperation", name="area_notary_successBalanceOperation")
*/
public function successBalanceOperation(Request $request, MerchantBalanceServiceInterface $merchantBalanceService): Response
{
$balanceOperationUuid = $request->query->get('trans');
if (!$balanceOperationUuid) {
return $this->redirectToRoute('paymentCompletedPage');
}
$isSuccess = $merchantBalanceService->successTopUp($balanceOperationUuid);
if (!$this->isGranted('ROLE_NOTARY')) {
return $this->redirectToRoute('paymentCompletedPage');
}
return $this->render('area/notary/successPayment.html.twig', [
'controller_name' => 'Баланс увеличен',
'message' => $isSuccess ? 'Пополнение баланса завершено' : 'Возникла проблема, попробуйте еще раз',
]);
}
/**
* Пустышка для редиректа если человек вышел
*
* @Route("/payment-completed", name="paymentCompletedPage")
*
* @return Response
*/
public function paymentCompletedPage(): Response
{
return $this->render('publicPages/pays/payResult.html.twig', [
'controller_name' => 'Заказ оплачен',
'message' => 'Оплата завершена',
]);
}
/**
* @Route("/pf/{id}", name="publicForm")
*/
public function publicForm(
Order $order,
ServiceFormRepository $serviceFormRepository,
PaperCopyService $paperCopyService,
ServiceFormPipeline $serviceFormPipeline,
): RedirectResponse|Response
{
if ($order->getClient2()) {
return $this->redirectToRoute('public_order_form', ['id' => $order->getId()]);
}
if ($order->getStatus_() !== OrderStatus::Draft) {
if ($order->getWhoPay() === 'client' && $order->getStatus_()->value === OrderStatus::New->value) {
return $this->redirectToRoute('publicPay', ['orderId' => $order->getId()]);
}
return $this->render('publicPages/order_not_draft.html.twig', [
'order_id' => $order->getId(),
'order_status_name' => Order::API_STATUS_NAMES[$order->getStatus_()->value],
]);
}
if ($order->isTranslation()) {
return $this->render('publicPages/translation/form.html.twig', ['id' => $order->getId()]);
}
$createClientForm = $this->createForm(NotaryClientType::class, new Client());
// Используем пайплайн для обработки формы
$context = new ServiceFormContext(order: $order, notary: $order->getNotary());
$form = $serviceFormPipeline->process($order->getServiceFormId(), $context);
// Формируем overForm из данных заказа для фронта
$overForm = array_reduce($order->getData(), function (array $carry, array $datum) {
if (!empty($datum['value'])) {
$carry[] = ['name' => $datum['name'], 'value' => $datum['value']];
}
return $carry;
}, []);
$data = [
'controller_name' => $form->getName(),
'form' => $form,
'order' => $order,
'clients' => [],
'createClientForm' => $createClientForm->createView(),
'overForm' => $overForm,
'pffSaveUrl' => false,
];
if (!$paperCopyService->isPaperCopy($form->getId())) {
$data['paperCopyPrice'] = $paperCopyService->getPaperCopyPriceCached();
}
$data['assessmentTypes'] = FormAssessmentType::getViewFormSelect($form);
$data['assessmentTypeHelpTexts'] = FormAssessmentType::getViewHelpText($form->getBitrixCategoryId());
return $this->render('publicPages/forms/form.html.twig', $data);
}
/**
* @Route("/pff/{id}", name="publicOnlyFilesForm")
* @param int $id
* @param OrderRepository $orderRepository
* @param ServiceFormRepository $serviceFormRepository
* @param PaperCopyService $paperCopyService
* @return Response
*/
public function publicOnlyFilesForm(int $id,
OrderRepository $orderRepository,
ServiceFormRepository $serviceFormRepository,
PaperCopyService $paperCopyService,
): Response
{
$order = $orderRepository->find($id);
if ($order->getStatus() >= Order::STATUS_PAID) {
return $this->render('publicPages/forms/orderStatus.html.twig', ['order' => $order]);
}
if ($order->isTranslation()) {
return $this->render('publicPages/translation/form.html.twig', ['id' => $id]);
}
$form = $serviceFormRepository->find($order->getServiceFormId());
$createClientForm = $this->createForm(NotaryClientType::class, new Client());
if ($order->getRealClient()?->getPartner()?->getIsVip() && $form->getVipPrice()) {
$form->setPrice($form->getVipPrice());
}
if ($order->getRealClient()?->getPartner()?->getPayLinkReferralEnabled() && !$form->isSelfPaperForm()) {
$form->setPrice($form->getPrice() + OrderSaveManager::PUBLIC_FORM_MARGIN);
}
$fields = $form->getFields();
$fields['existsOrderId'] = $order->getId();
//Удаляем все поля кроме полей с файлами
foreach ($fields['tabs'] ?? [] as $tabKey => $tab) {
if ($tab['title'] !== 'Загрузка файлов') {
unset($fields['tabs'][$tabKey]);
}
//Удаление заполненных полей
foreach ($tab['fields'] as $fieldKey => $field) {
if (
!empty($order->getFieldByName($field['id'])) &&
$order->getFieldByName($field['id']) !== '[]'
) {
unset($fields['tabs'][$tabKey]['fields'][$fieldKey]);
}
}
}
$form->setFields($fields);
$overForm = [];
if ($order->getFormAssessmentType() == FormAssessmentType::FOR_INHERITANCE->value) {
if ($placeOpen = $order->getFieldByName('place-open')) {
$form->setValueToFields('place-open', $placeOpen);
}
if ($testatorFIO = $order->getFieldByName('testatorFIO')) {
$form->setValueToFields('testatorFIO', $testatorFIO);
}
if ($deathDateTestator = $order->getFieldByName('deathDateTestator')) {
$form->setValueToFields('deathDateTestator', $deathDateTestator);
}
if ($numberDeathCertificate = $order->getFieldByName('numberDeathCertificate')) {
$form->setValueToFields('numberDeathCertificate', $numberDeathCertificate);
}
} else {
// Удалять поля из других видов оценок:
$form->unSetFieldByName('testatorFIO');
$form->unSetFieldByName('deathDateTestator');
$form->unSetFieldByName('numberDeathCertificate');
if ($formAssessmentType = $order->getFieldByName('formAssessmentType')) {
$overForm[] = ['name' => 'formAssessmentType', 'value' => $formAssessmentType];
}
if ($assessmentDate = $order->getFieldByName('assessment-date')) {
$overForm[] = ['name' => 'assessment-date', 'value' => $assessmentDate];
}
if ($ownerFullName = $order->getFieldByName('owner-full-name')) {
$overForm[] = ['name' => 'owner-full-name', 'value' => $ownerFullName];
}
}
$data = [
'controller_name' => $form->getName(),
'form' => $form,
'order' => $order,
'clients' => [],
'createClientForm' => $createClientForm->createView(),
'overForm' => $overForm,
'pffSaveUrl' => true,
];
if (!$paperCopyService->isPaperCopy($form->getId())) {
$data['paperCopyPrice'] = $paperCopyService->getPaperCopyPriceCached();
}
return $this->render('publicPages/forms/form.html.twig', $data);
}
/**
* @Route("/public/vin-info", name="publicGetVinINFO")
*/
public function publicGetVinINFO(
Request $request,
VinParserManager $vinParserManager,
): JsonResponse
{
$result = $vinParserManager->getData($request->get('typeParse', 'VIN'), $request->get('vin'));
return $this->response(['status' => 200, 'data' => $result]);
}
/**
* @param string $filename
* @param string $folder
* @return Response
*/
private function getFileResponse(string $filename, string $folder = '')
{
if (!$this->security->isGranted('ROLE_USER')) {
return new Response('Access denied', 403);
}
$path = $this->parameterBag->get('kernel.project_dir') . "/public_html/documents/" . $folder;
$content = file_get_contents($path . $filename);
$response = new Response();
//set headers
$response->headers->set('Content-Type', 'mime/type');
$response->headers->set('Content-Disposition', 'attachment;filename="' . $filename);
$response->setContent($content);
return $response;
}
}