<?php
namespace App\Controller\Front;
use App\Classes\FormRequestSparePart;
use App\Controller\Core\BaseFrontController;
use App\Entity\FormQuotationServices;
use App\Entity\FormQuotationTrucks;
use App\Entity\TruckBrand;
use App\Entity\TruckModel;
use App\Entity\TruckTonnage;
use App\Entity\UserClient;
use App\Form\Front\FormQuotationServicesType;
use App\Form\Front\FormQuotationTrucksType;
use App\Form\Front\QuotationRegisterType;
use App\Manager\AdviserUserManager;
use App\Manager\EstablishmentManager;
use App\Manager\FormQuotationRequestManager;
use App\Manager\FormQuotationServicesManager;
use App\Manager\FormQuotationTrucksManager;
use App\Manager\QuotationRequestManager;
use App\Manager\QuotationServicesManager;
use App\Manager\QuotationTrucksManager;
use App\Manager\RequestServiceManager;
use App\Manager\RequestSparePartManager;
use App\Manager\ServiceManager;
use App\Manager\TruckBrandManager;
use App\Manager\TruckModelManager;
use App\Manager\TruckTonnageManager;
use App\Manager\UserClientManager;
use App\Security\ClientQuotationAuthenticator;
use App\Service\CRM\ApiCRM;
use App\Service\CRM\Lead;
use App\Service\Mail\QuotationRequestMail;
use App\Service\Mail\QuotationServicesMail;
use App\Service\Mail\QuotationTrucksMail;
use App\Service\Mail\RequestServiceAdviserMail;
use App\Service\Mail\RequestServiceClientMail;
use App\Service\Mail\RequestSparePartsAdviserMail;
use App\Service\Mail\RequestSparePartsClientMail;
use App\Traits\FormFileTrait;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\File\UploadedFile;
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\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
class QuotationController extends BaseFrontController
{
use FormFileTrait;
const FORM_QUOTATION_TRUCKS = 'sd_form_quotation_trucks_entity';
const FORM_QUOTATION_SERVICES = 'sd_form_quotation_services_entity';
const FORM_QUOTATION_REGISTER = 'sd_form_quotation_register';
const FORM_QUOTATION_REGISTER_ERROR = 'sd_form_quotation_register_error';
/**
* @Route("/cotizar-camiones", name="quotation_trucks", methods={"GET"})
* @Template("front/quotation/trucks.html.twig")
*/
public function quotationTrucks(QuotationTrucksManager $quotationTrucksManager): array
{
$entity = $this->getFormSession(self::FORM_QUOTATION_TRUCKS, new FormQuotationTrucks());
$form = $this->getFormView(FormQuotationTrucksType::class, $entity, 'quotation_trucks_action');
$this->locals['sd'] = $quotationTrucksManager->find(1);
$this->locals['form'] = $form;
return $this->locals;
}
/**
* @Route("/cotizar-camiones", name="quotation_trucks_action", methods={"POST"})
*/
public function quotationTrucksAction(Request $request, FormQuotationTrucksManager $manager, QuotationTrucksMail $mail, ApiCRM $apiCRM): RedirectResponse
{
$entity = new FormQuotationTrucks();
$form = $this->getForm(FormQuotationTrucksType::class, $entity, 'quotation_trucks_action');
$form->handleRequest($request);
if ($form->isValid() && $this->captchaValidate()) {
$manager->save($entity);
$mail->load($entity)->send();
$result = $apiCRM->send(Lead::fromEntity($entity));
$entity->setResultCrm($result);
$manager->save($entity);
return $this->redirectToRoute('thanks_slug', ['slug' => 'cotizar-camiones']);
}
$this->saveFormSession(self::FORM_QUOTATION_TRUCKS, $entity);
return $this->redirectToRoute('quotation_trucks');
}
/**
* @Route("/cotizar-servicios", name="quotation_services", methods={"GET"})
* @Template("front/quotation/services.html.twig")
*/
public function quotationServices(QuotationServicesManager $quotationServicesManager, ServiceManager $serviceManager, AdviserUserManager $adviserUserManager, EstablishmentManager $establishmentManager): array
{
$entity = $this->getFormSession(self::FORM_QUOTATION_SERVICES, new FormQuotationServices());
$form = $this->getFormView(FormQuotationServicesType::class, $entity, 'quotation_services_action');
$this->locals['sd'] = $quotationServicesManager->find(1);
$this->locals['services'] = $serviceManager->valid();
$this->locals['advisers'] = $adviserUserManager->serviceAdviser();
$this->locals['establishments'] = $establishmentManager->inFormQuotationServices();
$this->locals['form'] = $form;
return $this->locals;
}
/**
* @Route("/cotizar-servicios", name="quotation_services_action", methods={"POST"})
*/
public function quotationServicesAction(Request $request, UserClientManager $userClientManager, RequestServiceManager $requestServiceManager, AdviserUserManager $adviserUserManager, FormQuotationServicesManager $manager, QuotationServicesMail $mail, RequestServiceAdviserMail $requestServiceAdviserMail, RequestServiceClientMail $requestServiceClientMail): RedirectResponse
{
$entity = new FormQuotationServices();
$form = $this->getForm(FormQuotationServicesType::class, $entity, 'quotation_services_action');
$form->handleRequest($request);
$adviserId = $request->request->getInt('adviser_id');
$adviser = $adviserUserManager->byId($adviserId);
if (is_null($adviser)) {
$adviser = $adviserUserManager->serviceRandom();
}
$entity->setAdviser($adviser);
if ($form->isValid() && $this->captchaValidate()) {
$entity = $manager->save($entity);
$user = $userClientManager->byDocument($entity->getDocumentNumber());
if (is_null($user)) {
$user = $userClientManager->byEmail($entity->getEmail());
if (is_null($user)) {
$user = $userClientManager->generate($entity->getEmail(), $entity->getName(), $entity->getDocumentNumber(), $entity->getPhone());
}
}
$requestService = $requestServiceManager->fromQuotation($user, $adviser, $entity);
$mail->load($entity)->send();
$requestServiceAdviserMail->load($requestService)->send();
$requestServiceClientMail->load($requestService)->send();
return $this->redirectToRoute('thanks_slug', ['slug' => 'cotizar-servicios']);
}
$this->saveFormSession(self::FORM_QUOTATION_SERVICES, $entity);
return $this->redirectToRoute('quotation_services');
}
/**
* @Route("/cotizar", name="quotation_request", methods={"GET"})
* @Template("front/quotation/quotation_request.html.twig")
*/
public function quotationRequest(QuotationRequestManager $quotationRequestManager, AdviserUserManager $adviserUserManager, TruckBrandManager $truckBrandManager): array
{
$this->locals['advisers'] = $adviserUserManager->sparePartsAdviser();
$this->locals['brands'] = $truckBrandManager->valid();
$this->locals['sd'] = $quotationRequestManager->find(1);
return $this->locals;
}
/**
* @Route("/cotizar", name="quotation_request_action", methods={"POST"})
*/
public function quotationRequestAction(Request $request, RequestSparePartManager $requestSparePartManager, AdviserUserManager $adviserUserManager, FormQuotationRequestManager $manager, QuotationRequestMail $mail, RequestSparePartsAdviserMail $requestSparePartsAdviserMail, RequestSparePartsClientMail $requestSparePartsClientMail): RedirectResponse
{
$brands = $request->request->get('form_brand', []);
$models = $request->request->get('form_model', []);
$vimPlates = $request->request->get('form_vim_plate', []);
$numberCodes = $request->request->get('form_number_code', []);
$quantities = $request->request->get('form_quantity', []);
$discounts = $request->request->get('form_discount', []);
$descriptions = $request->request->get('form_description', []);
$images = $request->files->get('form_images', []);
$spareParts = [];
foreach ($brands as $index => $brand) {
$model = $this->getDataFromRequestArray($models, $index);
$vimPlate = $this->getDataFromRequestArray($vimPlates, $index);
$numberCode = $this->getDataFromRequestArray($numberCodes, $index);
$quantity = $this->getDataFromRequestArray($quantities, $index);
$discount = $this->getDataFromRequestArray($discounts, $index);
$description = $this->getDataFromRequestArray($descriptions, $index);
$image = null;
$imageObject = array_key_exists($index, is_array($images) ? $images : []) ? $images[$index] : null;
if (!is_null($imageObject) and get_class($imageObject) === UploadedFile::class) {
$image = $this->saveFile($imageObject, 1000000, 0, 'cotizaciones-repuestos');
}
$sparePart = (new FormRequestSparePart())->create($brand, $model, $vimPlate, $numberCode, $quantity, $image, $discount, $description);
if (!is_null($sparePart)) {
$spareParts[] = $sparePart->toArray();
}
}
/** @var UserClient $user */
$user = $this->getUser();
$adviserId = $request->request->getInt('quotation_adviser');
$adviser = $adviserUserManager->byId($adviserId);
if (is_null($adviser)) {
$adviser = $adviserUserManager->sparePartsRandom();
}
$entity = $manager->createFromUser($user);
$entity->setSpareParts($spareParts);
$entity->setAdviser($adviser);
$manager->save($entity);
$requestSpareSpart = $requestSparePartManager->fromQuotation($user, $adviser, $entity);
$mail->load($entity)->send();
$requestSparePartsAdviserMail->load($requestSpareSpart)->send();
$requestSparePartsClientMail->load($requestSpareSpart)->send();
return $this->redirectToRoute('quotation_thanks');
}
/**
* @Route("/cotizar/ingreso", name="quotation_login")
* @Template("front/quotation/quotation_login.html.twig")
*/
public function quotationLogin(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('quotation_request');
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$this->locals['error'] = $error;
$this->locals['last_username'] = $lastUsername;
$response = new Response();
$content = $this->renderView('front/quotation/quotation_login.html.twig', $this->locals);
$response->setContent($content);
return $response;
}
/**
* @Route("/cotizar/registro", name="quotation_register", methods={"GET"})
* @Template("front/quotation/quotation_register.html.twig")
*/
public function quotationRegister(QuotationRequestManager $quotationRequestManager): array
{
$session = $this->requestStack->getSession();
$entity = $session->get(self::FORM_QUOTATION_REGISTER, new UserClient());
$session->remove(self::FORM_QUOTATION_REGISTER);
$errors = $session->get(self::FORM_QUOTATION_REGISTER_ERROR, []);
$session->remove(self::FORM_QUOTATION_REGISTER_ERROR);
$session->remove('sd_form_quotation_register_errors');
$form = $this->createForm(QuotationRegisterType::class, $entity, [
'action' => $this->generateUrl('quotation_register_action'),
'method' => 'POST',
])->createView();
$this->locals['sd'] = $quotationRequestManager->find(1);
$this->locals['form'] = $form;
$this->locals['error'] = $errors;
return $this->locals;
}
/**
* @Route("/cotizar/registro", name="quotation_register_action", methods={"POST"})
*/
public function quotationRegisterAction(Request $request, UserPasswordHasherInterface $hasher, UserClientManager $manager, UserAuthenticatorInterface $userAuthenticator, ClientQuotationAuthenticator $clientQuotationAuthenticator): RedirectResponse
{
if ($this->getUser()) {
return $this->redirectToRoute('quotation_request');
}
$entity = new UserClient();
$form = $this->createForm(QuotationRegisterType::class, $entity, [
'action' => $this->generateUrl('quotation_register_action'),
'method' => 'POST',
]);
$form->handleRequest($request);
$entity->setRoles(['ROLE_USER']);
$entity->setType(UserClient::USER_TYPE_CLIENT);
$entity->setPassword($hasher->hashPassword($entity, $entity->getEmail()));
if ($form->isValid() && $this->captchaValidate()) {
$manager->save($entity);
$userAuthenticator->authenticateUser($entity, $clientQuotationAuthenticator, $request);
return $this->redirectToRoute('quotation_request');
}
$error = null;
if ($manager->byDocument($entity->getDocument())) {
$error = 'document';
} elseif ($manager->byEmail($entity->getEmail())) {
$error = 'email';
}
$session = $this->requestStack->getSession();
$session->set(self::FORM_QUOTATION_REGISTER, $entity);
$session->set(self::FORM_QUOTATION_REGISTER_ERROR, $error);
return $this->redirectToRoute('quotation_register');
}
/**
* @Route("/cotizar/gracias", name="quotation_thanks")
* @Template("front/quotation/quotation_thanks.html.twig")
*/
public function quotationThanks(QuotationRequestManager $quotationRequestManager): array
{
$this->locals['sd'] = $quotationRequestManager->find(1);
return $this->locals;
}
/**
* @Route("/cotizar-marcas", name="quotation_brands")
*/
public function quotationBrands(Request $request, TruckBrandManager $truckBrandManager): JsonResponse
{
$brands = $truckBrandManager->valid();
$brandsArray = array_map(function (TruckBrand $brand) { return $brand->toArray(); }, $brands);
$response = new JsonResponse($brandsArray);
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
/**
* @Route("/cotizar-modelos", name="quotation_models")
*/
public function quotationModels(Request $request, TruckModelManager $truckModelManager): JsonResponse
{
$models = $truckModelManager->valid();
$modelsArray = array_map(function (TruckModel $model) { return $model->toArray(); }, $models);
$response = new JsonResponse($modelsArray);
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
/**
* @Route("/cotizar-tonelajes", name="quotation_tonnages")
*/
public function quotationTonnages(Request $request, TruckTonnageManager $truckTonnageManager): JsonResponse
{
$tonnages = $truckTonnageManager->valid();
$tonnagesArray = array_map(function (TruckTonnage $tonnage) { return $tonnage->toArray(); }, $tonnages);
$response = new JsonResponse($tonnagesArray);
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
/**
* @Route("/cotizar-modelos-marca", name="quotation_models_by_brand")
*/
public function quotationModelsByBrand(Request $request, TruckBrandManager $truckBrandManager, TruckModelManager $truckModelManager): JsonResponse
{
$brand = $request->request->get('brand', '');
if (!$brand) {
return new JsonResponse([]);
}
$brand = $truckBrandManager->bySlug($brand);
if (is_null($brand)) {
return new JsonResponse([]);
}
$models = $truckModelManager->byBrand($brand);
$modelsArray = array_map(function (TruckModel $model) { return $model->toArray(); }, $models);
$response = new JsonResponse($modelsArray);
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
/**
* @Route("/cotizar-modelos-tonelajes", name="quotation_models_by_tonnage")
*/
public function quotationModelsByTonnage(Request $request, TruckModelManager $truckModelManager, TruckTonnageManager $truckTonnageManager): JsonResponse
{
$tonnage = $request->request->get('tonnage', '');
if (!$tonnage) {
return new JsonResponse([]);
}
$tonnage = $truckTonnageManager->bySlug($tonnage);
if (is_null($tonnage)) {
return new JsonResponse([]);
}
$models = $truckModelManager->byTonnage($tonnage);
$modelsArray = array_map(function (TruckModel $model) { return $model->toArray(); }, $models);
$response = new JsonResponse($modelsArray);
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
/**
* @Route("/cotizar-tonelajes-modelo", name="quotation_tonnages_by_model")
*/
public function quotationTonnagesByModel(Request $request, TruckModelManager $truckModelManager, TruckTonnageManager $truckTonnageManager): JsonResponse
{
$model = $request->request->get('model', '');
if (!$model) {
return new JsonResponse([]);
}
$model = $truckModelManager->bySlug($model);
if (is_null($model)) {
return new JsonResponse([]);
}
$tonnages = $truckTonnageManager->byModel($model);
$tonnagesArray = array_map(function (TruckTonnage $tonnage) { return $tonnage->toArray(); }, $tonnages);
$response = new JsonResponse($tonnagesArray);
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
protected function getDataFromRequestArray($array, int $index): ?string
{
return array_key_exists($index, is_array($array) ? $array : []) ? $array[$index] : null;
}
}