<?php
namespace App\Controller\RCA;
use App\Controller\BaseController;
use App\Entity\Addressing\Address;
use App\Entity\Addressing\Country;
use App\Entity\Addressing\County;
use App\Entity\Log\LogEmailSending;
use App\Entity\System\ProductStatus;
use App\Entity\Partner\Partner;
use App\Entity\Vignette\Vignette;
use App\Manager\BitbagStatic\BlockManager;
use App\Entity\Customer\TrackerActivity;
use App\Entity\Order\Order;
use App\Entity\RCA\Availability;
use App\Entity\RCA\FuelType;
use App\Entity\RCA\InsuranceCompany;
use App\Entity\RCA\LeasingCompany;
use App\Entity\RCA\MappedCategory;
use App\Entity\RCA\MappedVehicleMake;
use App\Entity\RCA\MappedVehicleModel;
use App\Entity\RCA\RCA;
use App\Entity\RCA\SubCategory;
use App\Entity\RCA\UsageType;
use App\Entity\RCA\VehicleType;
use App\Entity\RoadAssistance\RoadAssistance;
use App\Manager\Cart\CartManager;
use App\Manager\Customer\VehicleManager;
use App\Manager\HuVignette\HuVignetteManager;
use App\Manager\Partner\PartnerManager;
use App\Manager\Rca\HistoryRcaManager;
use App\Manager\Rca\InsuranceCompanyManager;
use App\Manager\Rca\RcaManager;
use App\Manager\Rca\RcaOfferManager;
use App\Manager\Rca\RcaOfferV2Manager;
use App\Manager\RoadAssistance\RoadAssistanceManager;
use App\Model\ShopUserModel;
use App\Model\VignetteCategoryModel;
use App\Service\AddressService;
use App\Service\AuthTokenService;
use App\Service\CustomerService;
use App\Service\EmailService;
use App\Service\Log\LogEmailSendingService;
use App\Service\LogService;
use App\Service\RCAIssueService;
use App\Service\RCAService;
use App\Service\ReCaptcha;
use App\Service\StaticPagesBitbagService;
use App\Service\SystemService;
use App\Validator\RCAVehicleAddressFormValidator;
use App\Validator\RCAVehicleAvailabilityFormValidator;
use App\Validator\RCAVehicleDetailsFormValidator;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use function Sentry\captureException;
use Symfony\Contracts\Translation\TranslatorInterface;
class RCAController extends BaseController
{
public function getVehicleDetails(Request $request)
{
$reCaptcha = new ReCaptcha($_ENV['RECAPTCHA_INVISIBLE_SECRET']);
$response = json_encode(array('error' => 1));
if ($reCaptcha->verify($request->get('token'), $request->getClientIp())->isSuccess()) {
$result = null;
$partnerLimitless = false;
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$hashService = $this->getContainer()->get('app.service.security.hash_generator');
$partnerPublicToken = $request->get(PartnerManager::SESSION_PARTNER_PUBLIC_TOKEN_NAME);
$partnerService = $this->getContainer()->get('app.service.partner.partner');
$partner = $this->getEntityManager()->getRepository(Partner::class)
->findOneBy(array('publicToken' => $partnerPublicToken));
if ($hashService->isEncryptedValueValid($request->get('hash'))) {
$vehicleRetrieverRestrictionService = $this->getContainer()->get('app.service.vehicle_restriction');
$apiVehicleDataService = $this->getContainer()->get('app.service.api_vehicle_data');
if ($savedCar = $vehicleRetrieverRestrictionService->getSavedRcaCar()) {
return new Response($savedCar);
}
$serializer = $this->getContainer()->get('serializer');
if ($partner && $partnerService->checkPartnerAccessRights($partner)) {
$partnerLimitless = $partner->hasAutocompleteLimitless();
}
if ($vehicleRetrieverRestrictionService->checkUserForRcaCarService($this->getUser(), $serializer) || $partnerLimitless) {
if ($vehicleId = $request->get('vehicleId')) {
if (VehicleManager::checkIfVehicleIsEligibleForRcaByVehicleId($vehicleId, $this->getEntityManager())) {
$result = $apiVehicleDataService->findVehicleInDatabaseAndFormatDataForUI($vehicleId);
} else {
$vehicleData = VehicleManager::getRegistrationPlateAndVinByVehicleId($vehicleId, $this->getEntityManager());
$request->request->set('registrationPlate', $vehicleData['registrationPlate']);
$request->request->set('vin', $vehicleData['vin']);
}
}
if (!$result) {
$result = $apiVehicleDataService->findVehicleDetails($request->get('registrationPlate'), $request->get('vin'));
$vehicleRetrieverRestrictionService->logNewEntryForRcaCarService();
if ($partnerLimitless) {
PartnerManager::updateRemainingAutocompleteLimit($partner, $this->getEntityManager());
}
if ($result) {
$response = RCAService::retrieveCustomerDataByVehicleDetailIfAvailable($result, $this->getEntityManager());
$vehicleRetrieverRestrictionService->saveRcaCar($response);
} else {
$response = json_encode(array('status' => 'Nu a fost gasit(a).'));
}
}
} else {
$response = json_encode(array('limitReached' => true));
}
}
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$rcaTrackerActivityService->setVehicleDetailsSearched($customer, $response);
}
return new Response($response);
}
public function getVehicleDetailsByVin(Request $request)
{
$reCaptcha = new ReCaptcha($_ENV['RECAPTCHA_INVISIBLE_SECRET']);
$response = json_encode(array('error' => 1));
if ($reCaptcha->verify($request->get('token'), $request->getClientIp())->isSuccess()) {
$result = null;
$partnerLimitless = false;
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$hashService = $this->getContainer()->get('app.service.security.hash_generator');
$partnerPublicToken = $request->get('partnerPublicToken');
$partnerService = $this->getContainer()->get('app.service.partner.partner');
$partner = $this->getEntityManager()->getRepository(Partner::class)
->findOneBy(array('publicToken' => $partnerPublicToken));
if ($hashService->isEncryptedValueValid($request->get('hash'))) {
$vehicleRetrieverRestrictionService = $this->getContainer()->get('app.service.vehicle_restriction');
$apiVehicleDataService = $this->getContainer()->get('app.service.api_vehicle_data');
$serializer = $this->getContainer()->get('serializer');
if ($partner && $partnerService->checkPartnerAccessRights($partner)) {
$partnerLimitless = $partner->hasAutocompleteLimitless();
}
if ($vehicleRetrieverRestrictionService->checkUserForRcaCarService($this->getUser(), $serializer) || $partnerLimitless) {
if (!$result) {
$result = $apiVehicleDataService->findVehicleDetailsWsByVin($request->get('registrationPlate'), $request->get('vin'));
$vehicleRetrieverRestrictionService->logNewEntryForRcaCarService();
if ($partnerLimitless) {
PartnerManager::updateRemainingAutocompleteLimit($partner, $this->getEntityManager());
}
if ($result) {
$response = RCAService::retrieveCustomerDataByVehicleDetailIfAvailable($result, $this->getEntityManager());
$vehicleRetrieverRestrictionService->saveRcaCar($response);
} else {
$response = json_encode(array('status' => 'Nu a fost gasit(a).'));
}
}
} else {
$response = json_encode(array('limitReached' => true));
}
}
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$rcaTrackerActivityService->setVehicleDetailsSearched($customer, $response);
}
return new Response($response);
}
public function detailsAction(Request $request, TranslatorInterface $translator)
{
$rcaData = [];
$historyRca = [];
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$trackerActivityService = $this->getContainer()->get('app.service.customer.tracker_activity');
$trackerActivityService->startTracking($customer);
$vignetteCategories = (new VignetteCategoryModel($this->getEntityManager()))->getAllCategories();
$render = '@templates/RcaApp/Front/homepage.html.twig';
if ($this->isMobile) {
$render = '@templates/RcaApp/Mobile/homepage.html.twig';
}
$request->getSession()->remove('iframeSourceLink');
$leasingCompanies = $this->getDoctrine()
->getRepository(LeasingCompany::class)->findAll();
$country = $this->getDoctrine()->getRepository(Country::class)->findOneBy(array('code' => 'RO'));
$roadAssistanceService = $this->getContainer()->get('app.service.road_assistance.road_assistance');
if ($request->get('modalVehicleId') && $customer) {
$rcaData = RCAService::retrieveRcaDataByModalVehicleId($customer, $request, $this->getEntityManager());
$request->getSession()->remove('rcaVehicle');
$request->getSession()->remove('rcaCustomerData');
} else {
$historyRca = HistoryRcaManager::validateHistoryRca($request->getSession()->get('historyRca'));
RCAService::checkRcaSession($request);
}
$hashGeneratorService = $this->getContainer()->get('app.service.security.hash_generator');
return $this->render($render, [
'vignetteCategories' => $vignetteCategories,
'isOneYearHuVignetteAvailableThisYear' => new \DateTime <= new \DateTime(HuVignetteManager::LAST_DATE_FOR_ONE_YEAR_HU_VIGNETTE_AVAILABILITY . '-' . date('Y')),
'customerVehicleOrderByOptions' => VehicleManager::getCustomerVehicleOrderByOptions(),
'customerVehicleSearchByFields' => VehicleManager::getCustomerVehicleSearchByFields(),
'historyRca' => $historyRca ?: [],
'countyList' => $this->getDoctrine()->getRepository(County::class)->findAllCountiesByCountryAsArray($country),
'vehicleTypeList' => $this->getDoctrine()->getRepository(VehicleType::class)->findAllAsArrayForUI(),
'rcaMappedCategoryList' => $this->getDoctrine()->getRepository(MappedCategory::class)->findAllAsArray(),
'defaultMakeList' => $this->getDoctrine()->getRepository(MappedVehicleMake::class)->findByVehicleMappedCategoryAsArray(MappedCategory::MAPPED_CATEGORY_VEHICLE),
'availabilityList' => $this->getDoctrine()->getRepository(Availability::class)->findAllAsArray(),
'availabilityIntervalList' => RcaManager::getAvailabilityIntervalList(),
'insuranceCompanyList' => $this->getDoctrine()->getRepository(InsuranceCompany::class)->findAllOnlyNameOrderedByPositionAsArray(),
'fuelTypeList' => $this->getDoctrine()->getRepository(FuelType::class)->findAllAsArray(),
'usageTypeList' => $this->getDoctrine()->getRepository(UsageType::class)->findAllAsArray(),
'leasingCompanyList' => $this->getDoctrine()->getRepository(LeasingCompany::class)->findAllAsArray(),
'leasingCompanies' => $leasingCompanies,
'step' => $request->get('step'),
'haveOldVehicleValues' => (bool)$request->getSession()->get('rcaVehicle'),
'haveOldCustomerValues' => (bool)$request->getSession()->get('rcaCustomerData'),
'isAdmin' => ShopUserModel::checkIfUserIsAdmin($this->getUser(), $this->getEntityManager()),
'accordionBlocksAboutRca' => StaticPagesBitbagService::getAllFilteredBlocksAsArray($this->getEntityManager(), BlockManager::BLOCK_ACCORDION_TEXT_RCA_CODE_PATTERN),
'roadAssistanceDefaultPrice' => $roadAssistanceService->retrieveDefaultPrice(),
'roadAssistanceTranslations' => RoadAssistanceManager::getTranslationsForUI($translator),
'hash' => $hashGeneratorService->getHash(),
'recaptchaSiteKey' => $_ENV['RECAPTCHA_INVISIBLE_KEY'],
'oldVehicle' => $rcaData ? $rcaData['oldVehicle'] : $request->get('oldVehicle'),
'oldCustomer' => $rcaData ? $rcaData['oldCustomer'] : $request->get('oldCustomer'),
'oldOffer' => $rcaData ? $rcaData['oldOffer'] : $request->get('oldOffer'),
'canIssueRoadAssistance' => true,
]);
}
public function vehicleDetailsAction(Request $request)
{
return $this->redirectToRoute('app_shop_rca_details');
}
public function vehicleDetailsFormSubmitAction(Request $request, TranslatorInterface $translator): Response
{
$errors = null;
$session = $request->getSession();
$isMobile = false;
if ($request->request->has('isMobile')) {
$isMobile = $request->get('isMobile') == 'true';
}
$rcaVehicleDetailsFormValidator = new RCAVehicleDetailsFormValidator($this->getEntityManager(), $this->getSerializer(), $isMobile);
if ($rcaVehicleDetailsFormValidator->checkForm($request)) {
if ($request->get('vehicleType') != VehicleType::VEHICLE_REGISTRATION_TYPE_FOR_REGISTRATION) {
$request->request->set('registrationPlate', RCAService::validateAndFormatRegistrationPlate($request->get('registrationPlate')));
}
$rcaAlreadyActive = RCAService::checkRcaAvailability($request, $this->getEntityManager());
if (!$rcaAlreadyActive) {
$errors = json_encode(array('success' => true));
if (RoadAssistanceManager::isVehicleEligibleForRoadAssistance($request->request->all(), true)
&& !RoadAssistanceManager::haveAnActiveRoadAssistanceForRegistrationPlate($request, $this->getEntityManager())) {
$roadAssistanceService = $this->getContainer()->get('app.service.road_assistance.road_assistance');
$roadAssistanceResponse = $roadAssistanceService->storeNewRoadAssistanceInCart(RoadAssistance::FLAG_SOURCE_EXTRA_OPTION, true);
if (!$roadAssistanceResponse['success']) {
if ($roadAssistanceResponse['errorCode']) {
$this->addFlash('error', SystemService::retrieveMessage($roadAssistanceResponse['errorCode'], $translator));
}
}
}
} else {
$errors = json_encode(array('already_an_active_rca' => 1, 'active_rca_valid_until' => $rcaAlreadyActive));
}
} else {
if ($session->has('rcaVehicleDetailsErrors')) {
$errors = $session->get('rcaVehicleDetailsErrors');
}
}
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$rcaTrackerActivityService->setVehicleDetailsSubmitted($customer, $errors);
return new Response($errors);
}
public function getVehicleSubCategoryByCategoryAction(Request $request): Response
{
$vehicleSubCategoryRepository = $this->getDoctrine()->getRepository(SubCategory::class);
$vehicleCategoryId = $request->get('vehicleCategoryId');
$vehicleSubCategory = null;
if ($vehicleCategoryId != null) {
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$vehicleSubCategory = $vehicleSubCategoryRepository->findByCategoryId($vehicleCategoryId);
$vehicleSubCategory = $serializer->serialize($vehicleSubCategory, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getId();
}
]);
}
return new Response($vehicleSubCategory, 200, ['Content-Type' => 'application/json']);
}
public function issueRcaManually(Request $request)
{
$response = json_encode('fail');
$rcaId = $request->get('rcaId');
if ($rcaId) {
$rcaItem = $this->getEntityManager()->getRepository(RCA::class)->find($rcaId);
if ($rcaItem) {
$rcaIssueService = $this->getContainer()->get('app.rca.issue.service');
if ($rcaIssueService->issueRcaItem($rcaItem)) {
if ($rcaIssueService->sendRcaToCustomer($rcaItem, $this->getContainer()->get('twig'))) {
$response = json_encode('success');
}
}
}
}
return new Response($response);
}
public function deactivateRca(Request $request): Response
{
$response = [
'status' => 'fail',
'message' => 'A apărut o eroare neprevăzută.'
];
$rcaId = $request->get('rcaId');
$userId = $request->get('userId') ?? 0;
if ($rcaId) {
$rcaItem = $this->getEntityManager()->getRepository(RCA::class)->find($rcaId);
if ($rcaItem) {
$result = RCAService::deactivateRcaAndCustomerVehicleRcaValidUntil($rcaItem, $userId, $this->getEntityManager());
if ($result['status']) {
$response['status'] = 'success';
$response['message'] = $result['message'];
} else {
$response['message'] = $result['message'];
}
} else {
$response['message'] = 'Polița nu a fost gasita';
}
}
return new Response(json_encode($response));
}
public function offerAction(Request $request)
{
$session = $request->getSession();
$session->remove('rcaOffers');
$session->remove('rcaOfferParams');
$render = '@templates/Front/rca-offers.html.twig';
if ($this->isMobile) {
$render = '@templates/Mobile/rca-offers.html.twig';
}
$availabilityId = InsuranceCompanyManager::retrieveAvailabilityIdFromSession($request->getSession(), $this->getEntityManager());
$insuranceCompanies = InsuranceCompanyManager::getAllActiveInsuranceCompaniesForSelection($this->getEntityManager(), $availabilityId);
return $this->render($render, [
'isAdmin' => ShopUserModel::checkIfUserIsAdmin($this->getUser(), $this->getEntityManager()),
'insuranceCompanies' => $insuranceCompanies
]);
}
public function retrieveInsuranceCompanies()
{
return new Response(json_encode($this->getDoctrine()
->getRepository(InsuranceCompany::class)->findAllOnlyNameOrderedByPosition()));
}
public function retrieveActiveInsuranceCompanies(Request $request)
{
return new Response(json_encode(InsuranceCompanyManager::getAllActiveInsuranceCompaniesForSelection($this->getEntityManager(), $request->get('availabilityId'))));
}
public function getOffers(Request $request)
{
$insuranceCompany = $request->get('insuranceCompany');
$result = json_encode(array('fail' => true));
if ($insuranceCompany) {
$session = $request->getSession();
$offers = new \stdClass();
if ($session->has('rcaOffers')) {
$offers = json_decode($session->get('rcaOffers'));
}
$findOffer = true;
if (!empty($offers)) {
foreach ($offers as $key => $offer) {
if ($key == $insuranceCompany) {
$findOffer = false;
}
}
}
if ($findOffer) {
$rcaIssueService = $this->getContainer()->get('app.rca.issue.service');
if ($session->has('rcaOfferParams')) {
$params = $session->get('rcaOfferParams');
} else {
$params = $rcaIssueService->setParamsForOffers($request, $insuranceCompany);
$session->set('rcaOfferParams', $params);
}
$offerWithDeductedPrice = $rcaIssueService
->getOfferWithDeductedPriceByInsuranceCompanyName($params, $insuranceCompany, $request->request->all());
$offerWithoutDeductedPrice = $rcaIssueService
->getOfferWithoutDeductedPriceByInsuranceCompanyName($params, $insuranceCompany, $request->request->all());
$offers->$insuranceCompany = array('offerWithDeductedPrice' => $offerWithDeductedPrice,
'offerWithoutDeductedPrice' => $offerWithoutDeductedPrice);
$session->set('rcaOffers', json_encode($offers));
$result = json_encode(array('offerWithDeductedPrice' => $offerWithDeductedPrice,
'offerWithoutDeductedPrice' => $offerWithoutDeductedPrice));
} else {
$result = json_encode(array('offerWithDeductedPrice' => $offers->$insuranceCompany->offerWithDeductedPrice,
'offerWithoutDeductedPrice' => $offers->$insuranceCompany->offerWithoutDeductedPrice));
}
LogService::checkRcaOfferErrorAndStoreItIfNew($result, $this->getEntityManager(), $request, $this->getUser(), $params);
}
return new Response($result);
}
public function getOfferWithVue(Request $request)
{
$offers = array();
$data = $request->request->all();
$insuranceCompany = $data['insuranceCompany'];
$quotationType = $data['quotationType'];
$offersRequestUuid = $data['offersRequestUuid'];
$quotationTypeName = RcaOfferManager::getQuotationTypeNameById($quotationType);
$rcaIssueService = $this->getContainer()->get('app.rca.issue.service');
$data['comision'] = $rcaIssueService->setDiscountCommission($request);
$data['vehicle']['validFrom'] = RcaOfferManager::checkVehicleValidFromData($data['vehicle']['validFrom']);
$firstAvailability = $data['availabilityInterval'] != RcaManager::RCA_AVAILABILITY_OTHER_INTERVAL_VALUE ?
RcaManager::getFirstAvailabilityValueOfAvailabilityInterval($data['availabilityInterval']) : $data['vehicle']['availability'];
$params = $rcaIssueService->setParamsForOffersWithVue($data);
if ($rcaIssueService->isOfferEnabledForInsuranceCompanyAndSelectedAvailability($insuranceCompany['id'], $firstAvailability)) {
$params['product']['motor']['termTime'] = $firstAvailability;
$offer = $rcaIssueService->getOfferWithoutDeductedPriceByInsuranceCompanyName($params, $insuranceCompany, $data);
$result = json_encode(array($quotationTypeName => $offer));
LogService::checkRcaOfferErrorAndStoreItIfNew($result, $this->getEntityManager(), $request, $this->getUser(), $params, $firstAvailability, $offersRequestUuid);
$offers[$firstAvailability][$quotationTypeName]
= RcaOfferV2Manager::formatWsOfferResponse($offer, (bool)$quotationType);
} else {
$offers[$firstAvailability][$quotationTypeName]
= RcaOfferManager::getUnavailableMessageForInsuranceCompanyAndSelectedAvailability($insuranceCompany['name'], $firstAvailability);
}
//get Second interval as well if requested
if ($data['availabilityInterval'] != RcaManager::RCA_AVAILABILITY_OTHER_INTERVAL_VALUE) {
$secondAvailability = RcaManager::getSecondAvailabilityValueOfAvailabilityInterval($data['availabilityInterval']);
$params['product']['motor']['termTime'] = $secondAvailability;
if ($rcaIssueService->isOfferEnabledForInsuranceCompanyAndSelectedAvailability($insuranceCompany['id'], $secondAvailability)) {
$offer = $rcaIssueService->getOfferWithoutDeductedPriceByInsuranceCompanyName($params, $insuranceCompany, $data) ;
$result = json_encode(array($quotationTypeName => $offer));
LogService::checkRcaOfferErrorAndStoreItIfNew($result, $this->getEntityManager(), $request, $this->getUser(), $params, $secondAvailability, $offersRequestUuid);
$offers[$secondAvailability][$quotationTypeName]
= RcaOfferV2Manager::formatWsOfferResponse($offer, (bool)$quotationType);
} else {
$offers[$secondAvailability][$quotationTypeName]
= RcaOfferManager::getUnavailableMessageForInsuranceCompanyAndSelectedAvailability($insuranceCompany['name'], $secondAvailability);
}
}
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$paramsAsArray = json_decode(json_encode($params), true);
$rcaTrackerActivityService->setOffers($customer, $paramsAsArray, $offers);
return new Response(json_encode($offers));
}
public function initLogMappingWithVue(Request $request) {
$data = $request->request->all();
$data['insuranceCompany']['name'] = RCA::INSURANCE_COMPANY_GRAWE_NAME;
$data['comision'] = 0;
$firstAvailability = $data['availabilityInterval'] != RcaManager::RCA_AVAILABILITY_OTHER_INTERVAL_VALUE ?
RcaManager::getFirstAvailabilityValueOfAvailabilityInterval($data['availabilityInterval']) : $data['vehicle']['availability'];
$secondAvailability = $data['availabilityInterval'] != RcaManager::RCA_AVAILABILITY_OTHER_INTERVAL_VALUE ?
RcaManager::getSecondAvailabilityValueOfAvailabilityInterval($data['availabilityInterval']) : $data['vehicle']['availability'];
$offersRequestUuid = $data['offersRequestUuid'];
$rcaIssueService = $this->getContainer()->get('app.rca.issue.service');
$params = $rcaIssueService->setParamsForOffersWithVue($data);
LogService::initLogMapping($this->getEntityManager(), $request, $this->getUser(), $params, $firstAvailability, $offersRequestUuid);
LogService::initLogMapping($this->getEntityManager(), $request, $this->getUser(), $params, $secondAvailability, $offersRequestUuid);
return new Response(json_encode(array('status' => 'success')));
}
public function getCountyFromRegistrationPlate(Request $request)
{
$data = $request->request->all();
if(!empty($data['code'])) {
$county = $this->getDoctrine()->getRepository(County::class)->findByCode($data['code']);
$countyName = $county->getName();
}
if(!empty($countyName)) {
return new Response(json_encode(array('status' => 'success', 'county_name' => $countyName)));
}
return new Response(json_encode(array('status' => 'fail')));
}
public function offerSubmitAction(Request $request)
{
$response = RCAService::retrieveSelectedOfferItemAndStoreIt($request);
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$rcaTrackerActivityService->setOfferSubmitted($customer, ['is_stored' => $response]);
return new Response(json_encode(array('isStored' => $response)));
}
public function removeRcaFromCart(Request $request)
{
$response = json_encode(array('status' => 'fail'));
$key = $request->get('key');
$session = $request->getSession();
if ($rcaGlobalOrder = CartManager::getCartData($session, 'rcaGlobalOrder')) {
foreach ($rcaGlobalOrder as $indexKey => $rca) {
if ($key == $indexKey) {
RoadAssistanceManager::removeRoadAssistanceFromRca($rca, $session);
unset($rcaGlobalOrder[$key]);
}
}
$rcaGlobalOrder = array_values($rcaGlobalOrder);
CartManager::setToCart($session, 'rcaGlobalOrder', $rcaGlobalOrder);
$response = json_encode(array('status' => 'success'));
}
return new Response($response);
}
public function setCustomerDataAction(Request $request)
{
$params = $request->request->all();
$rcaService = new RCAService();
$validations = $rcaService->identifyRcaTypeAndValidateVueData($params);
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$rcaTrackerActivityService->setCustomerDetailsSubmitted($customer, $validations->getContent());
return new Response($validations->getContent());
}
public function replaceDiacriticsCustomerDataAction(Request $request)
{
$params = $request->request->all();
$response = RcaManager::replaceDiacriticsCustomerForm($params);
return new Response(json_encode($response));
}
public function showRcaAction(Request $request)
{
$id = $request->get('id');
$order = $this->getDoctrine()->getRepository(Order::class)->find($id);
if ($order->hasRca()) {
$rca = $order->getRca();
foreach ($rca as $rcaItem) {
if ($rcaItem && $rcaItem->getWsOfferId() && $rcaItem->getSeries()) {
$rcaApiService = $this->getContainer()->get('app.rca.issue.service');
$pdf = $rcaApiService->getPdf($rcaItem->getWsOfferId(), $rcaItem->getWsPolicyId());
$pdf = base64_decode($pdf);
header('Content-Type: application/pdf');
echo $pdf;
die();
}
}
}
echo "<script>window.close();</script>";
return new Response('success');
}
public function getVehicleMakeByCategoryAction(Request $request): Response
{
$vehicleMakeRepository = $this->getDoctrine()->getRepository(MappedVehicleMake::class);
$vehicleCategoryId = $request->get('vehicleCategoryId');
$vehicleMake = null;
if ($vehicleCategoryId != null) {
$vehicleMake = $vehicleMakeRepository->findByVehicleMappedCategoryAsArray($vehicleCategoryId);
}
return new Response(json_encode($vehicleMake));
}
public function getVehicleModelsByMakeAction(Request $request): Response
{
$vehicleModelsRepository = $this->getDoctrine()->getRepository(MappedVehicleModel::class);
$vehicleMakeId = $request->get('vehicleMakeId');
$vehicleModel = null;
if ($vehicleMakeId) {
$vehicleModel = $vehicleModelsRepository->findByMakeIdAsArray($vehicleMakeId);
}
return new Response(json_encode($vehicleModel));
}
public function autoLoginRcaClient(Request $request)
{
$redirect = $this->generateUrl('sylius_shop_homepage');
RCAService::removeRcaProcessSession($request);
$authTokenService = new AuthTokenService();
if ($token = $authTokenService->authenticateUserWithToken($request, $this->getEntityManager())) {
$registrationNumber = $request->get('registrationNumber');
$this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch($event, 'security.interactive_login');
$session = $request->getSession();
$session->set('_sylius.cart.FASHION_WEB', 180);
$session->save();
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$commercialNotificationService = $this->getContainer()->get('app.service.customer.commercial_notification');
$commercialNotificationService->markCustomerAsDoubleOptin($customer, $request->getClientIp());
$params = $request->query->all();
$params = RcaManager::formatUrlParams($params);
$params['from'] = TrackerActivity::FROM_COMMERCIAL_NOTIFICATION;
$params['step'] = TrackerActivity::STEP_VEHICLE;
$validFrom = RcaManager::getValidFromForAutologin($request->get('validUntil'));
$params['validFrom'] = $validFrom;
$redirect = $this->generateUrl('app_shop_rca_details', $params);
}
return $this->render('@templates/ShopCustom/Redirect/wait_to_be_redirected.html.twig',[
'url' => $redirect,
]);
}
public function checkRcaAvailabilityAction(Request $request)
{
if ($rcaAlreadyActive = RCAService::checkRcaAvailability($request, $this->getEntityManager())) {
$response = json_encode(array('already_an_active_rca' => 1, 'active_rca_valid_until' => $rcaAlreadyActive));
} else {
$response = json_encode(array('already_an_active_rca' => 0));
}
return new Response($response);
}
public function retrieveCustomerInfoAction(Request $request)
{
$customerInfo = RCAService::checkForCustomerInfoDetails($request, $this->getUser(), $this->getEntityManager());
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$vignettesRepository = $this->getDoctrine()->getRepository(Vignette::class);
if (!$customerInfo && $customer) {
$address = $this->getDoctrine()->getRepository(Address::class)->findLastLegalAddressForCustomer($customer->getId());
if ($address && $address->getCountryCode() == Country::RO_COUNTRY_CODE && $address->getCifCode()) {
$customerInfo['isLeasing'] = false;
$customerInfo['isLegalPerson'] = true;
$customerInfo['cifCode'] = $address->getCifCode();
$customerInfo['companyName'] = $address->getCompanyName();
} elseif ($lastVignetteAddress = $vignettesRepository->getLastSimpleCustomerAddressByCustomer($customer)) {
$vignetteAddress = $lastVignetteAddress->getOrder()->getBillingAddress();
$customerInfo = AddressService::formatAddressDataSimpleCustomerForRca($vignetteAddress, $this->getEntityManager());
}
}
if(!empty($request->get('countyCode')) && !$customerInfo['isLeasing'] && !$customerInfo['isLegalPerson'] ) {
$filledCountyCode = $this->getDoctrine()->getRepository(County::class)->findCodeById($customerInfo['county']);
$hasDifferentCounty = !empty($filledCountyCode) && ($filledCountyCode !== $request->get('countyCode'));
if(!empty($hasDifferentCounty)) {
$customerInfo = [];
return new Response(json_encode($customerInfo));
}
}
$rcaTrackerActivityService = $this->getContainer()->get('app.service.rca.tracker_activity');
$rcaTrackerActivityService->setCustomerInfoRetrieved($customer, $customerInfo);
return new Response(json_encode($customerInfo));
}
public function retrieveAvailabilityInfoAction(Request $request)
{
$availabilityInfo = RCAService::checkForAvailabilityInfoDetails($request, $this->getEntityManager());
return new Response(json_encode($availabilityInfo));
}
public function checkRcaAlreadyInCart(Request $request)
{
$alreadyInCart = RCAService::checkAlreadyInCart($request);
return new Response(json_encode(array('already_in_cart' => $alreadyInCart)));
}
public function retrieveOfferErrorMessage(Request $request)
{
$offer = $request->get('offer');
return new Response(json_encode(RCAService::getErrorMessageForOfferDeductedPrice($offer)));
}
public function showRcaPolicy(Request $request)
{
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$rca = $this->getDoctrine()->getRepository(RCA::class)
->findOneBy(array('wsOfferId' => $request->get('wsOfferId')));
if ($rca && $rca->getCustomer()->getId() == $customer->getId()) {
$rcaApiService = $this->getContainer()->get('app.rca.issue.service');
$pdf = $rcaApiService->getPdf($rca->getWsOfferId(), $rca->getWsPolicyId());
$pdf = base64_decode($pdf);
header('Content-Type: application/pdf');
echo $pdf;
}
return new Response('error');
}
public function showRcaPolicyForPartner(Request $request)
{
$id = $request->get('order_id');
$id = base64_decode($id);
$order = $this->getDoctrine()->getRepository(Order::class)->find($id);
if ($order->hasRca()) {
$rca = $order->getRca();
foreach ($rca as $rcaItem) {
if ($rcaItem && $rcaItem->getWsOfferId() && $rcaItem->getSeries()) {
$rcaApiService = $this->getContainer()->get('app.rca.issue.service');
$pdf = $rcaApiService->getPdf($rcaItem->getWsOfferId(), $rcaItem->getWsPolicyId());
$pdf = base64_decode($pdf);
header('Content-Type: application/pdf');
echo $pdf;
}
}
}
return new Response('error');
}
public function storeDataInSessionAndInVehicleList(Request $request)
{
$rcaIssueService = $this->getContainer()->get('app.rca.issue.service');
$rcaIssueService->storeDataInSessionHistory($request);
$rcaIssueService->storeDataInVehicleList($request, $this->getUser());
return new Response(json_encode(array('status' => 1)));
}
public function deleteItemFromSession(Request $request)
{
$rcaIssueService = $this->getContainer()->get('app.rca.issue.service');
$rcaIssueService->deleteItemFromSessionHistory($request);
return new Response(json_encode(array('status' => 1)));
}
public function addToCartWithOfferCode(Request $request)
{
$authTokenService = new AuthTokenService();
if ($token = $authTokenService->authenticateUserWithToken($request, $this->getEntityManager())) {
$this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch($event, 'security.interactive_login');
$session = $request->getSession();
$session->set('_sylius.cart.FASHION_WEB', 180);
$session->save();
}
$utm = [
'utm_source' => $request->get('utm_source'),
'utm_medium' => $request->get('utm_medium'),
'utm_campaign' => $request->get('utm_campaign'),
'utm_term' => $request->get('utm_term'),
'utm_content' => $request->get('utm_content'),
'utm_id' => $request->get('utm_id')
];
$offer = RcaOfferManager::retrieveOfferFromDb($request->get('code'), $this->getEntityManager());
if ($offer) {
if (!RcaOfferManager::isOfferExpired($offer) && !in_array($request->get('insurance_id'), [5, 6])) {
RCAService::addRcaToCartFromOffer($offer, $request);
$url = $this->generateUrl('app_shop_customer_info', $utm);
} else {
$oldVehicle = $offer->getRequest()['vehicle'];
if (is_int($oldVehicle['make']['name'])){
$oldVehicle['make']['name'] = $this->getEntityManager()->getRepository(MappedVehicleMake::class)->find($oldVehicle['make']['id'])->getName();
}
$oldVehicle['validFrom'] = RcaOfferManager::checkVehicleValidFromData($oldVehicle['validFrom']);
$utm['step'] = 'offer';
$url = $this->generateUrl('app_shop_rca_details', [
'oldVehicle' => $oldVehicle,
'oldCustomer' => $offer->getRequest()['customer'],
'oldOffer' => $offer->getData(),
] + $utm);
}
} else {
$url = $this->generateUrl('app_shop_rca_details', $utm);
}
return $this->render('@templates/ShopCustom/Redirect/wait_to_be_redirected.html.twig',[
'url' => $url,
]);
}
public function showCartWithToken(Request $request)
{
$authTokenService = new AuthTokenService();
if ($token = $authTokenService->authenticateUserWithToken($request, $this->getEntityManager())) {
$this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch($event, 'security.interactive_login');
$session = $request->getSession();
$session->set('_sylius.cart.FASHION_WEB', 180);
$session->save();
}
$url = $this->generateUrl('app_shop_customer_info');
return $this->render('@templates/ShopCustom/Redirect/wait_to_be_redirected.html.twig',[
'url' => $url,
]);
}
public function rcaIframe(Request $request, TranslatorInterface $translator)
{
$session = $request->getSession();
$partnerService = $this->getContainer()->get('app.service.partner.partner');
$partnerService->verifyToken($request, PartnerManager::CAN_ISSUE_RCA_INDEX);
$partner = $partnerService
->retrievePartner($request->getSession()->get(PartnerManager::SESSION_PARTNER_PUBLIC_TOKEN_NAME));
$partnerRole = $partner->getRole();
$token['partnerPublicToken'] = $partner->getPublicToken();
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$trackerActivityService = $this->getContainer()->get('app.service.customer.tracker_activity');
$trackerActivityService->startTracking($customer);
$vignetteCategories = (new VignetteCategoryModel($this->getEntityManager()))->getAllCategories();
$request->get('extOrderId') ? $rcaData = RCAService::retrieveRcaDataForIframeByOrderId($partner, $request, $this->getEntityManager()) : $rcaData = [];
$render = '@templates/RcaApp/Front/iframe.html.twig';
if ($this->isMobile) {
$render = '@templates/RcaApp/Mobile/iframe.html.twig';
}
$request->getSession()->set('iframeSourceLink', $this->generateUrl('app_shop_rca_iframe', $token));
if ($partner->getWithoutLocalStorage()) {
RCAService::removeRcaProcessSession($request);
CartManager::removeAllProductsFromCartBySession($session);
} else {
RCAService::checkRcaSession($request);
}
PartnerManager::checkQRCodeFlow($request);
$leasingCompanies = $this->getDoctrine()
->getRepository(LeasingCompany::class)->findAll();
$country = $this->getDoctrine()->getRepository(Country::class)->findOneBy(array('code' => 'RO'));
$roadAssistanceService = $this->getContainer()->get('app.service.road_assistance.road_assistance');
$historyRca = HistoryRcaManager::validateHistoryRca($request->getSession()->get('historyRca'));
$hashGeneratorService = $this->getContainer()->get('app.service.security.hash_generator');
return $this->render($render, [
'vignetteCategories' => $vignetteCategories,
'isOneYearHuVignetteAvailableThisYear' => new \DateTime <= new \DateTime(HuVignetteManager::LAST_DATE_FOR_ONE_YEAR_HU_VIGNETTE_AVAILABILITY . '-' . date('Y')),
'customerVehicleOrderByOptions' => VehicleManager::getCustomerVehicleOrderByOptions(),
'customerVehicleSearchByFields' => VehicleManager::getCustomerVehicleSearchByFields(),
'historyRca' => $historyRca ?: [],
'countyList' => $this->getDoctrine()->getRepository(County::class)->findAllCountiesByCountryAsArray($country),
'vehicleTypeList' => $this->getDoctrine()->getRepository(VehicleType::class)->findAllAsArrayForUI(),
'rcaMappedCategoryList' => $this->getDoctrine()->getRepository(MappedCategory::class)->findAllAsArray(),
'defaultMakeList' => $this->getDoctrine()->getRepository(MappedVehicleMake::class)->findByVehicleMappedCategoryAsArray(MappedCategory::MAPPED_CATEGORY_VEHICLE),
'availabilityList' => $this->getDoctrine()->getRepository(Availability::class)->findAllAsArray(),
'availabilityIntervalList' => RcaManager::getAvailabilityIntervalList(),
'insuranceCompanyList' => $this->getDoctrine()->getRepository(InsuranceCompany::class)->findAllOnlyNameOrderedByPositionAsArray(),
'fuelTypeList' => $this->getDoctrine()->getRepository(FuelType::class)->findAllAsArray(),
'usageTypeList' => $this->getDoctrine()->getRepository(UsageType::class)->findAllAsArray(),
'leasingCompanyList' => $this->getDoctrine()->getRepository(LeasingCompany::class)->findAllAsArray(),
'leasingCompanies' => $leasingCompanies,
'step' => $request->get('step'),
'haveOldVehicleValues' => (bool)$request->getSession()->get('rcaVehicle'),
'haveOldCustomerValues' => (bool)$request->getSession()->get('rcaCustomerData'),
'isAdmin' => ShopUserModel::checkIfUserIsAdmin($this->getUser(), $this->getEntityManager()),
'accordionBlocksAboutRca' => StaticPagesBitbagService::getAllFilteredBlocksAsArray($this->getEntityManager(), BlockManager::BLOCK_ACCORDION_TEXT_RCA_CODE_PATTERN),
'roadAssistanceDefaultPrice' => $roadAssistanceService->retrieveDefaultPrice(),
'roadAssistanceTranslations' => RoadAssistanceManager::getTranslationsForUI($translator),
'hash' => $hashGeneratorService->getHash(),
'recaptchaSiteKey' => $_ENV['RECAPTCHA_INVISIBLE_KEY'],
'oldVehicle' => $rcaData ? $rcaData['oldVehicle'] : $request->get('oldVehicle'),
'oldCustomer' => $rcaData ? $rcaData['oldCustomer'] : $request->get('oldCustomer'),
'oldOffer' => $rcaData ? $rcaData['oldOffer'] : $request->get('oldOffer'),
'canIssueRoadAssistance' => PartnerManager::doRoleHaveAccess($partnerRole, PartnerManager::CAN_ISSUE_ROAD_ASSISTANCE_INDEX),
'partner' => $partner,
]);
}
public function showRcaPolicyDocument(Request $request)
{
$wsOfferId = $request->get('ws_offer_id');
if ($wsOfferId) {
$rcaApiService = $this->getContainer()->get('app.rca.issue.service');
$rca = $this->getDoctrine()->getRepository(RCA::class)
->findOneBy(array('wsOfferId' => $wsOfferId));
$pdf = $rcaApiService->getPdf($rca->getWsOfferId(), $rca->getWsPolicyId());
$pdf = base64_decode($pdf);
header('Content-Type: application/pdf');
echo $pdf;
}
return new Response('error');
}
public function sendCustomerAndVehicleDataForCasco(Request $request)
{
$apiVehicleDataService = $this->getContainer()->get('app.service.api_vehicle_data');
$logEmailSendingService = new LogEmailSendingService($this->getEntityManager());
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
if (!$customer || !$request->get('vehicleId')) {
return new Response('error');
}
$rcaData = RCAService::retrieveCustomerAndVehicleDataByModalVehicleId($customer, $request, $apiVehicleDataService, $this->getEntityManager());
if (empty($rcaData)) {
$logEmailSendingService->storeNewLogEmailForCustomer($customer, LogEmailSending::EMAIL_CASCO_OFFER, false, array('error' => 'no valid data'));
return new Response('error');
}
if ($logEmailSendingService->checkIfEmailIsSentByAdditionalInfoAndEmailType($rcaData['vehicle']['registrationPlate'], LogEmailSending::EMAIL_CASCO_OFFER)) {
return new JsonResponse(['error' => 'Oferta a fost trimisa anterior, o sa fiti contactat pentru o oferta in cel mai scurt timp']);
}
$dataToSend = EmailService::formatJsonDataForEmailReading($rcaData);
$message = (new \Swift_Message('Cerere Oferta Casco - Nume Client:' . $customer->getFullName()))
->setFrom($_ENV['EMAIL_USERNAME'])
->setBcc($_ENV['EMAIL_ADMIN_SCALA'])
->setTo($_ENV['EMAIL_PARTENER_CASCO'])
->setBody('Buna ziua,<br>' . $dataToSend)
->setContentType("text/html");
$isSent = EmailService::sendEmail($message, $customer->getEmail());
$logEmailSendingService->storeNewLogEmailForCustomer($customer, LogEmailSending::EMAIL_CASCO_OFFER, $isSent, $rcaData);
return new Response(json_encode($isSent));
}
}