src/Controller/CrmController.php line 401

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Agent;
  4. use App\Entity\Customer;
  5. use App\Entity\CustomerComment;
  6. use App\Entity\Mail;
  7. use App\Entity\MailAttachment;
  8. use App\Entity\Parameter;
  9. use DateInterval;
  10. use DateTime;
  11. use Doctrine\Persistence\ObjectManager;
  12. use Error;
  13. use SSilence\ImapClient\ImapClientException;
  14. use SSilence\ImapClient\ImapClient;
  15. use SSilence\ImapClient\IncomingMessage;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. class CrmController extends AbstractCrmController
  20. {
  21.     /**
  22.      * @Route("/mailSingle", name="mailSingle")
  23.      * @return Response
  24.      * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  25.      */
  26.     public function mailSingle(Request $request): Response
  27.     {
  28.         /** @var  $agent Agent */
  29.         $agent $this->get('session')->get('User');
  30.         $em $this->getDoctrine()->getManager();
  31.         $repoMail $em->getRepository(Mail::class);
  32.         /** @var  $mail Mail */
  33.         $mail $repoMail->findOneById($request->get('id'));
  34.         $repoMailAttachment $em->getRepository(MailAttachment::class);
  35.         $mailAttachments $repoMailAttachment->findByMail($mail->getId());
  36.         if ($mailAttachments == null) {
  37.             $mailAttachments = array();
  38.         }
  39.         //if($mail->getAgent()->getId() == $agent->getId())
  40.         return $this->render('crm/mailSingle.html.twig', [
  41.             'email' => $mail,
  42.             'mailAttachments' => $mailAttachments
  43.         ]);
  44.     }
  45.     /**
  46.      * @Route("/myEmails", name="myEmails")
  47.      * @return Response
  48.      * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  49.      */
  50.     public function myEmails(): Response
  51.     {
  52.         /** @var  $agent Agent */
  53.         $agent $this->get('session')->get('User');
  54.         $em $this->getDoctrine()->getManager();
  55.         $repoMail $em->getRepository(Mail::class);
  56.         $existing $repoMail->findBy(array('agent' => $agent), array('message_uid' => 'DESC'));
  57.         return $this->render('crm/myEmails.html.twig', [
  58.             'emails' => $existing,
  59.             'detailsView' => false
  60.         ]);
  61.     }
  62.     /**
  63.      * @Route("/getEmail", name="getEmail")
  64.      * @return Response
  65.      * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  66.      */
  67.     public function getEmail(Request $request): Response
  68.     {
  69.         $forceMode $request->get('force') == null || $request->get('force') == '' : ($request->get('force') == '1' 0);
  70. //        throw new \Exception("forceMode " . $forceMode);
  71.         /** @var  $agent Agent */
  72.         $agent $this->get('session')->get('User');
  73.         if ($agent == null) {
  74.             return $this->render('crm/getEmail.html.twig', [
  75.                 'emaill' => "noAgent"
  76.             ]);
  77.         }
  78.         if ($agent->getPasswordToEmail() == null) {
  79.             return $this->render('crm/getEmail.html.twig', [
  80.                 'emaill' => "no password to email"
  81.             ]);
  82.         }
  83.         $now = new DateTime('now');
  84.         $emailAllowedDate $agent->getEmailAllowDate();
  85.         if ($emailAllowedDate == null) {
  86.             $emailAllowedDate $now;
  87.         }
  88.         if (!$forceMode && $emailAllowedDate->getTimestamp() > $now->getTimestamp()) {
  89.             return $this->render('crm/getEmail.html.twig', [
  90.                 'emaill' => "getEmail is allowed only each 5 minutes"
  91.             ]);
  92.         }
  93.         $em $this->getDoctrine()->getManager();
  94.         $repoAgent $em->getRepository(Agent::class);
  95.         /** @var $agent Agent */
  96.         $agent $repoAgent->findOneById($agent->getId());
  97.         $newEmailAllowedDate = new DateTime('now');
  98.         $newEmailAllowedDate->add(new DateInterval('PT5M'));
  99.         $agent->setEmailAllowDate($newEmailAllowedDate);
  100.         $em->persist($agent);
  101.         $em->flush();
  102.         $mailbox 'ssl0.ovh.net:993';
  103.         $username $agent->getEmail();//'test@unimetasoft.com';
  104.         $password $agent->getPasswordToEmail(); //'LEn3EpMRW7v3YNs';
  105.         $encryption ImapClient::ENCRYPT_SSL// TLS OR NULL accepted
  106. // Open connection
  107.         try {
  108.             $imap = new ImapClient($mailbox$username$password$encryption);
  109.             // You can also check out example-connect.php for more connection options
  110.         } catch (ImapClientException $error) {
  111.             echo $error->getMessage() . PHP_EOL// You know the rule, no errors in production ...
  112.             die(); // Oh no :( we failed
  113.         }
  114.         $mailInfo '';
  115.         $folders $imap->getFolders();
  116.         foreach ($folders as $folder) {
  117.             foreach (array_keys($folder) as $x)
  118.                 //echo array_keys($x);
  119.                 $mailInfo .= ' folder [ ' $x ' ]';
  120.         }
  121. // Select the folder INBOX
  122.         $imap->selectFolder('INBOX');
  123. // Count the messages in current folder
  124.         $overallMessages $imap->countMessages();
  125.         $mailInfo .= '   -> ' $overallMessages;
  126.         if (!$forceMode && $agent->getHowManyMessages() === $overallMessages) {
  127.             return $this->render('crm/getEmail.html.twig', [
  128.                 'emaill' => "norhing to do -> number of messages " $agent->getHowManyMessages()
  129.             ]);
  130.         }
  131.         $unreadMessages $imap->countUnreadMessages();
  132. // Fetch all the messages in the current folder
  133.         $customerRepo $em->getRepository(Customer::class);
  134.         $customers $customerRepo->findAll();
  135.         $numberOfIterations $overallMessages 10;
  136.         $repoMail $em->getRepository(Mail::class);
  137.         for ($i 0$i $numberOfIterations$i++) {
  138.             $messages $imap->getMessages(10$i);
  139.             $existing $repoMail->findByAgent($agent);
  140.             $agent->setHowManyMessages(count($existing));
  141.             $em->persist($agent);
  142.             $em->flush();
  143.             $howMany 0;
  144.             /** @var IncomingMessage $singleMail */
  145.             foreach ($messages as $singleMessage) {
  146.                 $howMany += $this->saveSingleEmail($existing$singleMessage$agent$customers$em);
  147.             }
  148.             $mailInfo .= '  howMany=' $howMany;
  149.             if ($howMany == && !$forceMode) {
  150.                 break;
  151.             }
  152.         }
  153.         $existing $repoMail->findByAgent($agent);
  154.         $agent->setHowManyMessages(count($existing));
  155.         $em->persist($agent);
  156.         $em->flush();
  157.         return $this->render('crm/getEmail.html.twig', [
  158.             'emaill' => $mailInfo
  159.         ]);
  160.     }
  161.     private function isExistingContaining($existing$message_id$messageUid)
  162.     {
  163.         /** @var Mail $singleMail */
  164.         foreach ($existing as $singleMail) {
  165.             if (strval($singleMail->getMessageUid()) === strval($messageUid) && $singleMail->getMessageId() === $message_id) {// &&
  166.                 return true;
  167.             }
  168.         }
  169.         return false;
  170.     }
  171.     /**
  172.      * @Route("/testEmail", name="testEmail")
  173.      * @param \Swift_Mailer $mailer
  174.      * @return Response
  175.      * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  176.      */
  177.     public function testEmail(\Swift_Mailer $mailer): Response
  178.     {
  179.         $message = (new \Swift_Message('Hello Email'))
  180.             ->setFrom('crm@wronieruchomosci.pl')
  181.             ->setTo('tzygadl@gmail.com')
  182.             ->setBody('ggg'
  183. //                $this->renderView(
  184. //                // templates/hello/email.txt.twig
  185. //                    'hello/email.txt.twig',
  186. //                    ['name' => 'xxx']
  187. //                )
  188.             );
  189.         $mailer->send($message);
  190.         return $this->redirectToRoute('app_crm');
  191.     }
  192.     /**
  193.      * @Route("/", name="app_crm")
  194.      * @param Request $request
  195.      * @return Response
  196.      */
  197.     public function index(Request $request): Response
  198.     {
  199.         $em $this->getDoctrine()->getManager();
  200.         $repo $em->getRepository(Customer::class);
  201.         /** @var  $agent Agent */
  202.         $agent $this->get('session')->get('User');
  203.         if ($agent == null) {
  204.             return $this->render('crm/login.html.twig', [
  205.                 'controller_name' => 'CrmController',
  206.             ]);
  207.         }
  208.         if ($request->get('page')) {
  209.             $page $request->get('page');
  210.         } else {
  211.             $page 1;
  212.         }
  213.         if ($request->get('pageToCall')) {
  214.             $pageToCall $request->get('pageToCall');
  215.         } else {
  216.             $pageToCall 1;
  217.         }
  218.         if ($agent->getAgentRole() === 'admin') {
  219.             $all $repo->findAllDesc("/"$page 1);
  220.             $xpages $repo->findAllXpages("/"$page);
  221.         } else {
  222.             $all $repo->findAllDesc("/"$page 1$agent);
  223.             $xpages $repo->findAllXpages("/"$page$agent);
  224.         }
  225.         $tocall $repo->toCall("/"$pageToCall 1$agent);
  226.         $tocallpages $repo->findToCallXpages("/"$page$agent);
  227.         return $this->render('crm/index.html.twig', [
  228.             'controller_name' => 'CrmController',
  229.             'myCustomers' => $all,
  230.             'xpages' => $xpages,
  231.             'tocall' => $tocall,
  232.             'image_picture' => $this->getImagePicture($agent),
  233.             'tocallpages' => $tocallpages,
  234.             'logged' => $agent
  235.         ]);
  236.     }
  237.     /**
  238.      * @Route("/logout", name="logout")
  239.      */
  240.     public function logout(): Response
  241.     {
  242.         $this->get('session')->set('User'null);
  243.         return $this->redirectToRoute('app_crm');
  244.     }
  245.     /**
  246.      * @Route("/login", name="login")
  247.      * @param Request $request
  248.      * @return Response
  249.      */
  250.     public function login(Request $request): Response
  251.     {
  252.         $em $this->getDoctrine()->getManager();
  253.         $repo $em->getRepository(Agent::class);
  254.         if (empty($repo->findAll())) {
  255.             $a = new Agent();
  256.             $a->setEmail('admin@admin.pl');
  257.             $a->setPassword('admin');
  258.             $a->setPasswordToEmail('n/a');
  259.             $a->setFirstname('admin');
  260.             $a->setLastname('admin');
  261.             $a->setAgentRole('admin');
  262.             $em->persist($a);
  263.             $em->flush();
  264.         }
  265.         if ($repo->findBy(
  266.                 array('email' => $request->get('email'), 'password' => $request->get('password'))) == null) {
  267.             return $this->render('crm/login.html.twig', [
  268.                 'controller_name' => 'CrmController',
  269.                 'logged' => $this->get('session')->get('User')
  270.             ]);
  271.         } else {
  272.             $this->get('session')->set('User'$repo->findOneBy(
  273.                 array('email' => $request->get('email'), 'password' => $request->get('password'))));
  274.             return $this->redirectToRoute('app_crm');
  275.         }
  276.     }
  277.     /**
  278.      * @Route("/allContacts", name="allContacts")
  279.      * @param Request $request
  280.      * @return Response
  281.      */
  282.     public function allContacts(Request $request): Response
  283.     {
  284.         if (!$this->get('session')->get('User')) {
  285.             return $this->redirectToRoute('app_crm');
  286.         }
  287.         if (!$this->isAdminOrManager()) {
  288.             return $this->redirectToRoute('app_crm');
  289.         }
  290.         $em $this->getDoctrine()->getManager();
  291.         $repo $em->getRepository(Customer::class);
  292.         if ($request->get('page')) {
  293.             $page $request->get('page');
  294.         } else {
  295.             $page 1;
  296.         }
  297.         $all $repo->findAllDesc("/allContacts"$page 1);
  298.         $xpages $repo->findAllXpages("/allContacts"$page);
  299.         /** @var  $contact Customer */
  300.         $this->repairContactPhones($all$em);
  301.         /** @var  $contact Customer */
  302.         return $this->render('crm/contacts.html.twig', [
  303.             'controller_name' => 'CrmController',
  304.             'myCustomers' => $all,
  305.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  306.             'xpages' => $xpages,
  307.             'logged' => $this->get('session')->get('User')
  308.         ]);
  309.     }
  310.     /**
  311.      * @Route("/myContacts", name="myContacts")
  312.      */
  313.     public function myContacts(Request $request): Response
  314.     {
  315.         if (!$this->get('session')->get('User')) {
  316.             return $this->redirectToRoute('app_crm');
  317.         }
  318.         $em $this->getDoctrine()->getManager();
  319.         $repo $em->getRepository(Customer::class);
  320.         if ($request->get('page')) {
  321.             $page $request->get('page');
  322.         } else {
  323.             $page 1;
  324.         }
  325.         $myContacts $repo->findAllDesc("/myContacts"$page 1$this->get('session')->get('User'));
  326.         $xpages $repo->findAllXpages("/myContacts"$page$this->get('session')->get('User'));
  327.         $this->repairContactPhones($myContacts$em);
  328.         return $this->render('crm/contacts.html.twig', [
  329.             'controller_name' => 'CrmController',
  330.             'myCustomers' => $myContacts,
  331.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  332.             'xpages' => $xpages,
  333.             'logged' => $this->get('session')->get('User')
  334.         ]);
  335.     }
  336.     /**
  337.      * @Route("/searchContacts", name="searchContacts")
  338.      */
  339.     public function searchContacts(Request $request): Response
  340.     {
  341.         if (!$this->get('session')->get('User')) {
  342.             return $this->redirectToRoute('app_crm');
  343.         }
  344.         $em $this->getDoctrine()->getManager();
  345.         $repo $em->getRepository(Customer::class);
  346.         $myContacts $repo->search($request->get('text'), "/searchContacts",
  347.             $this->isAdminOrManager() ? null $this->get('session')->get('User'));
  348.         $xpages = array();
  349.         $this->repairContactPhones($myContacts$em);
  350.         return $this->render('crm/contacts.html.twig', [
  351.             'controller_name' => 'CrmController',
  352.             'myCustomers' => $myContacts,
  353.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  354.             'xpages' => $xpages,
  355.             'logged' => $this->get('session')->get('User')
  356.         ]);
  357.     }
  358.     /**
  359.      * @Route("/newContact", name="newContact")
  360.      */
  361.     public function newContact(): Response
  362.     {
  363.         if (!$this->get('session')->get('User')) {
  364.             return $this->redirectToRoute('app_crm');
  365.         }
  366.         $em $this->getDoctrine()->getManager();
  367. //        $repo = $em->getRepository(Customer::class);
  368.         return $this->render('crm/newContact.html.twig', [
  369.             'controller_name' => 'CrmController',
  370.             'logged' => $this->get('session')->get('User'),
  371.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  372.         ]);
  373.     }
  374.     /**
  375.      * @Route("/reserve", name="reserve")
  376.      */
  377.     public function reserve(Request $request\Swift_Mailer $mailer): Response
  378.     {
  379.         return $this->reserveCustomer($request->get('id'), $request->get('action'), $mailer);
  380.     }
  381.     public function reserveCustomer($id$action\Swift_Mailer $mailer$message null): Response
  382.     {
  383.         if (!$this->get('session')->get('User')) {
  384.             return $this->redirectToRoute('app_crm');
  385.         }
  386.         $em $this->getDoctrine()->getManager();
  387.         $repo $em->getRepository(Customer::class);
  388.         $repo2 $em->getRepository(Agent::class);
  389.         /** @var  $customer Customer */
  390.         $customer $repo->findOneById($id);
  391.         $now = new DateTime('now');
  392.         $user $this->get('session')->get('User');
  393.         if ($customer->getReservedTo() != null && $now $customer->getReservedTo()) {
  394.             if ($customer->getAgent()->getId() != $this->get('session')->get('User')->getId()) {
  395.                 if ($customer->getReservedTo()->getTimestamp() <= $now->getTimestamp()) {
  396.                     $message "przejmujesz_klienta_od_"
  397.                         $customer->getAgent()->getFirstname() . '_' $customer->getAgent()->getLastname();
  398.                     $emailToSend = (new \Swift_Message('PrzejÄ™ty klient '))
  399.                         ->setFrom('crm@wronieruchomosci.pl')
  400.                         ->setTo($customer->getAgent()->getEmail())
  401.                         ->setBody('Użytkownik ' $user->getFirstname() . ' ' $user->getLastname() . ' ' $user->getEmail() . " przejÄ…Å‚ Twojego klienta "
  402.                             $customer->getFirstname() . ' ' $customer->getLastname() . ' ' $customer->getEmail() . ' ' $customer->getPhone());
  403.                     $mailer->send($emailToSend);
  404.                     $customer->setAddDate($now);
  405.                     $customer->setAgent($this->get('session')->get('User'));
  406.                 } else {
  407.                     return $this->redirect($action "?reserved_by=" $customer->getAgent()->getFirstname() . '_' $customer->getAgent()->getLastname());
  408.                 }
  409.             }
  410.         }
  411.         $customer->setAddDate($now);
  412.         $customer->setAgent($repo2->findOneById($this->get('session')->get('User')->getId()));
  413.         $date = new DateTime('now');
  414.         $em $this->getDoctrine()->getManager();
  415.         $repoParameter $em->getRepository(Parameter::class);
  416.         /** @var Parameter $reservationHours */
  417.         $reservationHours $repoParameter->findOneByParam('reservationHours');
  418.         if (!$reservationHours) {
  419.             $reservationHours = new Parameter();
  420.             $reservationHours->setParam("reservationHours");
  421.             $reservationHours->setVal("80");
  422.             $em->persist($reservationHours);
  423.             $em->flush();
  424.         }
  425.         $date->add(new DateInterval('PT' $reservationHours->getVal() . 'H'));
  426.         $customer->setReservedTo($date);
  427.         $em->persist($customer);
  428.         $em->flush();
  429.         if ($message) {
  430.             $redirection "/details?id=" $customer->getId() . "&message=$message";
  431.         } else {
  432.             $redirection $action "?reserved_now=" $customer->getReservedToFormatted();
  433.         }
  434.         return $this->redirect($redirection);
  435.     }
  436.     /**
  437.      * @Route("/call", name="call")
  438.      */
  439.     public function call(Request $request): Response
  440.     {
  441.         $em $this->getDoctrine()->getManager();
  442.         $repo $em->getRepository(Customer::class);
  443.         /** @var  $customer Customer */
  444.         $customer $repo->findOneById($request->get('id'));
  445.         $customer->setStatus('do obdzwonki');
  446.         $em->persist($customer);
  447.         $em->flush();
  448.         return $this->redirect($request->get('action'));
  449.     }
  450.     /**
  451.      * @Route("/callMade", name="callMade")
  452.      */
  453.     public function callMade(Request $request): Response
  454.     {
  455.         if (!$this->get('session')->get('User')) {
  456.             return $this->redirectToRoute('app_crm');
  457.         }
  458.         $em $this->getDoctrine()->getManager();
  459.         $repo $em->getRepository(Customer::class);
  460.         /** @var  $customer Customer */
  461.         $customer $repo->findOneById($request->get('id'));
  462.         $customer->setStatus('obdzwoniono');
  463.         $em->persist($customer);
  464.         $em->flush();
  465.         return $this->redirectToRoute('app_crm');
  466.     }
  467.     /**
  468.      * @Route("/details", name="details")
  469.      */
  470.     public function details(Request $request): Response
  471.     {
  472.         if (!$this->get('session')->get('User')) {
  473.             return $this->redirectToRoute('app_crm');
  474.         }
  475.         /** @var  $agent Agent */
  476.         $agent $this->get('session')->get('User');
  477.         $em $this->getDoctrine()->getManager();
  478.         $repo $em->getRepository(Customer::class);
  479.         $repoComments $em->getRepository(CustomerComment::class);
  480.         /** @var  $customer Customer */
  481.         $customer $repo->findOneById($request->get('id'));
  482.         $repoMail $em->getRepository(Mail::class);
  483.         if (!$this->isAdminOrManager()) {
  484.             if ($customer->getAgent() && $agent->getId() != $customer->getAgent()->getId()) {
  485.                 $customerAgentMails $repoMail->findBy(array('customer' => $customer->getId(), 'agent' => $agent->getId()));
  486.                 if (empty($customerAgentMails)) {
  487.                     return $this->redirectToRoute('app_crm');
  488.                 }
  489.             }
  490.         }
  491.         $customerMails $repoMail->findByCustomer($request->get('id'));
  492.         $customerComments $repoComments->findByCustomer($request->get('id'));
  493.         return $this->render('crm/customerDetails.html.twig', [
  494.             'controller_name' => 'CrmController',
  495.             'logged' => $this->get('session')->get('User'),
  496.             'customerComments' => $customerComments,
  497.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  498.             'isAdminOrManager' => $this->isAdminOrManager(),
  499.             'currentDate' => (new DateTime('now'))->format('Y-m-d'),
  500.             'customer' => $customer,
  501.             'emails' => $customerMails,
  502.             'detailsView' => true
  503.         ]);
  504.     }
  505.     /**
  506.      * @Route("/updateDetails", name="updateDetails")
  507.      */
  508.     public function updateDetails(Request $request): Response
  509.     {
  510.         if (!$this->get('session')->get('User')) {
  511.             return $this->redirectToRoute('app_crm');
  512.         }
  513.         if ($request->get('customertype') == null || $request->get('customertype') === '') {
  514.             return $this->redirectToRoute('details', array(
  515.                 'id' => $request->get('id'),
  516.             ));
  517.         }
  518.         if ($request->get('phone') == null || $request->get('phone') === '') {
  519.             if ($request->get('email') == null || $request->get('email') === '') {
  520.                 return $this->redirectToRoute('details', array(
  521.                     'id' => $request->get('id'),
  522.                 ));
  523.             }
  524.         }
  525.         $em $this->getDoctrine()->getManager();
  526.         $repo $em->getRepository(Customer::class);
  527.         $checkCustomer $this->checkCustomer($request);
  528.         if ($checkCustomer != null) {
  529.             if ("klient_jest_juz_w_bazie" === $checkCustomer) {
  530.                 /** @var  $duplicate Customer */
  531.                 $duplicate $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
  532.                 if (intval($duplicate->getId()) != intval($request->get('id'))) {
  533.                     return $this->redirect("/details?id=" $request->get('id') . "&message=" $checkCustomer);
  534.                 }
  535.             }
  536. //
  537. //            return $this->redirectToRoute('details', array(
  538. //                'id' => $request->get('id'),
  539. //            ));
  540.         }
  541.         /** @var  $customer Customer */
  542.         $customer $repo->findOneById($request->get('id'));
  543.         $customer->setPhone($request->get('phone'));
  544.         if (empty($request->get('contractdate'))) {
  545.             $customer->setContractDate(null);
  546.         } else {
  547.             $customer->setContractDate(DateTime::createFromFormat('Y-m-d'$request->get('contractdate')));
  548.         }
  549.         if (empty($request->get('reservedto'))) {
  550.             $customer->setReservedTo(null);
  551.         } else {
  552.             $customer->setReservedTo(DateTime::createFromFormat('Y-m-d'$request->get('reservedto')));
  553.         }
  554.         $customer->setEmail($request->get('email'));
  555.         $customer->setLink($request->get('link'));
  556.         $customer->setFirstname($request->get('firstname'));
  557.         $customer->setLastname($request->get('lastname'));
  558.         $customer->setCustomerType($request->get('customertype'));
  559.         $customer->setStatus($request->get('status'));
  560.         $em->persist($customer);
  561.         $em->flush();
  562.         return $this->redirectToRoute('details', array(
  563.             'id' => $customer->getId(),
  564.         ));
  565.     }
  566.     /**
  567.      * @Route("/addComment", name="addComment")
  568.      */
  569.     public function addComment(Request $request): Response
  570.     {
  571.         if (!$this->get('session')->get('User')) {
  572.             return $this->redirectToRoute('app_crm');
  573.         }
  574.         $em $this->getDoctrine()->getManager();
  575.         $repo $em->getRepository(Customer::class);
  576.         $customer $repo->findOneById($request->get('id'));
  577.         $comment = new CustomerComment();
  578.         $comment->setCustomer($customer);
  579.         $comment->setDate(DateTime::createFromFormat('Y-m-d'$request->get('actiondate')));
  580.         $comment->setCommentAddDate(new \DateTime());
  581.         $comment->setComment($request->get('customerComment'));
  582.         $em->persist($comment);
  583.         $em->flush();
  584.         return $this->redirectToRoute('details', array(
  585.             'id' => $customer->getId(),
  586.         ));
  587.     }
  588.     private function checkCustomer(Request $request)
  589.     {
  590.         if ($request->get('customertype') == null || $request->get('customertype') === '') {
  591.             return "bledny_typ_klienta";
  592.         }
  593.         if ($request->get('phone') == null || $request->get('phone') === '') {
  594.             if ($request->get('email') == null || $request->get('email') === '') {
  595.                 return "nie_podano_telefonu_ani_maila";
  596.             }
  597.         }
  598.         $em $this->getDoctrine()->getManager();
  599.         $repo $em->getRepository(Customer::class);
  600.         $duplicate $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
  601.         if ($duplicate) {
  602.             return "klient_jest_juz_w_bazie";
  603.         }
  604.         return null;
  605.     }
  606.     /**
  607.      * @Route("/newCustomer", name="newCustomer")
  608.      * @param Request $request
  609.      * @param \Swift_Mailer $mailer
  610.      * @return Response
  611.      */
  612.     public function newCustomer(Request $request\Swift_Mailer $mailer): Response
  613.     {
  614.         if (!$this->get('session')->get('User')) {
  615.             return $this->redirectToRoute('app_crm');
  616.         }
  617.         $em $this->getDoctrine()->getManager();
  618.         $checkCustomer $this->checkCustomer($request);
  619.         $customer = new Customer();
  620.         $message null;
  621.         /** @var  $user Agent */
  622.         $user $this->get('session')->get('User');
  623.         if ($checkCustomer != null) {
  624.             if ("klient_jest_juz_w_bazie" === $checkCustomer) {
  625.                 $repo $em->getRepository(Customer::class);
  626.                 /** @var  $duplicate Customer */
  627.                 $duplicate $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
  628.                 $now = new DateTime('now');
  629.                 if ($duplicate->getReservedTo() && $duplicate->getAgent()) {
  630.                     if ($duplicate->getReservedTo()->getTimestamp() > $now->getTimestamp()
  631.                         && $duplicate->getAgent()->getId() !== $user->getId()) {
  632.                         return $this->redirect("/newContact?message=" $checkCustomer "_zarezerwowany_przez_"
  633.                             $duplicate->getAgent()->getFirstname() . '_' $duplicate->getAgent()->getLastname());
  634.                     } else {
  635.                         $customer $duplicate;
  636.                         $message $checkCustomer "_i_go_przejmujesz_od_"
  637.                             $duplicate->getAgent()->getFirstname() . '_' $duplicate->getAgent()->getLastname();
  638.                         $message2 = (new \Swift_Message('PrzejÄ™ty klient '))
  639.                             ->setFrom('crm@wronieruchomosci.pl')
  640.                             ->setTo($duplicate->getAgent()->getEmail())
  641.                             ->setBody('Użytkownik ' $user->getFirstname() . ' ' $user->getLastname() . ' ' $user->getEmail() . " przejÄ…Å‚ Twojego klienta " $duplicate->getFirstname() . ' ' $duplicate->getLastname() . ' ' $duplicate->getEmail() . ' ' $duplicate->getPhone());
  642.                         $mailer->send($message2);
  643.                     }
  644.                 } else {
  645.                     $customer $duplicate;
  646.                     $message $checkCustomer "_choc_nie_byl_do_nikogo_przypisany";
  647.                 }
  648.             } else {
  649.                 return $this->redirect("/newContact?message=" $checkCustomer);
  650.             }
  651.         }
  652.         if ($request->get('phone')) {
  653.             $customer->setPhone($request->get('phone'));
  654.         }
  655.         if (!$customer->getAddDate()) {
  656.             $customer->setAddDate(new DateTime('now'));
  657.         }
  658.         if ($request->get('email')) {
  659.             $customer->setEmail($request->get('email'));
  660.         }
  661.         if ($request->get('link')) {
  662.             $customer->setLink($request->get('link'));
  663.         }
  664.         if ($request->get('firstname')) {
  665.             $customer->setFirstname($request->get('firstname'));
  666.         }
  667.         if ($request->get('lastname')) {
  668.             $customer->setLastname($request->get('lastname'));
  669.         }
  670.         $customer->setCustomerType($request->get('customertype'));
  671.         $customer->setStatus('nowy');
  672.         $em->persist($customer);
  673.         $em->flush();
  674.         if ($request->get('customerComment') != null && !empty($request->get('customerComment'))) {
  675.             $comment = new CustomerComment();
  676.             $comment->setCustomer($customer);
  677.             $comment->setDate(new \DateTime());
  678.             $comment->setCommentAddDate(new \DateTime());
  679.             $comment->setComment("" $user->getFirstname() . ' ' $user->getLastname() . "  Dodano klienta: " $request->get('customerComment'));
  680.             $em->persist($comment);
  681.             $em->flush();
  682.         } else {
  683.             $comment = new CustomerComment();
  684.             $comment->setCustomer($customer);
  685.             $comment->setDate(new \DateTime());
  686.             $comment->setCommentAddDate(new \DateTime());
  687.             $comment->setComment("" $user->getFirstname() . ' ' $user->getLastname() . "  Dodano klienta");
  688.             $em->persist($comment);
  689.             $em->flush();
  690.         }
  691. //    $redirection = "/details?id=" . $customer->getId();
  692.         return $this->reserveCustomer($customer->getId(), "/"$mailer$message);
  693. //        return $this->redirectToRoute('app_crm');
  694.     }
  695.     /**
  696.      * @param Agent $agent
  697.      * @return string
  698.      */
  699.     private function getImagePicture(?Agent $agent): string
  700.     {
  701.         $imagePicture $agent && $agent->getImageUrl() ? $agent->getImageUrl() : '';
  702.         return $imagePicture;
  703.     }
  704.     /**
  705.      * @param $existing
  706.      * @param $singleMessage
  707.      * @param Agent $agent
  708.      * @param $customers
  709.      * @param ObjectManager $em
  710.      * @param string $mailInfo
  711.      * @return integer
  712.      */
  713.     private function saveSingleEmail($existing$singleMessageAgent $agent$customersObjectManager $em): string
  714.     {
  715.         if (!$this->isExistingContaining($existing$singleMessage->header->message_id$singleMessage->header->uid)) {
  716.             $mailEntity = new Mail();
  717.             $mailEntity->setSubject($singleMessage->header->subject);//
  718.             $mailEntity->setSender($singleMessage->header->from);//
  719.             if (property_exists($singleMessage->header'to')) {
  720.                 $mailEntity->setReceiver($singleMessage->header->to);//
  721.             } else {
  722.                 $mailEntity->setReceiver($agent->getEmail());
  723.             }
  724.             $mailEntity->setReceiveDate($singleMessage->header->date);//
  725.             $mailEntity->setMessageId($singleMessage->header->message_id);//
  726.             $mailEntity->setMessageUid($singleMessage->header->uid);//.)
  727.             $mailEntity->setMessageText($singleMessage->message->text);
  728.             if ($mailEntity->getMessageText() == null) {
  729.                 $mailEntity->setMessageText("");
  730.             }
  731.             //$mailEntity->setFullMail(serialize($singleMessage));
  732.             //$mailEntity->setMessageText($singleMail->attachments);
  733.             $mailEntity->setAgent($agent);
  734.             /** @var  $singleCustomer Customer */
  735.             foreach ($customers as $singleCustomer) {
  736.                 if ($singleCustomer->getEmail() && $singleCustomer->getEmail() !== ''
  737.                     && str_contains($mailEntity->getSender(), $singleCustomer->getEmail())) {
  738.                     $mailEntity->setCustomer($singleCustomer);
  739.                     break;
  740.                 }
  741.             }
  742.             if ($mailEntity->getCustomer() == null) {
  743.                 $senderTLC strtolower($mailEntity->getSender());
  744.                 /** @var  $singleCustomer Customer */
  745.                 foreach ($customers as $singleCustomer) {
  746.                     $firstnameTLC strtolower($singleCustomer->getFirstname());
  747.                     $lastnameTLC strtolower($singleCustomer->getLastname());
  748.                     if ($firstnameTLC != null
  749.                         && $firstnameTLC !== ''
  750.                         && str_contains($senderTLC$firstnameTLC)
  751.                         && $lastnameTLC != null
  752.                         && $lastnameTLC !== ''
  753.                         && str_contains($senderTLC$lastnameTLC)) {
  754.                         $mailEntity->setCustomer($singleCustomer);
  755.                         break;
  756.                     }
  757.                 }
  758.             }
  759.             $em->persist($mailEntity);
  760.             if ($singleMessage->attachments) {
  761.                 foreach ($singleMessage->attachments as $attachment) {
  762.                     $name $attachment->name;
  763.                     $contents base64_decode($attachment->body);
  764.                     $mailAttachment = new MailAttachment();
  765.                     $mailAttachment->setName($attachment->name);
  766.                     $mailAttachment->setBody('');
  767.                     $mailAttachment->setMail($mailEntity);
  768.                     $em->persist($mailAttachment);
  769.                     $em->flush();
  770.                     if (!file_exists('attachment')) {
  771.                         mkdir("attachment"0777true);
  772.                     }
  773.                     if (!file_exists("attachment/" $mailAttachment->getId())) {
  774.                         mkdir("attachment/" $mailAttachment->getId(), 0777true);
  775.                     }
  776.                     if ($name == null || str_starts_with($name"=?")) {
  777.                         $name "" $mailAttachment->getId();
  778.                     }
  779.                     file_put_contents("attachment/" $mailAttachment->getId() . "/" $name$contents);
  780.                     $mailAttachment->setBody("/attachment/" $mailAttachment->getId() . "/" $name);
  781.                     $em->persist($mailAttachment);
  782.                     $em->flush();
  783.                 }
  784.             }
  785.             return 1;
  786.         }
  787.         return 0;
  788.     }
  789.     /**
  790.      * @param $myContacts
  791.      * @param ObjectManager $em
  792.      * @return void
  793.      */
  794.     public function repairContactPhones($myContactsObjectManager $em): void
  795.     {
  796.         /** @var  $contact Customer */
  797.         foreach ($myContacts as $contact) {
  798.             if (strpos($contact->getPhone(), ' ') !== false) {
  799.                 $contact->setPhone(str_replace(' '''$contact->getPhone()));
  800.                 $em->persist($contact);
  801.                 $em->flush();
  802.             }
  803.         }
  804.     }
  805. }