<?php
namespace App\Services\Helpers;
use App\Entity\CoreBundle\Lead;
use App\Entity\CoreBundle\LeadHistory;
use App\Factory\Leads\LeadFactory;
use App\Services\Authorization;
use App\Services\Currency;
use App\Services\DeleteEntities;
use App\Services\Exporter;
use App\Services\myMailer;
use App\Services\RESTApiService;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Container\ContainerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class LeadHelper
{
private Currency $currency;
private EntityManagerInterface $em;
private UserHelper $userHelper;
private Logger $logger;
private $twig;
public function __construct(EntityManagerInterface $em, Currency $currency, UserHelper $userHelper, Logger $logger,
ContainerInterface $container)
{
$this->currency = $currency;
$this->em = $em;
$this->userHelper = $userHelper;
$this->logger = $logger;
$this->twig = $container->get('twig');
}
public function isAllLeadsHaveSameStatus(array $leads): array
{
$allLeadsHaveSameStatus = true;
$firstLeadStatusId = -1;
$counter = 0;
foreach ($leads as $lead)
{
if($counter == 0)
{
$firstLeadStatusId = $lead->getStatus()->getId();
$counter++;
}
else
{
if($lead->getStatus()->getId() != $firstLeadStatusId)
{
$allLeadsHaveSameStatus = false;
break;
}
}
}
return [ "allLeadsHaveSameStatus" => $allLeadsHaveSameStatus ,
"statusId" => $firstLeadStatusId];
}
public function calculateLeadTotalPrice(Lead $lead): array
{
//(1).1st PC price
$mainUpSellPrice = $lead->getMainUpSellPrice();
$mainUpSellPriceInSystem = $lead->getMainUpSellPriceInSystem();
$mainUpSellPriceWithCurrency = $this->currency->priceFormat($mainUpSellPrice , $lead->getOffer()->getCountry()->getCurrencySymbol());
$totalNumberOfAllPurchasedItems = 1;
//(2).UpSells Price
$upSellPrice = 0;
$upSellPriceInSystem = 0;
if(count($lead->getExtraUpSells()) > 0)
{
foreach ($lead->getExtraUpSells() as $upSell)
{
$upSellPrice += $upSell->getTotalPriceInCountry();
$upSellPriceInSystem += $upSell->getTotalPriceInSystem();
$totalNumberOfAllPurchasedItems += $upSell->getNumberOfPieces();
}
}
$upSellPriceWithCurrency = $this->currency->priceFormat($upSellPrice , $lead->getOffer()->getCountry()->getCurrencySymbol());
//(3).Cross Sells Price
$crossSellsPrice = 0; //1
$crossSellsPriceInSystem = 0;
foreach ($lead->getCrossSells() as $crossSell)
{
$crossSellsPrice += $crossSell->getUnitPriceInCountry() * $crossSell->getNumberOfPieces();
$crossSellsPriceInSystem += $crossSell->getUnitPriceInSystem() * $crossSell->getNumberOfPieces();
$totalNumberOfAllPurchasedItems += $crossSell->getNumberOfPieces();
}
$crossSellsPriceWithCurrency = $this->currency->priceFormat($crossSellsPrice , $lead->getOffer()->getCountry()->getCurrencySymbol());
//(4).Gifts Price
$giftsPrice = 0;
$giftsPriceInSystem = 0;
foreach ($lead->getGifts() as $gift)
{
$giftsPrice += $gift->getTotalPriceInCountry();
$giftsPriceInSystem += $gift->getTotalPriceInSystem();
}
$giftsPriceWithCurrency = $this->currency->priceFormat($giftsPrice , $lead->getOffer()->getCountry()->getCurrencySymbol());
//(5). Taxes + TotalCost
$subTotal = $mainUpSellPrice + $upSellPrice + $crossSellsPrice + $giftsPrice;
$subTotalInSystem = $mainUpSellPriceInSystem + $upSellPriceInSystem + $crossSellsPriceInSystem + $giftsPriceInSystem;
//Delivery In Progress = 8 / Success Delivery = 9 / Not Paid = 10 / Returned = 11 ------> From Database
//View
if(($lead->getStatus()->getId() == 8 || $lead->getStatus()->getId() == 9 || $lead->getStatus()->getId() == 10 ||
$lead->getStatus()->getId() == 11) && ($lead->getTotalCostInSystem() > 0))
{
$allTaxesPrice = $lead->getTotalTaxes();
$allTaxesPriceInSystem = $lead->getTotalTaxesInSystem();
$totalCost = $lead->getTotalCost();
$deliveryFees = $lead->getDeliveryFees();
$totalCostInSystem = $lead->getTotalCostInSystem();
$totalCostWithCurrency = $this->currency->priceFormat($totalCost , $lead->getOffer()->getCountry()->getCurrencySymbol());
}
else
{
$allTaxesPrice = 0;
$allTaxesPriceInSystem = 0;
foreach ($lead->getOffer()->getCountry()->getTaxes() as $tax)
{
if($tax->getOperator() == 'percentage')
{
$allTaxesPrice += ($tax->getValue() / 100) * $subTotal;
$allTaxesPriceInSystem += ($tax->getValueInSystem() / 100) * $subTotal;
}
else
{
$allTaxesPrice += $tax->getValue();
$allTaxesPriceInSystem += $tax->getValueInSystem();
}
}
$deliveryFees = 0;
if($lead->getDeliveryType() == "Free")
{
if ($totalNumberOfAllPurchasedItems >= $lead->getNumberOfPCsForFreeDelivery())
$deliveryFees = 0;
else
{
if($lead->getCity())
$deliveryFees = $lead->getCity()->getDeliveryFees();
}
}
else
{
if($lead->getCity())
$deliveryFees = $lead->getCity()->getDeliveryFees();
}
//$deliveryFees is city currency so can only be added here
$totalCost = $subTotal + $allTaxesPrice + $deliveryFees;
$totalCostInSystem = $subTotalInSystem + $allTaxesPriceInSystem;
$totalCostWithCurrency = $this->currency->priceFormat($totalCost , $lead->getOffer()->getCountry()->getCurrencySymbol());
}
$taxesPriceWithCurrency = $this->currency->priceFormat($allTaxesPrice , $lead->getOffer()->getCountry()->getCurrencySymbol());
return ['totalCost' => $totalCost , 'totalCostWithCurrency' => $totalCostWithCurrency ,
'totalTaxes' => $allTaxesPrice , 'totalTaxesPriceWithCurrency' => $taxesPriceWithCurrency ,
'crossSellsPrice' => $crossSellsPriceWithCurrency , 'mainUpSellPrice' => $mainUpSellPriceWithCurrency ,
'upSellsPrice' => $upSellPriceWithCurrency , 'giftsPrice' => $giftsPriceWithCurrency ,
'allTaxesPriceInSystem' => $allTaxesPriceInSystem ,'totalCostInSystem' => $totalCostInSystem ,
'deliveryFees' => $deliveryFees ];
}
public function validateLeadForLoggedInOperator(Lead $lead , $params = []): array
{
$loggedInUser = $this->userHelper->getUser();
$userType = $this->userHelper->getLoggedUserEntity();
if($userType != 'User')
{
$getLog = array_key_exists('getLog' , $params) ? $params['getLog'] : NULL;
$callingFunction = array_key_exists('callingFunction' , $params) ? $params['callingFunction'] : '';
$failExit = false;
if ($lead->getAssignedOperator() == NULL || $lead->getAssignedOperator()->getId() != $loggedInUser->getId())
{
$failExit = true;
$message = "Operator(" . $loggedInUser->getUsername().") Not Assigned to this lead (" . $callingFunction . ")";
$this->logger->createLeadLog('error', ['updatedLead' => $lead,'message' => $message]);
$data['errorType'] = "unAssigned";
$data["errorTitle"] = "You have been unassigned to this lead !";
}
else if($lead->getOperatorPlannedCall() != NULL)
{
$failExit = true;
$message = "Operator(" . $loggedInUser->getUsername().") Can't edit Lead in Planned Call List (" . $callingFunction .")";
$this->logger->createLeadLog('error', ['updatedLead' => $lead,'message' => $message]);
$data['errorType'] = "leadInPlannedCallList";
$data["errorTitle"] = "This lead in planned call list !";
}
if($failExit == true)
{
if($getLog != NULL && $getLog == true)
{
$logs = $this->em->getRepository(Lead::class)->getLeadLogAndLeadComments($lead->getId());
$data['logHtml'] = $this->twig->render('CoreBundle/Lead/parts/infoPopupLog.html.twig', ['leadLog' => $logs]);
//$data['logHtml'] = $this->renderView(
}
$data["status"] = "error";
$data["errorMessage"] = "Please Refresh The Page";
return ['valid' => false , 'data' => $data];
}
}
return ['valid' => true];
}
public function copyLead(Lead $lead): Lead
{
$newLead = new Lead();
$newLead->setLanguage($lead->getLanguage());
$newLead->setAddress($lead->getAddress());
$newLead->setName($lead->getName());
$newLead->setPhone($lead->getPhone());
$newLead->setLanguage($lead->getLanguage());
$newLead->setInformation($lead->getInformation());
$newLead->setEmail($lead->getEmail());
$newLead->setCity($lead->getCity());
$newLead->setLeadSource($lead->getLeadSource());
$newLead->setStatus($lead->getStatus());
$newLead->setAssignedOperator($lead->getAssignedOperator());
return $newLead;
}
public function isPlanDeliveryDateStringValid($dateString): bool
{
$valid = (bool)strtotime($dateString); //check string
if(!$valid)
return false;
$dateConverted = strtotime($dateString);
$oldTime = strtotime("-1 day", time());
if($dateConverted < $oldTime)
return false;
return true;
}
public function createLead(array $params = []): Lead
{
LeadFactory::setDependencies($this->em, $this->userHelper);
$lead = LeadFactory::create($params);
$this->em->persist($lead);
return $lead;
}
public function createNewLeadHistory(Lead $lead): void
{
//Create New History
$result = $this->em->getRepository(Lead::class)->isLeadWasSentFromExistedSource($lead->getPhone(), $lead->getEmail());
if ($result)
{
foreach ($result as $matchedLead)
{
if ($matchedLead->getId() != $lead->getId()) //not the same ids
{
//Create History
$leadHistory = new LeadHistory();
$leadHistory->setNewLead($lead);
$leadHistory->setFoundLead($matchedLead);
$this->em->persist($leadHistory);
}
}
}
}
public function getNotFoundHashes($orderHashes): array
{
if($orderHashes == NULL || count($orderHashes) == 0)
return [];
//Check For In Valid Hashes
$hashesNotFound = [];
$leadHashes = $this->em->getRepository(Lead::class)->getLeadHashesByHashes($orderHashes);
if(count($leadHashes) != count($orderHashes))
{
for ($i = 0; $i < count($orderHashes); $i++)
{
$found = false;
foreach ($leadHashes as $leadHash)
{
$orderHashes[$i] = trim(preg_replace('/\s+/', '', $orderHashes[$i]));
if ($orderHashes[$i] == $leadHash['hash'])
{
$found = true;
break;
}
}
if(!$found)
array_push($hashesNotFound , $orderHashes[$i]);
}
}
return $hashesNotFound;
}
}