vendor/uvdesk/core-framework/Repository/TicketRepository.php line 134

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\CoreFrameworkBundle\Repository;
  3. use Doctrine\ORM\Query;
  4. use Doctrine\ORM\QueryBuilder;
  5. use Doctrine\Common\Collections\Criteria;
  6. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  7. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Ticket;
  8. use Webkul\UVDesk\CoreFrameworkBundle\Entity\TicketType;
  9. use Webkul\UVDesk\CoreFrameworkBundle\Entity\Tag;
  10. use Symfony\Component\HttpFoundation\ParameterBag;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. /**
  13.  * TicketRepository
  14.  *
  15.  * This class was generated by the Doctrine ORM. Add your own custom
  16.  * repository methods below.
  17.  */
  18. class TicketRepository extends \Doctrine\ORM\EntityRepository
  19. {
  20.     const LIMIT 15;
  21.     const TICKET_GLOBAL_ACCESS 1;
  22.     const TICKET_GROUP_ACCESS 2;
  23.     const TICKET_TEAM_ACCESS  3;
  24.     const DEFAULT_PAGINATION_LIMIT 15;
  25.     private $container;
  26.     private $requestStack;
  27.     private $safeFields = ['page''limit''sort''order''direction'];
  28.     public function getTicketLabelCollection(Ticket $ticketUser $user)
  29.     {
  30.         // $queryBuilder = $this->getEntityManager()->createQueryBuilder()
  31.         //     ->select("DISTINCT supportLabel.id, supportLabel.name, supportLabel.colorCode as color")
  32.         //     ->from(Ticket::class, 'ticket')
  33.         //     ->leftJoin('ticket.supportLabels', 'supportLabel')
  34.         //     // ->leftJoin('supportLabel.user', 'user')
  35.         //     ->where('ticket.id = :ticketId')->setParameter('ticketId', $ticket->getId())
  36.         //     ->andWhere('supportLabel.user = :user')->setParameter('user', $user);
  37.         return [];
  38.     }
  39.     public function getAllTickets(ParameterBag $obj null$container$actAsUser null)
  40.     {
  41.         $currentUser $actAsUser ? : $container->get('user.service')->getCurrentUser();
  42.         $json = array();
  43.         $qb $this->getEntityManager()->createQueryBuilder();
  44.         $qb->select('DISTINCT t,gr,pr,tp,s,a.id as agentId,c.id as customerId')->from($this->getEntityName(), 't');
  45.         $qb->leftJoin('t.agent''a');
  46.         $qb->leftJoin('a.userInstance''ad');
  47.         $qb->leftJoin('t.status''s');
  48.         $qb->leftJoin('t.customer''c');
  49.         $qb->leftJoin('t.supportGroup''gr');
  50.         $qb->leftJoin('t.priority''pr');
  51.         $qb->leftJoin('t.type''tp');
  52.         $qb->addSelect("CONCAT(a.firstName,' ', a.lastName) AS name");
  53.         $qb->andwhere("t.agent IS NULL OR ad.supportRole != 4");
  54.         $data $obj $obj->all() : [];
  55.         $data array_reverse($data);
  56.         foreach ($data as $key => $value) {
  57.             if(!in_array($key,$this->safeFields)) {
  58.                 if(isset($data['search']) && $key == 'search') {
  59.                     $qb->andwhere("t.subject LIKE :subject OR a.email LIKE :agentName OR t.id LIKE :ticketId");
  60.                     $qb->setParameter('subject''%'.urldecode($value).'%');
  61.                     $qb->setParameter('agentName''%'.urldecode($value).'%');
  62.                     $qb->setParameter('ticketId''%'.urldecode($value).'%');
  63.                 } elseif($key == 'status') {
  64.                     $qb->andwhere('t.status = '.intval($value));
  65.                 }
  66.             }
  67.         }
  68.         $qb->andwhere('t.isTrashed != 1');
  69.         if(!isset($data['sort'])) {
  70.             $qb->orderBy('t.id',Criteria::DESC);
  71.         }
  72.         if(isset($data['sort']) && $data['sort'] == "t.updatedAt") {
  73.             $qb->orderBy('t.updatedAt',Criteria::DESC);
  74.         }
  75.         $paginator $container->get('knp_paginator');
  76.         $newQb = clone $qb;
  77.         $newQb->select('COUNT(DISTINCT t.id)');
  78.         $results $paginator->paginate(
  79.             $qb->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY)->setHint('knp_paginator.count'$newQb->getQuery()->getSingleScalarResult()),
  80.             isset($data['page']) ? $data['page'] : 1,
  81.             isset($data['limit']) && !empty($data['limit']) ? $data['limit'] : self::LIMIT,
  82.             array('distinct' => true)
  83.         );
  84.         $paginationData $results->getPaginationData();
  85.         $queryParameters $results->getParams();
  86.         $queryParameters['page'] = "replacePage";
  87.         $paginationData['url'] = '#'.$container->get('uvdesk.service')->buildPaginationQuery($queryParameters);
  88.         $data = array();
  89.         $userService $container->get('user.service');
  90.         $ticketService $container->get('ticket.service');
  91.         $translatorService $container->get('translator');
  92.         foreach ($results as $key => $ticket) {
  93.             $ticket[0]['status']['description'] = $translatorService->trans($ticket[0]['status']['description']);
  94.             $data[] = [
  95.                 'id' => $ticket[0]['id'],
  96.                 'subject' => $ticket[0]['subject'],
  97.                 'isCustomerView' => $ticket[0]['isCustomerViewed'],
  98.                 'status' => $ticket[0]['status'],
  99.                 'group' => $ticket[0]['supportGroup'],
  100.                 'type' => $ticket[0]['type'],
  101.                 'priority' => $ticket[0]['priority'],
  102.                 'formatedCreatedAt' => $userService->convertToTimezone($ticket[0]['createdAt']),
  103.                 'totalThreads' => $ticketService->getTicketTotalThreads($ticket[0]['id']),
  104.                 'agent' => $ticket['agentId'] ? $userService->getAgentDetailById($ticket['agentId']) : null,
  105.                 'customer' => $ticket['customerId'] ? $userService->getCustomerPartialDetailById($ticket['customerId']) : null,
  106.                 // 'hasAttachments' => $ticketService->hasAttachments($ticket[0]['id'])
  107.             ];
  108.         }
  109.         $json['tickets'] = $data;
  110.         $json['pagination'] = $paginationData;
  111.         return $json;
  112.     }
  113.     public function getAllCustomerTickets(ParameterBag $obj null$container$actAsUser null)
  114.     {
  115.         $currentUser $actAsUser ? : $container->get('user.service')->getCurrentUser();
  116.         $json = array();
  117.         $qb $this->getEntityManager()->createQueryBuilder();
  118.         $qb->select('DISTINCT t,gr,pr,tp,s,a.id as agentId,c.id as customerId')->from($this->getEntityName(), 't');
  119.         $qb->leftJoin('t.agent''a');
  120.         $qb->leftJoin('a.userInstance''ad');
  121.         $qb->leftJoin('t.status''s');
  122.         $qb->leftJoin('t.customer''c');
  123.         $qb->leftJoin('t.supportGroup''gr');
  124.         $qb->leftJoin('t.priority''pr');
  125.         $qb->leftJoin('t.type''tp');
  126.         $qb->leftJoin('t.collaborators''tc');
  127.         $qb->addSelect("CONCAT(a.firstName,' ', a.lastName) AS name");
  128.         $qb->andwhere("t.agent IS NULL OR ad.supportRole != 4");
  129.         $data $obj->all();
  130.         $data array_reverse($data);
  131.         foreach ($data as $key => $value) {
  132.             if(!in_array($key,$this->safeFields)) {
  133.                 if(isset($data['search']) && $key == 'search') {
  134.                     $qb->andwhere("t.subject LIKE :subject OR a.email LIKE :agentName OR t.id LIKE :ticketId");
  135.                     $qb->setParameter('subject''%'.urldecode($value).'%');
  136.                     $qb->setParameter('agentName''%'.urldecode($value).'%');
  137.                     $qb->setParameter('ticketId''%'.urldecode($value).'%');
  138.                 } elseif($key == 'status') {
  139.                     $qb->andwhere('t.status = '.intval($value));
  140.                 }
  141.             }
  142.         }
  143.         $qb->andwhere('t.customer = :customerId OR tc.id =:collaboratorId');
  144.         $qb->setParameter('customerId'$currentUser->getId());
  145.         $qb->setParameter('collaboratorId'$currentUser->getId());
  146.         $qb->andwhere('t.isTrashed != 1');
  147.         if(!isset($data['sort'])) {
  148.             $qb->orderBy('t.id',Criteria::DESC);
  149.         }
  150.         $paginator $container->get('knp_paginator');
  151.         $newQb = clone $qb;
  152.         $newQb->select('COUNT(DISTINCT t.id)');
  153.         $results $paginator->paginate(
  154.             $qb->getQuery()->setHydrationMode(Query::HYDRATE_ARRAY)->setHint('knp_paginator.count'$newQb->getQuery()->getSingleScalarResult()),
  155.             isset($data['page']) ? $data['page'] : 1,
  156.             self::LIMIT,
  157.             array('distinct' => true)
  158.         );
  159.         $paginationData $results->getPaginationData();
  160.         $queryParameters $results->getParams();
  161.         $queryParameters['page'] = "replacePage";
  162.         $paginationData['url'] = '#'.$container->get('uvdesk.service')->buildPaginationQuery($queryParameters);
  163.         $data = array();
  164.         $userService $container->get('user.service');
  165.         $ticketService $container->get('ticket.service');
  166.         $translatorService $container->get('translator');
  167.         foreach ($results as $key => $ticket) {
  168.             $ticket[0]['status']['code'] = $translatorService->trans($ticket[0]['status']['code']);
  169.             $data[] = [
  170.                 'id' => $ticket[0]['id'],
  171.                 'subject' => $ticket[0]['subject'],
  172.                 'isCustomerView' => $ticket[0]['isCustomerViewed'],
  173.                 'status' => $ticket[0]['status'],
  174.                 'group' => $ticket[0]['supportGroup'],
  175.                 'type' => $ticket[0]['type'],
  176.                 'priority' => $ticket[0]['priority'],
  177.                 'totalThreads' => $ticketService->getTicketTotalThreads($ticket[0]['id']),
  178.                 'agent' => $ticket['agentId'] ? $userService->getAgentDetailById($ticket['agentId']) : null,
  179.                 'customer' => $ticket['customerId'] ? $userService->getCustomerPartialDetailById($ticket['customerId']) : null,
  180.                 'formatedCreatedAt' => $userService->getLocalizedFormattedTime($ticket[0]['createdAt'],$userService->getSessionUser()),
  181.             ];
  182.         }
  183.         $json['tickets'] = $data;
  184.         $json['pagination'] = $paginationData;
  185.         return $json;
  186.     }
  187.     public function addPermissionFilter($qbUser $user, array $supportGroupReferences = [], array $supportTeamReferences = [])
  188.     {
  189.         $userInstance $user->getAgentInstance();
  190.         if (!empty($userInstance) && ('ROLE_AGENT' == $userInstance->getSupportRole()->getCode() && $userInstance->getTicketAccesslevel() != self::TICKET_GLOBAL_ACCESS)) {
  191.             $qualifiedGroups = empty($this->params['group']) ? $supportGroupReferences array_intersect($supportGroupReferencesexplode(','$this->params['group']));
  192.             $qualifiedTeams = empty($this->params['team']) ? $supportTeamReferences array_intersect($supportTeamReferencesexplode(','$this->params['team']));
  193.             switch ($userInstance->getTicketAccesslevel()) {
  194.                 case self::TICKET_GROUP_ACCESS:
  195.                     $qb
  196.                         ->andWhere("ticket.agent = :agentId OR supportGroup.id IN(:supportGroupIds) OR supportTeam.id IN(:supportTeamIds)")
  197.                         ->setParameter('agentId'$user->getId())
  198.                         ->setParameter('supportGroupIds'$qualifiedGroups)
  199.                         ->setParameter('supportTeamIds'$qualifiedTeams);
  200.                     break;
  201.                 case self::TICKET_TEAM_ACCESS:
  202.                     $qb
  203.                         ->andWhere("ticket.agent = :agentId OR supportTeam.id IN(:supportTeamIds)")
  204.                         ->setParameter('agentId'$user->getId())
  205.                         ->setParameter('supportTeamIds'$qualifiedTeams);
  206.                     break;
  207.                 default:
  208.                     $qb
  209.                         ->andWhere("ticket.agent = :agentId")
  210.                         ->setParameter('agentId'$user->getId());
  211.                     break;
  212.             }
  213.         }
  214.         return $qb;
  215.     }
  216.     public function prepareBaseTicketQuery(User $user, array $supportGroupIds = [], array $supportTeamIds = [], array $params = [], bool $filterByStatus true)
  217.     {
  218.         $queryBuilder $this->getEntityManager()->createQueryBuilder()
  219.             ->select("
  220.                 DISTINCT ticket,
  221.                 supportGroup.name as groupName,
  222.                 supportTeam.name as teamName, 
  223.                 priority,
  224.                 type.code as typeName, 
  225.                 agent.id as agentId,
  226.                 agent.email as agentEmail,
  227.                 agentInstance.profileImagePath as smallThumbnail, 
  228.                 customer.id as customerId, 
  229.                 customer.email as customerEmail, 
  230.                 customerInstance.profileImagePath as customersmallThumbnail, 
  231.                 CONCAT(customer.firstName, ' ', customer.lastName) AS customerName, 
  232.                 CONCAT(agent.firstName,' ', agent.lastName) AS agentName
  233.             ")
  234.             ->from(Ticket::class, 'ticket')
  235.             ->leftJoin('ticket.type''type')
  236.             ->leftJoin('ticket.agent''agent')
  237.             ->leftJoin('ticket.threads''threads')
  238.             ->leftJoin('ticket.priority''priority')
  239.             ->leftJoin('ticket.customer''customer')
  240.             ->leftJoin('ticket.supportTeam''supportTeam')
  241.             ->leftJoin('ticket.supportTags''supportTags')
  242.             ->leftJoin('agent.userInstance''agentInstance')
  243.             ->leftJoin('ticket.supportLabels''supportLabel')
  244.             ->leftJoin('ticket.supportGroup''supportGroup')
  245.             ->leftJoin('customer.userInstance''customerInstance')
  246.             ->where('customerInstance.supportRole = 4')
  247.             ->andWhere("agent.id IS NULL OR agentInstance.supportRole != 4")
  248.             ->andWhere('ticket.isTrashed = :isTrashed')->setParameter('isTrashed', isset($params['trashed']) ? true false);
  249.         if (!isset($params['sort'])) {
  250.             $queryBuilder->orderBy('ticket.updatedAt'Criteria::DESC);
  251.         }
  252.         if ($filterByStatus) {
  253.             $queryBuilder->andWhere('ticket.status = :status')->setParameter('status', isset($params['status']) ? $params['status'] : 1);
  254.         }
  255.         $this->addPermissionFilter($queryBuilder$user$supportGroupIds$supportTeamIds);
  256.         // applyFilter according to params
  257.         return $this->prepareTicketListQueryWithParams($queryBuilder$params$user);
  258.     }
  259.     public function prepareBasePaginationTicketTypesQuery(array $params)
  260.     {
  261.         $queryBuilder $this->getEntityManager()->createQueryBuilder()
  262.             ->select("ticketType")
  263.             ->from(TicketType::class, 'ticketType');
  264.         // Apply filters
  265.         foreach ($params as $field => $fieldValue) {
  266.             if (in_array($field$this->safeFields)) {
  267.                 continue;
  268.             }
  269.             switch ($field) {
  270.                 case 'search':
  271.                     $queryBuilder->andwhere("ticketType.code LIKE :searchQuery OR ticketType.description LIKE :searchQuery");
  272.                     $queryBuilder->setParameter('searchQuery''%' urldecode(trim($fieldValue)) . '%');
  273.                     break;
  274.                 case 'isActive':
  275.                     $queryBuilder->andwhere("ticketType.isActive LIKE :searchQuery");
  276.                     $queryBuilder->setParameter('searchQuery''%' urldecode(trim($fieldValue)) . '%');
  277.                     break;
  278.                 default:
  279.                     break;
  280.             }
  281.         }
  282.         // Define sort by
  283.         if (empty($params['sort']) || 'a.id' == $params['sort']) {
  284.             $queryBuilder->orderBy('ticketType.id', (empty($params['direction']) || 'ASC' == strtoupper($params['direction'])) ? Criteria::ASC Criteria::DESC);
  285.         } else {
  286.             $queryBuilder->orderBy('ticketType.code', (empty($params['direction']) || 'ASC' == strtoupper($params['direction'])) ? Criteria::ASC Criteria::DESC);
  287.         }
  288.         return $queryBuilder;
  289.     }
  290.     public function prepareBasePaginationTagsQuery(array $params)
  291.     {
  292.         $queryBuilder $this->getEntityManager()->createQueryBuilder()
  293.             ->select('supportTag.id as id, supportTag.name as name, COUNT(ticket) as totalTickets')
  294.             ->from(Tag::class, 'supportTag')
  295.             ->leftJoin('supportTag.tickets''ticket')
  296.             ->groupBy('supportTag.id');
  297.         // Apply filters
  298.         foreach ($params as $field => $fieldValue) {
  299.             if (in_array($field$this->safeFields)) {
  300.                 continue;
  301.             }
  302.             switch ($field) {
  303.                 case 'search':
  304.                     $queryBuilder->andwhere("supportTag.name LIKE :searchQuery")->setParameter('searchQuery''%' urldecode(trim($fieldValue)) . '%');
  305.                     break;
  306.                 default:
  307.                     break;
  308.             }
  309.         }
  310.         // Define sort by
  311.         if (empty($params['sort']) || 'a.id' == $params['sort']) {
  312.             $queryBuilder->orderBy('supportTag.id', (empty($params['direction']) || 'ASC' == strtoupper($params['direction'])) ? Criteria::ASC Criteria::DESC);
  313.         } else {
  314.             $queryBuilder->orderBy('supportTag.name', (empty($params['direction']) || 'ASC' == strtoupper($params['direction'])) ? Criteria::ASC Criteria::DESC);
  315.         }
  316.         return $queryBuilder;
  317.     }
  318.     public function getTicketTabDetails(User $user, array $supportGroupIds = [], array $supportTeamIds = [], array $params = [], bool $filterByStatus true)
  319.     {
  320.         $data = array(=> 0=> 0=> 0=> 0=> 0=> 0);
  321.         
  322.         $queryBuilder $this->getEntityManager()->createQueryBuilder()
  323.             ->select("
  324.                 COUNT(DISTINCT ticket.id) as countTicket, 
  325.                 status.id as statusId, 
  326.                 status.code as tab
  327.             ")
  328.             ->from(Ticket::class, 'ticket')
  329.             ->leftJoin('ticket.type',   'type')
  330.             ->leftJoin('ticket.agent''agent')
  331.             ->leftJoin('ticket.status''status')
  332.             ->leftJoin('ticket.threads''threads')
  333.             ->leftJoin('ticket.priority''priority')
  334.             ->leftJoin('ticket.customer''customer')
  335.             ->leftJoin('ticket.supportTeam''supportTeam')
  336.             ->leftJoin('ticket.supportTags''supportTags')
  337.             ->leftJoin('ticket.supportGroup''supportGroup')
  338.             ->leftJoin('agent.userInstance''agentInstance')
  339.             ->leftJoin('ticket.supportLabels''supportLabel')
  340.             ->leftJoin('customer.userInstance''customerInstance')
  341.             ->where('customerInstance.supportRole = 4')
  342.             ->andWhere("agent.id IS NULL OR agentInstance.supportRole != 4")
  343.             ->andWhere('ticket.isTrashed = :isTrashed')->setParameter('isTrashed', isset($params['trashed']) ? true false)
  344.             ->groupBy('status');
  345.         // applyFilter according to permission
  346.         $this->addPermissionFilter($queryBuilder$user$supportGroupIds$supportTeamIds);
  347.         
  348.         $queryBuilder $this->prepareTicketListQueryWithParams($queryBuilder$params$user);
  349.         $results $queryBuilder->getQuery()->getResult();
  350.         foreach($results as $status) {
  351.             $data[$status['statusId']] += $status['countTicket'];
  352.         }
  353.         return $data;
  354.     }
  355.     public function countTicketTotalThreads($ticketId$threadType 'reply')
  356.     {
  357.         $totalThreads $this->getEntityManager()->createQueryBuilder()
  358.             ->select('COUNT(thread.id) as threads')
  359.             ->from(Ticket::class, 'ticket')
  360.             ->leftJoin('ticket.threads''thread')
  361.             ->where('ticket.id = :ticketId')->setParameter('ticketId'$ticketId)
  362.             ->andWhere('thread.threadType = :threadType')->setParameter('threadType'$threadType)
  363.             ->getQuery()->getSingleScalarResult();
  364.         
  365.         return (int) $totalThreads;
  366.     }
  367.     public function getTicketNavigationIteration($ticket$container)
  368.     {
  369.         $ticketsCollection $this->getEntityManager()->getRepository(Ticket::class)
  370.                    ->getAllTickets(null$container);
  371.         if ($ticketsCollection)
  372.             $results $ticketsCollection['tickets'];
  373.         $nextPrevPage = array('next' => 0,'prev' => 0);
  374.         for ($i 0$i count($results); $i++) {
  375.             if($results[$i]['id'] == $ticket->getId()) {
  376.                 $nextPrevPage['next'] = isset($results[$i 1]) ? $results[$i 1]['id'] : 0;
  377.                 $nextPrevPage['prev'] = isset($results[$i 1]) ? $results[$i 1]['id'] : 0;
  378.             }
  379.         }
  380.         return $nextPrevPage;
  381.     }
  382.     public function countCustomerTotalTickets(User $user$container)
  383.     {
  384.         $userService $container->get('user.service');
  385.         $queryBuilder $this->getEntityManager()->createQueryBuilder()
  386.             ->select('COUNT(ticket.id) as tickets')
  387.             ->from(Ticket::class, 'ticket')
  388.             ->leftJoin('ticket.priority''p')
  389.             ->leftJoin('ticket.status''s')
  390.             ->leftJoin('ticket.agent''a')
  391.             ->leftJoin('ticket.type''type')
  392.             ->leftJoin('ticket.supportGroup''supportGroup')
  393.             ->leftJoin('ticket.supportTeam''supportTeam')
  394.             ->leftJoin('a.userInstance''ad')
  395.             ->andWhere('ticket.customer = :customerId')
  396.             ->andWhere('ticket.isTrashed != 1')
  397.             ->setParameter('customerId'$user->getId())
  398.             ->andwhere("a IS NULL OR ad.supportRole != 4")
  399.             ->orderBy('ticket.id'Criteria::DESC);
  400.         $agent $userService->getCurrentUser();
  401.         $supportGroupReference $this->getEntityManager()->getRepository(User::class)->getUserSupportGroupReferences($agent);
  402.         $supportTeamReference  $this->getEntityManager()->getRepository(User::class)->getUserSupportTeamReferences($agent);
  403.         
  404.         $this->addPermissionFilter($queryBuilder$agent$supportGroupReference$supportTeamReference);
  405.         return (int) $queryBuilder->getQuery()->getSingleScalarResult();
  406.     }
  407.     public function isLabelAlreadyAdded($ticket,$label)
  408.     {
  409.         $qb $this->getEntityManager()->createQueryBuilder();
  410.         $qb->select('COUNT(t.id) as ticketCount')->from(Ticket::class, 't')
  411.                 ->leftJoin('t.supportLabels','tl')
  412.                 ->andwhere('tl.id = :labelId')
  413.                 ->andwhere('t.id = :ticketId')
  414.                 ->setParameter('labelId',$label->getId())
  415.                 ->setParameter('ticketId',$ticket->getId());
  416.         return $qb->getQuery()->getSingleScalarResult() ? true false;
  417.     }
  418.     public function isTicketCollaborator($ticket$collaboratorEmail)
  419.     {
  420.         if ($ticket->getCollaborators()) {
  421.             foreach ($ticket->getCollaborators() as $collaborator) {
  422.                 if (strtolower($collaborator->getEmail()) == strtolower($collaboratorEmail)) {
  423.                     return true;
  424.                 }
  425.             }
  426.         }
  427.         return false;
  428.     }
  429.     public function getTicketDetails(ParameterBag $obj null$container)
  430.     {
  431.         $data $obj->all();
  432.         $userService $container->get('user.service');
  433.         $ticketService $container->get('ticket.service');
  434.         $json = [];
  435.         $qb $this->getEntityManager()->createQueryBuilder();
  436.         $qb->select('DISTINCT t,gr.name as groupName,supportTeam.name as supportTeamName,tp.code as typeName,s,pr,a.id as agentId,c.id as customerId')->from($this->getEntityName(), 't')
  437.                 ->leftJoin('t.agent''a')
  438.                 ->leftJoin('t.status''s')
  439.                 ->leftJoin('t.customer''c')
  440.                 ->leftJoin('t.supportGroup''gr')
  441.                 ->leftJoin('t.supportTeam''supportTeam')
  442.                 ->leftJoin('t.priority''pr')
  443.                 ->leftJoin('t.type''tp')
  444.                 ->leftJoin('c.userInstance''cd')
  445.                 ->leftJoin('a.userInstance''ad')
  446.                 ->leftJoin('t.supportTags''tg')
  447.                 ->leftJoin('t.supportLabels''tl')
  448.                 ->andwhere('t.id = :ticketId')
  449.                 ->setParameter('ticketId'$data['ticketId']);
  450.         $results $qb->getQuery()->getArrayResult();
  451.         $ticket array_shift($results);
  452.         
  453.         return [
  454.             'id' => $ticket[0]['id'],
  455.             'subject' => $ticket[0]['subject'],
  456.             'isStarred' => $ticket[0]['isStarred'],
  457.             'isAgentView' => $ticket[0]['isAgentViewed'],
  458.             'isTrashed' => $ticket[0]['isTrashed'],
  459.             'status' => $ticket[0]['status'],
  460.             'groupName' => $ticket['groupName'],
  461.             'subGroupName' => $ticket['supportTeamName'],
  462.             'typeName' => $ticket['typeName'],
  463.             'priority' => $ticket[0]['priority'],
  464.             'formatedCreatedAt' => $ticketService->timeZoneConverter($ticket[0]['createdAt']),      
  465.             'ticketLabels' => $ticketService->getTicketLabels($ticket[0]['id']),
  466.             'totalThreads' => $ticketService->getTicketTotalThreads($ticket[0]['id']),
  467.             'agent' => $ticket['agentId'] ? $userService->getAgentDetailById($ticket['agentId']) : null,
  468.             'customer' => $ticket['customerId'] ? $userService->getCustomerPartialDetailById($ticket['customerId']) : null,
  469.             'lastReplyAgentName' => $ticketService->getlastReplyAgentName($ticket[0]['id']),
  470.             'createThread' => $ticketService->getCreateReply($ticket[0]['id']),
  471.             'lastReply' => $ticketService->getLastReply($ticket[0]['id']),
  472.         ];
  473.     }
  474.     // Get customer more ticket sidebar details
  475.     public function getCustomerMoreTicketsSidebar($customerId$container$request) {
  476.         $userService $container->get('user.service');
  477.         $ticketService $container->get('ticket.service');
  478.         $qb $this->getEntityManager()->createQueryBuilder();
  479.         $qb->select("DISTINCT ticket as tickets,s.code as statusName, supportTeam.name as teamName,supportGroup.name as groupName, p.code as priorityName, p.colorCode as priorityColor, type.code as typeName, a.id as agentId, CONCAT(a.firstName, ' ', a.lastName) AS agentName")
  480.                 ->from($this->getEntityName(), 'ticket')
  481.                 ->leftJoin('ticket.priority''p')
  482.                 ->leftJoin('ticket.status''s')
  483.                 ->leftJoin('ticket.agent''a')
  484.                 ->leftJoin('ticket.type''type')
  485.                 ->leftJoin('ticket.supportGroup''supportGroup')
  486.                 ->leftJoin('ticket.supportTeam''supportTeam')
  487.                 ->leftJoin('a.userInstance''ad')
  488.                 ->andWhere('ticket.customer = :customerId')
  489.                 ->andWhere('ticket.isTrashed != 1')
  490.                 ->setParameter('customerId'$customerId)
  491.                 ->andwhere("a IS NULL OR ad.supportRole != 4")
  492.                 ->orderBy('ticket.id'Criteria::DESC);
  493.         $user $userService->getCurrentUser();
  494.         $supportGroupReference $this->getEntityManager()->getRepository(User::class)->getUserSupportGroupReferences($user);
  495.         $supportTeamReference  $this->getEntityManager()->getRepository(User::class)->getUserSupportTeamReferences($user);
  496.         // if($currentUser->getRole() == "ROLE_AGENT" && $currentUser->detail['agent']->getTicketView() != UserData::GLOBAL_ACCESS) {
  497.         //     $this->em->getRepository('WebkulTicketBundle:Ticket')->addPermissionFilter($qb, $this->container, false);
  498.         //     $qb->addSelect('gr.name as groupName');
  499.         // } else {
  500.         //     $qb->leftJoin('t.supportGroup', 'gr');
  501.         //     $qb->addSelect('gr.name as groupName');
  502.         // }
  503.         $this->addPermissionFilter($qb$user$supportGroupReference$supportTeamReference);
  504.        
  505.         $results $qb->getQuery()->getArrayResult();
  506.         foreach ($results as $key => $ticket) {
  507.             $results[$key] = $ticket['tickets'];
  508.             unset($ticket['tickets']);
  509.             $results[$key] = array_merge($results[$key], $ticket);
  510.             $results[$key]['timestamp']= $userService->convertToTimezone($results[$key]['createdAt']);
  511.             $results[$key]['formatedCreatedAt'] = $results[$key]['createdAt']->format('d-m-Y H:i A');
  512.             $results[$key]['totalThreads']= $ticketService->getTicketTotalThreads($results[$key]['id']);
  513.             
  514.         }
  515.         return $results;
  516.     }
  517.     public function prepareTicketListQueryWithParams($queryBuilder$params$actAsUser null)
  518.     {
  519.         foreach ($params as $field => $fieldValue) {
  520.             if (in_array($field$this->safeFields)) {
  521.                 continue;
  522.             }
  523.             if($actAsUser != null ) {
  524.                 $userInstance $actAsUser->getAgentInstance();
  525.                 if (!empty($userInstance) && ('ROLE_AGENT' == $userInstance->getSupportRole()->getCode() && $field == 'mine') || ('ROLE_ADMIN' == $userInstance->getSupportRole()->getCode()) && $field == 'mine') {
  526.                     $fieldValue $actAsUser->getId();
  527.                 }
  528.             } 
  529.             switch ($field) {
  530.                 case 'label':
  531.                     $queryBuilder->andwhere('supportLabel.id = :labelIds');
  532.                     $queryBuilder->setParameter('labelIds'$fieldValue);
  533.                     break;
  534.                 case 'starred':
  535.                     $queryBuilder->andWhere('ticket.isStarred = 1');
  536.                     break;
  537.                 case 'search':
  538.                     $value trim($fieldValue);
  539.                     $queryBuilder->andwhere("ticket.subject LIKE :search OR ticket.id  LIKE :search OR customer.email LIKE :search OR CONCAT(customer.firstName,' ', customer.lastName) LIKE :search OR agent.email LIKE :search OR CONCAT(agent.firstName,' ', agent.lastName) LIKE :search");
  540.                     $queryBuilder->setParameter('search''%'.urldecode($value).'%');
  541.                     break;
  542.                 case 'unassigned':
  543.                     $queryBuilder->andWhere("agent.id is NULL");
  544.                     break;
  545.                 case 'notreplied':
  546.                     $queryBuilder->andWhere('ticket.isReplied = 0');
  547.                     break;
  548.                 case 'mine':
  549.                     $queryBuilder->andWhere('agent = :agentId')->setParameter('agentId'$fieldValue);
  550.                     break;
  551.                 case 'new':
  552.                     $queryBuilder->andwhere('ticket.isNew = 1');
  553.                     break;
  554.                 case 'priority':
  555.                     $queryBuilder->andwhere('priority.id = :priority')->setParameter('priority'$fieldValue);
  556.                     break;
  557.                 case 'type':
  558.                     $queryBuilder->andwhere('type.id IN (:typeCollection)')->setParameter('typeCollection'explode(','$fieldValue));
  559.                     break;
  560.                 case 'agent':
  561.                     $queryBuilder->andwhere('agent.id IN (:agentCollection)')->setParameter('agentCollection'explode(','$fieldValue));
  562.                     break;
  563.                 case 'customer':
  564.                     $queryBuilder->andwhere('customer.id IN (:customerCollection)')->setParameter('customerCollection'explode(','$fieldValue));
  565.                     break;
  566.                 case 'group':
  567.                     $queryBuilder->andwhere('supportGroup.id IN (:groupIds)');
  568.                     $queryBuilder->setParameter('groupIds'explode(','$fieldValue));
  569.                     break;
  570.                 case 'team':
  571.                     $queryBuilder->andwhere("supportTeam.id In(:subGrpKeys)");
  572.                     $queryBuilder->setParameter('subGrpKeys'explode(','$fieldValue));
  573.                     break;
  574.                 case 'tag':
  575.                     $queryBuilder->andwhere("supportTags.id In(:tagIds)");
  576.                     $queryBuilder->setParameter('tagIds'explode(','$fieldValue));
  577.                     break;
  578.                 case 'source':
  579.                     $queryBuilder->andwhere('ticket.source IN (:sources)');
  580.                     $queryBuilder->setParameter('sources'explode(','$fieldValue));
  581.                     break;
  582.                 case 'after':
  583.                     $date = \DateTime::createFromFormat('d-m-Y H:i'$fieldValue.' 23:59');
  584.                     if ($date) {
  585.                        // $date = \DateTime::createFromFormat('d-m-Y H:i', $this->userService->convertTimezoneToServer($date, 'd-m-Y H:i'));
  586.                         $queryBuilder->andwhere('ticket.createdAt > :afterDate');
  587.                         $queryBuilder->setParameter('afterDate'$date);
  588.                     }
  589.                     break;
  590.                 case 'before':
  591.                     $date = \DateTime::createFromFormat('d-m-Y H:i'$fieldValue.' 00:00');
  592.                     if ($date) {
  593.                         //$date = \DateTime::createFromFormat('d-m-Y H:i', $container->get('user.service')->convertTimezoneToServer($date, 'd-m-Y H:i'));
  594.                         $queryBuilder->andwhere('ticket.createdAt < :beforeDate');
  595.                         $queryBuilder->setParameter('beforeDate'$date);
  596.                     }
  597.                     break;
  598.                 case 'repliesLess':
  599.                     $queryBuilder->andWhere('threads.threadType = :threadType')->setParameter('threadType''reply')
  600.                         ->groupBy('ticket.id')
  601.                         ->andHaving('count(threads.id) < :threadValueLesser')->setParameter('threadValueLesser'intval($params['repliesLess']));
  602.                     break;
  603.                 case 'repliesMore':
  604.                     $queryBuilder->andWhere('threads.threadType = :threadType')->setParameter('threadType''reply')
  605.                         ->groupBy('ticket.id')
  606.                         ->andHaving('count(threads.id) > :threadValueGreater')->setParameter('threadValueGreater'intval($params['repliesMore']));
  607.                     break;
  608.                 case 'mailbox':
  609.                         $queryBuilder->andwhere('ticket.mailboxEmail IN (:mailboxEmails)');
  610.                         $queryBuilder->setParameter('mailboxEmails'explode(','$fieldValue));
  611.                     break;
  612.                 default:
  613.                     break;
  614.             }
  615.         }
  616.         return $queryBuilder;
  617.     }
  618.     public function getAgentTickets($agentId,$container) {
  619.         $qb $this->getEntityManager()->createQueryBuilder();
  620.         $qb->select('t')->from(Ticket::class, 't');
  621.         $qb->andwhere('t.agent = :agentId');
  622.         $qb->setParameter('agentId',$agentId);
  623.         return $qb->getQuery()->getResult();
  624.     }
  625. }