src/Controller/CrmController.php line 46

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.         return $this->render('crm/contacts.html.twig', [
  301.             'controller_name' => 'CrmController',
  302.             'myCustomers' => $all,
  303.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  304.             'xpages' => $xpages,
  305.             'logged' => $this->get('session')->get('User')
  306.         ]);
  307.     }
  308.     /**
  309.      * @Route("/myContacts", name="myContacts")
  310.      */
  311.     public function myContacts(Request $request): Response
  312.     {
  313.         if (!$this->get('session')->get('User')) {
  314.             return $this->redirectToRoute('app_crm');
  315.         }
  316.         $em $this->getDoctrine()->getManager();
  317.         $repo $em->getRepository(Customer::class);
  318.         if ($request->get('page')) {
  319.             $page $request->get('page');
  320.         } else {
  321.             $page 1;
  322.         }
  323.         $myContacts $repo->findAllDesc("/myContacts"$page 1$this->get('session')->get('User'));
  324.         $xpages $repo->findAllXpages("/myContacts"$page$this->get('session')->get('User'));
  325.         return $this->render('crm/contacts.html.twig', [
  326.             'controller_name' => 'CrmController',
  327.             'myCustomers' => $myContacts,
  328.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  329.             'xpages' => $xpages,
  330.             'logged' => $this->get('session')->get('User')
  331.         ]);
  332.     }
  333.     /**
  334.      * @Route("/searchContacts", name="searchContacts")
  335.      */
  336.     public function searchContacts(Request $request): Response
  337.     {
  338.         if (!$this->get('session')->get('User')) {
  339.             return $this->redirectToRoute('app_crm');
  340.         }
  341.         $em $this->getDoctrine()->getManager();
  342.         $repo $em->getRepository(Customer::class);
  343.         $myContacts $repo->search($request->get('text'), "/searchContacts",
  344.             $this->isAdminOrManager() ? null $this->get('session')->get('User'));
  345.         $xpages = array();
  346.         return $this->render('crm/contacts.html.twig', [
  347.             'controller_name' => 'CrmController',
  348.             'myCustomers' => $myContacts,
  349.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  350.             'xpages' => $xpages,
  351.             'logged' => $this->get('session')->get('User')
  352.         ]);
  353.     }
  354.     /**
  355.      * @Route("/newContact", name="newContact")
  356.      */
  357.     public function newContact(): Response
  358.     {
  359.         if (!$this->get('session')->get('User')) {
  360.             return $this->redirectToRoute('app_crm');
  361.         }
  362.         $em $this->getDoctrine()->getManager();
  363. //        $repo = $em->getRepository(Customer::class);
  364.         return $this->render('crm/newContact.html.twig', [
  365.             'controller_name' => 'CrmController',
  366.             'logged' => $this->get('session')->get('User'),
  367.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  368.         ]);
  369.     }
  370.     /**
  371.      * @Route("/reserve", name="reserve")
  372.      */
  373.     public function reserve(Request $request\Swift_Mailer $mailer): Response
  374.     {
  375.         return $this->reserveCustomer($request->get('id'), $request->get('action'), $mailer);
  376.     }
  377.     public function reserveCustomer($id$action\Swift_Mailer $mailer$message null): Response
  378.     {
  379.         if (!$this->get('session')->get('User')) {
  380.             return $this->redirectToRoute('app_crm');
  381.         }
  382.         $em $this->getDoctrine()->getManager();
  383.         $repo $em->getRepository(Customer::class);
  384.         $repo2 $em->getRepository(Agent::class);
  385.         /** @var  $customer Customer */
  386.         $customer $repo->findOneById($id);
  387.         $now = new DateTime('now');
  388.         $user $this->get('session')->get('User');
  389.         if ($customer->getReservedTo() != null && $now $customer->getReservedTo()) {
  390.             if ($customer->getAgent()->getId() != $this->get('session')->get('User')->getId()) {
  391.                 if ($customer->getReservedTo()->getTimestamp() <= $now->getTimestamp()) {
  392.                     $message "przejmujesz_klienta_od_"
  393.                         $customer->getAgent()->getFirstname() . '_' $customer->getAgent()->getLastname();
  394.                     $emailToSend = (new \Swift_Message('Przejęty klient '))
  395.                         ->setFrom('crm@wronieruchomosci.pl')
  396.                         ->setTo($customer->getAgent()->getEmail())
  397.                         ->setBody('Użytkownik ' $user->getFirstname() . ' ' $user->getLastname() . ' ' $user->getEmail() . " przejął Twojego klienta "
  398.                             $customer->getFirstname() . ' ' $customer->getLastname() . ' ' $customer->getEmail() . ' ' $customer->getPhone());
  399.                     $mailer->send($emailToSend);
  400.                     $customer->setAddDate($now);
  401.                     $customer->setAgent($this->get('session')->get('User'));
  402.                 } else {
  403.                     return $this->redirect($action "?reserved_by=" $customer->getAgent()->getFirstname() . '_' $customer->getAgent()->getLastname());
  404.                 }
  405.             }
  406.         }
  407.         $customer->setAddDate($now);
  408.         $customer->setAgent($repo2->findOneById($this->get('session')->get('User')->getId()));
  409.         $date = new DateTime('now');
  410.         $em $this->getDoctrine()->getManager();
  411.         $repoParameter $em->getRepository(Parameter::class);
  412.         /** @var Parameter $reservationHours */
  413.         $reservationHours $repoParameter->findOneByParam('reservationHours');
  414.         if (!$reservationHours) {
  415.             $reservationHours = new Parameter();
  416.             $reservationHours->setParam("reservationHours");
  417.             $reservationHours->setVal("80");
  418.             $em->persist($reservationHours);
  419.             $em->flush();
  420.         }
  421.         $date->add(new DateInterval('PT' $reservationHours->getVal() . 'H'));
  422.         $customer->setReservedTo($date);
  423.         $em->persist($customer);
  424.         $em->flush();
  425.         if ($message) {
  426.             $redirection "/details?id=" $customer->getId() . "&message=$message";
  427.         } else {
  428.             $redirection $action "?reserved_now=" $customer->getReservedToFormatted();
  429.         }
  430.         return $this->redirect($redirection);
  431.     }
  432.     /**
  433.      * @Route("/call", name="call")
  434.      */
  435.     public function call(Request $request): Response
  436.     {
  437.         $em $this->getDoctrine()->getManager();
  438.         $repo $em->getRepository(Customer::class);
  439.         /** @var  $customer Customer */
  440.         $customer $repo->findOneById($request->get('id'));
  441.         $customer->setStatus('do obdzwonki');
  442.         $em->persist($customer);
  443.         $em->flush();
  444.         return $this->redirect($request->get('action'));
  445.     }
  446.     /**
  447.      * @Route("/callMade", name="callMade")
  448.      */
  449.     public function callMade(Request $request): Response
  450.     {
  451.         if (!$this->get('session')->get('User')) {
  452.             return $this->redirectToRoute('app_crm');
  453.         }
  454.         $em $this->getDoctrine()->getManager();
  455.         $repo $em->getRepository(Customer::class);
  456.         /** @var  $customer Customer */
  457.         $customer $repo->findOneById($request->get('id'));
  458.         $customer->setStatus('obdzwoniono');
  459.         $em->persist($customer);
  460.         $em->flush();
  461.         return $this->redirectToRoute('app_crm');
  462.     }
  463.     /**
  464.      * @Route("/details", name="details")
  465.      */
  466.     public function details(Request $request): Response
  467.     {
  468.         if (!$this->get('session')->get('User')) {
  469.             return $this->redirectToRoute('app_crm');
  470.         }
  471.         /** @var  $agent Agent */
  472.         $agent $this->get('session')->get('User');
  473.         $em $this->getDoctrine()->getManager();
  474.         $repo $em->getRepository(Customer::class);
  475.         $repoComments $em->getRepository(CustomerComment::class);
  476.         /** @var  $customer Customer */
  477.         $customer $repo->findOneById($request->get('id'));
  478.         $repoMail $em->getRepository(Mail::class);
  479.         if (!$this->isAdminOrManager()) {
  480.             if ($customer->getAgent() && $agent->getId() != $customer->getAgent()->getId()) {
  481.                 $customerAgentMails $repoMail->findBy(array('customer' => $customer->getId(), 'agent' => $agent->getId()));
  482.                 if (empty($customerAgentMails)) {
  483.                     return $this->redirectToRoute('app_crm');
  484.                 }
  485.             }
  486.         }
  487.         $customerMails $repoMail->findByCustomer($request->get('id'));
  488.         $customerComments $repoComments->findByCustomer($request->get('id'));
  489.         return $this->render('crm/customerDetails.html.twig', [
  490.             'controller_name' => 'CrmController',
  491.             'logged' => $this->get('session')->get('User'),
  492.             'customerComments' => $customerComments,
  493.             'image_picture' => $this->getImagePicture($this->get('session')->get('User')),
  494.             'isAdminOrManager' => $this->isAdminOrManager(),
  495.             'currentDate' => (new DateTime('now'))->format('Y-m-d'),
  496.             'customer' => $customer,
  497.             'emails' => $customerMails,
  498.             'detailsView' => true
  499.         ]);
  500.     }
  501.     /**
  502.      * @Route("/updateDetails", name="updateDetails")
  503.      */
  504.     public function updateDetails(Request $request): Response
  505.     {
  506.         if (!$this->get('session')->get('User')) {
  507.             return $this->redirectToRoute('app_crm');
  508.         }
  509.         if ($request->get('customertype') == null || $request->get('customertype') === '') {
  510.             return $this->redirectToRoute('details', array(
  511.                 'id' => $request->get('id'),
  512.             ));
  513.         }
  514.         if ($request->get('phone') == null || $request->get('phone') === '') {
  515.             if ($request->get('email') == null || $request->get('email') === '') {
  516.                 return $this->redirectToRoute('details', array(
  517.                     'id' => $request->get('id'),
  518.                 ));
  519.             }
  520.         }
  521.         $em $this->getDoctrine()->getManager();
  522.         $repo $em->getRepository(Customer::class);
  523.         $checkCustomer $this->checkCustomer($request);
  524.         if ($checkCustomer != null) {
  525.             if ("klient_jest_juz_w_bazie" === $checkCustomer) {
  526.                 /** @var  $duplicate Customer */
  527.                 $duplicate $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
  528.                 if (intval($duplicate->getId()) != intval($request->get('id'))) {
  529.                     return $this->redirect("/details?id=" $request->get('id') . "&message=" $checkCustomer);
  530.                 }
  531.             }
  532. //
  533. //            return $this->redirectToRoute('details', array(
  534. //                'id' => $request->get('id'),
  535. //            ));
  536.         }
  537.         /** @var  $customer Customer */
  538.         $customer $repo->findOneById($request->get('id'));
  539.         $customer->setPhone($request->get('phone'));
  540.         if (empty($request->get('contractdate'))) {
  541.             $customer->setContractDate(null);
  542.         } else {
  543.             $customer->setContractDate(DateTime::createFromFormat('Y-m-d'$request->get('contractdate')));
  544.         }
  545.         if (empty($request->get('reservedto'))) {
  546.             $customer->setReservedTo(null);
  547.         } else {
  548.             $customer->setReservedTo(DateTime::createFromFormat('Y-m-d'$request->get('reservedto')));
  549.         }
  550.         $customer->setEmail($request->get('email'));
  551.         $customer->setLink($request->get('link'));
  552.         $customer->setFirstname($request->get('firstname'));
  553.         $customer->setLastname($request->get('lastname'));
  554.         $customer->setCustomerType($request->get('customertype'));
  555.         $customer->setStatus($request->get('status'));
  556.         $em->persist($customer);
  557.         $em->flush();
  558.         return $this->redirectToRoute('details', array(
  559.             'id' => $customer->getId(),
  560.         ));
  561.     }
  562.     /**
  563.      * @Route("/addComment", name="addComment")
  564.      */
  565.     public function addComment(Request $request): Response
  566.     {
  567.         if (!$this->get('session')->get('User')) {
  568.             return $this->redirectToRoute('app_crm');
  569.         }
  570.         $em $this->getDoctrine()->getManager();
  571.         $repo $em->getRepository(Customer::class);
  572.         $customer $repo->findOneById($request->get('id'));
  573.         $comment = new CustomerComment();
  574.         $comment->setCustomer($customer);
  575.         $comment->setDate(DateTime::createFromFormat('Y-m-d'$request->get('actiondate')));
  576.         $comment->setCommentAddDate(new \DateTime());
  577.         $comment->setComment($request->get('customerComment'));
  578.         $em->persist($comment);
  579.         $em->flush();
  580.         return $this->redirectToRoute('details', array(
  581.             'id' => $customer->getId(),
  582.         ));
  583.     }
  584.     private function checkCustomer(Request $request)
  585.     {
  586.         if ($request->get('customertype') == null || $request->get('customertype') === '') {
  587.             return "bledny_typ_klienta";
  588.         }
  589.         if ($request->get('phone') == null || $request->get('phone') === '') {
  590.             if ($request->get('email') == null || $request->get('email') === '') {
  591.                 return "nie_podano_telefonu_ani_maila";
  592.             }
  593.         }
  594.         $em $this->getDoctrine()->getManager();
  595.         $repo $em->getRepository(Customer::class);
  596.         $duplicate $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
  597.         if ($duplicate) {
  598.             return "klient_jest_juz_w_bazie";
  599.         }
  600.         return null;
  601.     }
  602.     /**
  603.      * @Route("/newCustomer", name="newCustomer")
  604.      * @param Request $request
  605.      * @param \Swift_Mailer $mailer
  606.      * @return Response
  607.      */
  608.     public function newCustomer(Request $request\Swift_Mailer $mailer): Response
  609.     {
  610.         if (!$this->get('session')->get('User')) {
  611.             return $this->redirectToRoute('app_crm');
  612.         }
  613.         $em $this->getDoctrine()->getManager();
  614.         $checkCustomer $this->checkCustomer($request);
  615.         $customer = new Customer();
  616.         $message null;
  617.         /** @var  $user Agent */
  618.         $user $this->get('session')->get('User');
  619.         if ($checkCustomer != null) {
  620.             if ("klient_jest_juz_w_bazie" === $checkCustomer) {
  621.                 $repo $em->getRepository(Customer::class);
  622.                 /** @var  $duplicate Customer */
  623.                 $duplicate $repo->findDuplicate($request->get('email'), $request->get('phone'), $request->get('link'));
  624.                 $now = new DateTime('now');
  625.                 if ($duplicate->getReservedTo() && $duplicate->getAgent()) {
  626.                     if ($duplicate->getReservedTo()->getTimestamp() > $now->getTimestamp()
  627.                         && $duplicate->getAgent()->getId() !== $user->getId()) {
  628.                         return $this->redirect("/newContact?message=" $checkCustomer "_zarezerwowany_przez_"
  629.                             $duplicate->getAgent()->getFirstname() . '_' $duplicate->getAgent()->getLastname());
  630.                     } else {
  631.                         $customer $duplicate;
  632.                         $message $checkCustomer "_i_go_przejmujesz_od_"
  633.                             $duplicate->getAgent()->getFirstname() . '_' $duplicate->getAgent()->getLastname();
  634.                         $message2 = (new \Swift_Message('Przejęty klient '))
  635.                             ->setFrom('crm@wronieruchomosci.pl')
  636.                             ->setTo($duplicate->getAgent()->getEmail())
  637.                             ->setBody('Użytkownik ' $user->getFirstname() . ' ' $user->getLastname() . ' ' $user->getEmail() . " przejął Twojego klienta " $duplicate->getFirstname() . ' ' $duplicate->getLastname() . ' ' $duplicate->getEmail() . ' ' $duplicate->getPhone());
  638.                         $mailer->send($message2);
  639.                     }
  640.                 } else {
  641.                     $customer $duplicate;
  642.                     $message $checkCustomer "_choc_nie_byl_do_nikogo_przypisany";
  643.                 }
  644.             } else {
  645.                 return $this->redirect("/newContact?message=" $checkCustomer);
  646.             }
  647.         }
  648.         if ($request->get('phone')) {
  649.             $customer->setPhone($request->get('phone'));
  650.         }
  651.         if (!$customer->getAddDate()) {
  652.             $customer->setAddDate(new DateTime('now'));
  653.         }
  654.         if ($request->get('email')) {
  655.             $customer->setEmail($request->get('email'));
  656.         }
  657.         if ($request->get('link')) {
  658.             $customer->setLink($request->get('link'));
  659.         }
  660.         if ($request->get('firstname')) {
  661.             $customer->setFirstname($request->get('firstname'));
  662.         }
  663.         if ($request->get('lastname')) {
  664.             $customer->setLastname($request->get('lastname'));
  665.         }
  666.         $customer->setCustomerType($request->get('customertype'));
  667.         $customer->setStatus('nowy');
  668.         $em->persist($customer);
  669.         $em->flush();
  670.         if ($request->get('customerComment') != null && !empty($request->get('customerComment'))) {
  671.             $comment = new CustomerComment();
  672.             $comment->setCustomer($customer);
  673.             $comment->setDate(new \DateTime());
  674.             $comment->setCommentAddDate(new \DateTime());
  675.             $comment->setComment("" $user->getFirstname() . ' ' $user->getLastname() . "  Dodano klienta: " $request->get('customerComment'));
  676.             $em->persist($comment);
  677.             $em->flush();
  678.         } else {
  679.             $comment = new CustomerComment();
  680.             $comment->setCustomer($customer);
  681.             $comment->setDate(new \DateTime());
  682.             $comment->setCommentAddDate(new \DateTime());
  683.             $comment->setComment("" $user->getFirstname() . ' ' $user->getLastname() . "  Dodano klienta");
  684.             $em->persist($comment);
  685.             $em->flush();
  686.         }
  687. //    $redirection = "/details?id=" . $customer->getId();
  688.         return $this->reserveCustomer($customer->getId(), "/"$mailer$message);
  689. //        return $this->redirectToRoute('app_crm');
  690.     }
  691.     /**
  692.      * @param Agent $agent
  693.      * @return string
  694.      */
  695.     private function getImagePicture(?Agent $agent): string
  696.     {
  697.         $imagePicture $agent && $agent->getImageUrl() ? $agent->getImageUrl() : '';
  698.         return $imagePicture;
  699.     }
  700.     /**
  701.      * @param $existing
  702.      * @param $singleMessage
  703.      * @param Agent $agent
  704.      * @param $customers
  705.      * @param ObjectManager $em
  706.      * @param string $mailInfo
  707.      * @return integer
  708.      */
  709.     private function saveSingleEmail($existing$singleMessageAgent $agent$customersObjectManager $em): string
  710.     {
  711.         if (!$this->isExistingContaining($existing$singleMessage->header->message_id$singleMessage->header->uid)) {
  712.             $mailEntity = new Mail();
  713.             $mailEntity->setSubject($singleMessage->header->subject);//
  714.             $mailEntity->setSender($singleMessage->header->from);//
  715.             if (property_exists($singleMessage->header'to')) {
  716.                 $mailEntity->setReceiver($singleMessage->header->to);//
  717.             } else {
  718.                 $mailEntity->setReceiver($agent->getEmail());
  719.             }
  720.             $mailEntity->setReceiveDate($singleMessage->header->date);//
  721.             $mailEntity->setMessageId($singleMessage->header->message_id);//
  722.             $mailEntity->setMessageUid($singleMessage->header->uid);//.)
  723.             $mailEntity->setMessageText($singleMessage->message->text);
  724.             if ($mailEntity->getMessageText() == null) {
  725.                 $mailEntity->setMessageText("");
  726.             }
  727.             //$mailEntity->setFullMail(serialize($singleMessage));
  728.             //$mailEntity->setMessageText($singleMail->attachments);
  729.             $mailEntity->setAgent($agent);
  730.             /** @var  $singleCustomer Customer */
  731.             foreach ($customers as $singleCustomer) {
  732.                 if ($singleCustomer->getEmail() && $singleCustomer->getEmail() !== ''
  733.                     && str_contains($mailEntity->getSender(), $singleCustomer->getEmail())) {
  734.                     $mailEntity->setCustomer($singleCustomer);
  735.                     break;
  736.                 }
  737.             }
  738.             if ($mailEntity->getCustomer() == null) {
  739.                 $senderTLC strtolower($mailEntity->getSender());
  740.                 /** @var  $singleCustomer Customer */
  741.                 foreach ($customers as $singleCustomer) {
  742.                     $firstnameTLC strtolower($singleCustomer->getFirstname());
  743.                     $lastnameTLC strtolower($singleCustomer->getLastname());
  744.                     if ($firstnameTLC != null
  745.                         && $firstnameTLC !== ''
  746.                         && str_contains($senderTLC$firstnameTLC)
  747.                         && $lastnameTLC != null
  748.                         && $lastnameTLC !== ''
  749.                         && str_contains($senderTLC$lastnameTLC)) {
  750.                         $mailEntity->setCustomer($singleCustomer);
  751.                         break;
  752.                     }
  753.                 }
  754.             }
  755.             $em->persist($mailEntity);
  756.             if ($singleMessage->attachments) {
  757.                 foreach ($singleMessage->attachments as $attachment) {
  758.                     $name $attachment->name;
  759.                     $contents base64_decode($attachment->body);
  760.                     $mailAttachment = new MailAttachment();
  761.                     $mailAttachment->setName($attachment->name);
  762.                     $mailAttachment->setBody('');
  763.                     $mailAttachment->setMail($mailEntity);
  764.                     $em->persist($mailAttachment);
  765.                     $em->flush();
  766.                     if (!file_exists('attachment')) {
  767.                         mkdir("attachment"0777true);
  768.                     }
  769.                     if (!file_exists("attachment/" $mailAttachment->getId())) {
  770.                         mkdir("attachment/" $mailAttachment->getId(), 0777true);
  771.                     }
  772.                     if ($name == null || str_starts_with($name"=?")) {
  773.                         $name "" $mailAttachment->getId();
  774.                     }
  775.                     file_put_contents("attachment/" $mailAttachment->getId() . "/" $name$contents);
  776.                     $mailAttachment->setBody("/attachment/" $mailAttachment->getId() . "/" $name);
  777.                     $em->persist($mailAttachment);
  778.                     $em->flush();
  779.                 }
  780.             }
  781.             return 1;
  782.         }
  783.         return 0;
  784.     }
  785. }