- <?php
- 
- namespace AdminBundle\Controller;
- 
- use Doctrine\ORM\EntityManagerInterface;
- use Sonata\AdminBundle\Admin\AdminHelper;
- use Sonata\AdminBundle\Admin\Pool;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\BinaryFileResponse;
- use DateTime;
- use CoreBundle\Services\Jira\JiraService;
- use CoreBundle\Entity\Ticket;
- use CoreBundle\Entity\TicketComment;
- use CoreBundle\Entity\TicketCommentFile;
- use CoreBundle\Entity\TicketFile;
- use CoreBundle\Entity\TicketTime;
- use CoreBundle\Entity\User;
- use CoreBundle\Entity\UserUtm;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- use Symfony\Component\HttpFoundation\File\UploadedFile;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
- use Symfony\Component\Mailer\MailerInterface;
- use Symfony\Component\Mime\Address;
- use Symfony\Component\Mime\Email;
- use Symfony\Component\Routing\RouterInterface;
- 
- class TicketController extends AbstractController
- {
-     protected \CoreBundle\Model\Ticket $ticketModel;
-     protected Pool $adminPool;
-     protected RouterInterface $router;
-     protected EntityManagerInterface $em;
- 
-     public function __construct(\CoreBundle\Model\Ticket $ticketModel, Pool $adminPool, RouterInterface $router, EntityManagerInterface $em)
-     {
-         $this->ticketModel = $ticketModel;
-         $this->adminPool = $adminPool;
-         $this->router = $router;
-         $this->em = $em;
-     }
- 
-     public function reportInit(Request $request): JsonResponse
-     {
- 
-         $start = new DateTime($request->get('start'));
-         $end = new DateTime($request->get('end'));
-         $TiketTimes = $this->em->getRepository(TicketTime::class)->getByPeriod($start,$end);
-         $result = [];
-         $prices = [
-             9 => 123,
-             11 => 107,
-             12 => 165,
-             13 => 165,
-         ];
-         /** @var TicketTime $tiketTime */
-         foreach ($TiketTimes as $tiketTime) {
-             $user = $tiketTime->getTicket()->getDealer();
-             $userId = $user ? $user->getId() : 'all';
-             $userName = $user ? $user->getName() : 'Другие';
-             if(!isset($result[$userId])) {
-                 $result[$userId] = [
-                     'title' => $userName,
-                     'time' => [
-                         9 => 0,
-                         11 => 0,
-                         12 => 0,
-                         13 => 0,
-                     ],
-                     'task' => [],
-                 ];
-             }
-             $ticket = $tiketTime->getTicket();
-             $result[$userId]['time'][$ticket->getWorkType()] = round(($result[$userId]['time'][$ticket->getWorkType()] + ($tiketTime->getTime()/60/60)),2);
-             $result[$userId]['cost'][$ticket->getWorkType()] = round(round($result[$userId]['time'][$ticket->getWorkType()],0)* $prices[$ticket->getWorkType()]);
-             if(!isset($result[$userId]['task'][$ticket->getId()])) {
-                 $result[$userId]['task'][$ticket->getId()] = [
-                     'title' => $ticket->getTitle(),
-                     'time' => 0,
-                 ];
-             }
-             $result[$userId]['task'][$ticket->getId()]['time'] = round(($result[$userId]['task'][$ticket->getId()]['time'] + ($tiketTime->getTime()/60/60)),2);
-         }
- 
- 
- 
-         $userResult = [];
-         /** @var TicketTime $tiketTime */
-         foreach ($TiketTimes as $tiketTime) {
- 
-             if(!$User = $tiketTime->getUser()) {
-                 continue;
-             }
- 
-             $name = $User->getFullName();
- 
-             $uId = $User->getId();
-             $Date = $tiketTime->getDateStart();
-             if(!isset($userResult[$uId])) {
-                 $userResult[$uId] = [
-                     'name' => $name,
-                     'total' => 0,
-                     'time' => [],
-                 ];
-             }
-             $fDate = $Date->format('d.m.Y');
-             if(!isset($userResult[$uId]['time'][$fDate])) {
-                 $userResult[$uId]['time'][$fDate] = 0;
-             }
-             $userResult[$uId]['time'][$fDate] = round($userResult[$uId]['time'][$fDate]+($tiketTime->getTime()/60/60),2);
-             $userResult[$uId]['total'] = round($userResult[$uId]['total']+($tiketTime->getTime()/60/60),2);
-         }
- 
- 
-         return $this->json(['success' => true,'data' => $result, 'users' => $userResult]);
-     }
- 
-     public function downloadReport2(Request $request): BinaryFileResponse
-     {   //отчет по UTM
- 
-         $pDir = $this->getParameter('kernel.project_dir');
-         $spreadsheet = new Spreadsheet();
-         $sheet = $spreadsheet->getActiveSheet();
-         $sheet->setCellValue('A1', "Info_ID");
-         $sheet->getColumnDimension ('A') -> setWidth(10);
-         $sheet->setCellValue('B1', 'email');
-         $sheet->getColumnDimension ('B') -> setWidth(27);
-         $sheet->setCellValue('C1', 'Имя');
-         $sheet->getColumnDimension ('C') -> setWidth(14);
-         $sheet->setCellValue('D1', 'Фамилия');
-         $sheet->getColumnDimension ('D') -> setWidth(17);
-         $sheet->setCellValue('E1', 'Телефон');
-         $sheet->getColumnDimension ('E') -> setAutoSize (true);
-         $sheet->setCellValue('F1', 'Дата регистрации');
-         $sheet->getColumnDimension ('F') -> setWidth(27);
-         $sheet->setCellValue('G1', 'Тип');
-         $sheet->getColumnDimension ('G') -> setWidth(27);
-         $sheet->setCellValue('H1', 'URL');
-         $sheet->getColumnDimension ('H') -> setWidth(66);
-         $sheet->setCellValue('I1', 'Referrer');
-         $sheet->getColumnDimension ('I') -> setWidth(33);
-         //$sheet->getColumnDimension ('G') -> setAutoSize (true);
-         $sheet->setCellValue('J1', 'UTM1 NAME');
-         $sheet->getColumnDimension ('J') -> setAutoSize (true);
-         $sheet->setCellValue('K1', 'UTM1 VALUE');
-         $sheet->getColumnDimension ('K') -> setAutoSize (true);
-         $sheet->setCellValue('L1', 'UTM2 NAME');
-         $sheet->getColumnDimension ('L') -> setAutoSize (true);
-         $sheet->setCellValue('M1', 'UTM2 VALUE');
-         $sheet->getColumnDimension ('M') -> setAutoSize (true);
-         $sheet->setCellValue('N1', 'UTM3 NAME');
-         $sheet->getColumnDimension ('N') -> setAutoSize (true);
-         $sheet->setCellValue('O1', 'UTM3 VALUE');
-         $sheet->getColumnDimension ('O') -> setAutoSize (true);
-         $sheet->setCellValue('P1', 'UTM4 VALUE');
-         $sheet->getColumnDimension ('P') -> setAutoSize (true);
-         $sheet->setCellValue('Q1', 'UTM5 VALUE');
-         $sheet->getColumnDimension ('Q') -> setAutoSize (true);
-         $sheet->setCellValue('R1', 'UTM6 VALUE');
-         $sheet->getColumnDimension ('R') -> setAutoSize (true);
-         $sheet->calculateColumnWidths();
- 
- 
- 
-         $start= new DateTime($request->get('start'));
-         $end= new DateTime($request->get('end'));
- 
-         $userUtm= $this->em->getRepository(UserUtm::class)->getUtmByPeriod($start,$end);
- 
-             $i = 1;
-         /** @var UserUtm $utm */
-             foreach ($userUtm as $utm) {
-                 if (strlen($utm->getReferrer())>1) {
-                     $refsrc = explode("?", $utm->getReferrer());  //0-ссылка 1 - utm метки
- 
-                 $i++;
-                 $i2 = 0;
- 
-                 $pars = explode("&", $refsrc[1]);
- 
- //поля по БД
-                 $sheet->setCellValue('A' . $i, $utm->getId());
-                 $sheet->setCellValue('B' . $i, $utm->getUser()->getEmail());
-                 $sheet->setCellValue('C' . $i, $utm->getUser()->getFullName());
-                 $sheet->setCellValue('D' . $i, $utm->getUser()->getLastName());
-                 $sheet->setCellValue('E' . $i, $utm->getUser()->getPhone());
-                 $sheet->setCellValue('F' . $i, $utm->getCreatedAt()->format('d.m.Y H:m:s'));
-                     switch ($utm->getType()) {
-                         case User::UTM_REGISTRATION:
-                             $typeName = 'Регистрация';
-                             break;
-                         case User::UTM_LOGIN:
-                             $typeName = 'Авторизация';
-                             break;
-                         default:
-                             $typeName = 'Не определено';
-                             break;
-                     }
- 
- 
-                 $sheet->setCellValue('G' . $i, $typeName);
-                 $sheet->setCellValue('H' . $i, $utm->getReferrer());
-                 $sheet->setCellValue('I' . $i, $refsrc[0]); // чистый реферрер до UTM меток
- 
-                 //парсим поле с UTM метками и добавляем вправо данные по UTM1,2,3...
-                 foreach ($pars as $val1) {
-                     $i2++;
-                     $inpars = explode("=", $val1);
- 
-                     if ($i2 == 1) {
-                         $sheet->setCellValue('J' . $i, $inpars[0]);
-                     } //UTM1 Name
-                     if ($i2 == 1) {
-                         $sheet->setCellValue('K' . $i, $inpars[1]);
-                     } //UTM1 Value
-                     if ($i2 == 2) {
-                         $sheet->setCellValue('L' . $i, $inpars[0]);
-                     } //UTM2 Name
-                     if ($i2 == 2) {
-                         $sheet->setCellValue('M' . $i, $inpars[1]);
-                     } //UTM2 Value
-                     if ($i2 == 3) {
-                         $sheet->setCellValue('N' . $i, $inpars[0]);
-                     } //UTM3 Name
-                     if ($i2 == 3) {
-                         $sheet->setCellValue('O' . $i, $inpars[1]);
-                     } //UTM3 Value
-                     if ($i2 == 4) {
-                         $sheet->setCellValue('P' . $i, $inpars[1]);
-                     } //UTM4 Value
-                     if ($i2 == 5) {
-                         $sheet->setCellValue('Q' . $i, $inpars[1]);
-                     } //UTM5 Value
-                     if ($i2 == 6) {
-                         $sheet->setCellValue('R' . $i, $inpars[1]);
-                     } //UTM6 Value
-                 }
- 
-                     //if ($i2==5) {$sheet->setCellValue('J1', $inpars[0]);
-                 }
-                 }
- 
- 
- 
-         $writer = new Xlsx($spreadsheet);
-         $name = 'report_'.time().'.xlsx';
-         $writer->save($pDir.'/public/uploads/files/'.$name);
-         return $this->file($pDir.'/public/uploads/files/'.$name);
-     }
-     public function downloadReport(Request $request): BinaryFileResponse
-     {
-         $start = new DateTime($request->get('start'));
-         $end = new DateTime($request->get('end'));
-         $TiketTimes = $this->em->getRepository(TicketTime::class)->getByPeriod($start,$end);
-         $result = [];
-         $prices = [
-             9 => 123,
-             11 => 107,
-             12 => 165,
-             13 => 165,
-         ];
-         /** @var TicketTime $tiketTime */
-         foreach ($TiketTimes as $tiketTime) {
-             $user = $tiketTime->getTicket()->getDealer();
-             $userId = $user ? $user->getId() : 'all';
-             $userName = $user ? $user->getName() : 'На всех';
-             if(!isset($result[$userId])) {
-                 $result[$userId] = [
-                     'title' => $userName,
-                     'time' => [
-                         9 => 0,
-                         11 => 0,
-                         12 => 0,
-                         13 => 0,
-                     ],
-                     'task' => [],
-                 ];
-             }
-             $ticket = $tiketTime->getTicket();
-             $result[$userId]['time'][$ticket->getWorkType()] = round(($result[$userId]['time'][$ticket->getWorkType()] + ($tiketTime->getTime()/60/60)),2);
-             $result[$userId]['cost'][$ticket->getWorkType()] = round(round($result[$userId]['time'][$ticket->getWorkType()],0)* $prices[$ticket->getWorkType()]);
-             if(!isset($result[$userId]['task'][$ticket->getId()])) {
-                 $result[$userId]['task'][$ticket->getId()] = [
-                     'title' => $ticket->getTitle(),
-                     'time' => 0,
-                 ];
-             }
-             $result[$userId]['task'][$ticket->getId()]['time'] = round(($result[$userId]['task'][$ticket->getId()]['time'] + ($tiketTime->getTime()/60/60)),2);
-         }
- 
- 
-         $pDir = $this->getParameter('kernel.project_dir');
-         $spreadsheet = new Spreadsheet();
-         $sheet = $spreadsheet->getActiveSheet();
-         $sheet->setCellValue('A1', 'Дилер');
-         $sheet->setCellValue('B1', 'Верстка (часы/гривны)');
-         $sheet->setCellValue('C1', 'Программирование (часы/гривны))');
-         $sheet->setCellValue('D1', 'Дизайн (часы/гривны');
-         $sheet->setCellValue('E1', 'Контент (часы/гривны)');
-         $sheet->setCellValue('F1', 'Итого, грн');
-         $i = 1;
-         foreach ($result as $user) {
-             $i++;
-             $vTime = $user['time'][13] ?? 0;
-             $pTime = $user['time'][9] ?? 0;
-             $dTime = $user['time'][12] ?? 0;
-             $cTime = $user['time'][11] ?? 0;
- 
-             $vCost = $user['cost'][13] ?? 0;
-             $pCost = $user['cost'][9] ?? 0;
-             $dCost = $user['cost'][12] ?? 0;
-             $cCost = $user['cost'][11] ?? 0;
- 
-             $totalCost = ceil($vCost+$pCost+$dCost+$cCost);
- 
-             $sheet->setCellValue('A'.$i, $user['title']);
-             $sheet->setCellValue('B'.$i, $vTime.', ч. / '.$vCost.', грн');
-             $sheet->setCellValue('C'.$i, $pTime.', ч. / '.$pCost.', грн');
-             $sheet->setCellValue('D'.$i, $dTime.', ч. / '.$dCost.', грн');
-             $sheet->setCellValue('E'.$i, $cTime.', ч. / '.$cCost.', грн');
-             $sheet->setCellValue('F'.$i, $totalCost.', грн');
- 
-         }
- 
-         $writer = new Xlsx($spreadsheet);
-         $name = 'report_'.time().'.xlsx';
-         $writer->save($pDir.'/public/uploads/files/'.$name);
-         return $this->file($pDir.'/public/uploads/files/'.$name);
-     }
- 
-     public function uploadFiles(Request $request, EntityManagerInterface $em, JiraService $jiraService): JsonResponse
-     {
-         $id = $request->request->get('id');
-         $Ticket = $em->getRepository(Ticket::class)->find($id);
-         if(!$Ticket) {
-             return $this->json(['success' => false]);
-         }
-         $files = $request->files->get('fileInput');
-         foreach ($files as $file) {
-             $fileName = $this->upload($file);
-             if($fileName) {
-                 $ticketFile = new TicketFile();
-                 $ticketFile->setFile($fileName);
-                 $ticketFile->setTicket($Ticket);
-                 $Ticket->addFile($ticketFile);
-                 $em->persist($ticketFile);
-                 $em->persist($Ticket);
-                 $em->flush();
-             }
-             if ($Ticket->getIssueId()) {
-                 $jiraService->sendFile($ticketFile, $Ticket->getIssueId());
-             }
-         }
-         return $this->json(['success' => true, 'ticket' => $this->entityToArray($Ticket)]);
- 
-     }
- 
-     private function upload(UploadedFile $file)
-     {
-         $name = $file->getClientOriginalName();
-         $rootDir = $this->container->getParameter('kernel.project_dir');
-         $file->move(
-             $rootDir.'/public/uploads/files',
-             $name
-         );
-         return $name;
-     }
- 
-     public function kanbanInit()
-     {
-         $User = $this->getUser();
-         if(!$User) {
-             return new JsonResponse(['success' => false]);
-         }
-         $tickets = $this->em->getRepository(Ticket::class)->getByState([],[8,3]);
-         $ticketsArray = $this->ticketsToArray($tickets);
-         $userData = [
-             'id' => $User->getId(),
-             'name' => $User->getFullNAme(),
-         ];
- 
- 
-         $times = [
-             'month' => 0,
-             'yesterday' => 0,
-             'today' => 0,
-         ];
-         $now = new DateTime();
-         $yesterday = new DateTime('-1 day');
-         $start = new DateTime($now->format('Y-m-01 00:00:00'));
-         $Timers = $this->em->getRepository(TicketTime::class)->getByPeriod($start,$now, $this->getUser());
-         /** @var TicketTime $timer */
-         foreach ($Timers as $timer) {
-             $timerStart = $timer->getDateStart();
-             $timerEnd = $timer->getDateEnd() ?: new DateTime();
-             $diff = $timerEnd->diff($timerStart);
-             $min = ($diff->d * 24 * 60) + $diff->h*60 + $diff->i;
-             $times['month'] += $min;
- 
-             if($timerStart->format('Y-m-d') == $now->format('Y-m-d')) {
-                 $times['today'] += $min;
-             }
- 
-             if($timerStart->format('Y-m-d') == $yesterday->format('Y-m-d')) {
-                 $times['yesterday'] += $min;
-             }
-         }
- 
-         foreach ($times as $key => $min) {
-             $hours = floor($min/60);
-             $min -= $hours*60;
-             $minStr = $min < 10 ? '0'.$min : $min;
-             $times[$key] = $hours.':'.$minStr;
-         }
- 
- 
-         return new JsonResponse(['success' => true, 'time' => $times, 'types' => \CoreBundle\Model\Ticket::$works,  'priority' => \CoreBundle\Model\Ticket::$priority, 'tickets' => $ticketsArray, 'user' => $userData]);
-     }
- 
- 
- 
-     private function ticketsToArray($tickets) {
-         $ticketsArray = [];
-         /** @var Ticket $ticket */
-         foreach ($tickets as $ticket) {
-             $ticketsArray[] = $this->entityToArray($ticket);
-         }
-         return $ticketsArray;
-     }
- 
-     private function entityToArray(Ticket $ticket): array
-     {
-         $ticketItem = [
-             'id' => $ticket->getId(),
-             'title' => $ticket->getTitle(),
-             'content' => $ticket->getContent(),
-             'dateCreate' => $ticket->getDateCreate()->format('d.m.Y H:i'),
-             'state' => $ticket->getState(),
-             'priority' => $ticket->getPriority(),
-             'type' => $ticket->getWorkType(),
-             'totalTime' => $this->ticketModel->getTotalTime($ticket),
-             'editUrl' => $this->adminPool->getAdminByAdminCode('admin.ticket')->generateUrl('edit',['id' => $ticket->getId()]),
-             'showUrl' => $this->adminPool->getAdminByAdminCode('admin.ticket')->generateUrl('show',['id' => $ticket->getId()]),
-             'creator' => [
-                 'id' => $ticket->getCreator()->getId(),
-                 'name' => $ticket->getCreator()->getFullName(),
-             ],
-         ];
-         if($ticket->getAssigned()) {
-             $ticketItem['assigned'] = [
-                 'id' => $ticket->getAssigned()->getId(),
-                 'name' => $ticket->getAssigned()->getFullName(),
-             ];
-         }
-         if($ticket->getDealer()) {
-             $ticketItem['dealer'] = [
-                 'id' => $ticket->getDealer()->getId(),
-                 'name' => $ticket->getDealer()->getName(),
-             ];
-         }
- 
-         if($Timer = $this->ticketModel->getActiveTimer($ticket)) {
-             $now = new DateTime();
-             $start = $Timer->getDateStart();
-             $diff = $now->diff($start);
-             $ticketItem['activeTimer'] = [
-                 'id' => $Timer->getId(),
-                 'start' => $Timer->getDateStart()->format('m.d.Y H:i:s'),
-                 'time' => $diff->h.':'.$diff->i.':'.$diff->s,
-             ];
-         }
-         if($ticket->getFiles()->count()) {
-             $ticketItem['files'] = [];
-             /** @var TicketFile $file */
-             foreach ($ticket->getFiles() as $file) {
-                 $ticketItem['files'][] = [
-                     'name' => basename($file->getFile()),
-                     'href' => $this->router->generate('ticket_file_download',['id' => $file->getId()])
-                 ];
-             }
-         }
-         if($ticket->getComments()->count()) {
-             $ticketItem['comments'] = [];
-             /** @var TicketComment $comment */
-             foreach ($ticket->getComments() as $comment) {
-                 $commentItem = [
-                     'user' => $comment->getUser()->getFullName(),
-                     'date' => $comment->getDateCreate()->format('d.m.Y H:i'),
-                     'content' => $comment->getContent(),
-                     'files' => [],
-                 ];
-                 if(count($comment->getFiles())) {
-                     foreach ($comment->getFiles() as $file) {
-                         $commentItem['files'][] = [
-                             'name' => basename($file->getFile()),
-                             'href' => $this->router->generate('ticket_comment_file_download',['id' => $file->getId()])
-                         ];
-                     }
-                 }
-                 $ticketItem['comments'][] = $commentItem;
-             }
-         }
-         if($ticket->getTime()->count()) {
-             $ticketItem['times'] = [];
-             /** @var TicketTime $time */
-             foreach ($ticket->getTime() as $time) {
-                 $start = $time->getDateStart();
-                 $end = $time->getDateEnd();
-                 if(!$end) {
-                     $end = new DateTime();
-                 }
-                 $diff = $end->diff($start);
-                 $min = $diff->i < 10 ? '0'.$diff->i : $diff->i;
-                 $ticketItem['times'][] = [
-                     'user' => $time->getUser() ? $time->getUser()->getFullName() : '',
-                     'dateStart' => $start->format('d.m.Y H:i'),
-                     'time' => $diff->h.':'.$min,
-                 ];
-             }
-         }
-         return $ticketItem;
-     }
- 
-     public function changeState(Request $request)
-     {
-         $ticketId = $request->get('ticketId');
-         $state = $request->get('state');
-         $ticket = $this->em->getRepository(Ticket::class)->find($ticketId);
-         $TicketModel = $this->get('core.ticket.model');
-         switch ($state) {
-             case \CoreBundle\Model\Ticket::STATE_NEW:
-                 $TicketModel->toNew($ticket);
-                 break;
-             case \CoreBundle\Model\Ticket::STATE_DOING:
-                 $TicketModel->toDoing($ticket);
-                 break;
-             case \CoreBundle\Model\Ticket::STATE_WAIT:
-                 $TicketModel->toWait($ticket);
-                 break;
-             case \CoreBundle\Model\Ticket::STATE_DONE:
-                 $TicketModel->toDone($ticket);
-                 break;
-             case \CoreBundle\Model\Ticket::STATE_APPROVED:
-                 $TicketModel->toApproved($ticket);
-                 break;
-         }
- 
-         $tickets = $this->em->getRepository(Ticket::class)->getByState([],[\CoreBundle\Model\Ticket::STATE_APPROVED]);
-         $ticketsArray = $this->ticketsToArray($tickets);
-         return new JsonResponse(['tickets' => $ticketsArray]);
-     }
- 
- 
-     public function deleteTicketFile($id)
-     {
-         $File = $this->em->getRepository(TicketFile::class)->find($id);
-         if(!$File) {
-             return new JsonResponse(['success' => true]);
-         }
-         $rootDir = $this->container->getParameter('kernel.project_dir');
-         $filePath = $rootDir.'/public/uploads/files/'.$File->getFile();
-         if(file_exists($filePath)) {
-             unlink($filePath);
-         }
-         $this->em->remove($File);
-         $this->em->flush();
-         return new JsonResponse(['success' => true]);
-     }
- 
-     public function downloadTicketFile($id): BinaryFileResponse
-     {
-         $File = $this->em->getRepository(TicketFile::class)->find($id);
-         if(!$File) {
-             throw new NotFoundHttpException();
-         }
-         $rootDir = $this->container->getParameter('kernel.project_dir');
-         $filePath = $rootDir.'/public/uploads/files/'.$File->getFile();
-         if(!file_exists($filePath)) {
-             throw new NotFoundHttpException();
-         }
-         return $this->file($filePath);
-     }
-     public function downloadTicketCommentFile($id): BinaryFileResponse
-     {
-         $File = $this->em->getRepository(TicketCommentFile::class)->find($id);
-         if(!$File) {
-             throw new NotFoundHttpException();
-         }
-         $rootDir = $this->container->getParameter('kernel.project_dir');
-         $filePath = $rootDir.'/public/uploads/files/'.$File->getFile();
-         if(!file_exists($filePath)) {
-             throw new NotFoundHttpException();
-         }
-         return $this->file($filePath);
-     }
- 
- 
-     public function timeStart(Request $request)
-     {
-         $ticketId = $request->get('id');
-         $ticket = $this->em->getRepository(Ticket::class)->find($ticketId);
-         if(!$ticket) {
-             return new JsonResponse(['success' => false, 'error' => 'Не удалось запустить таймер 1']);
-         }
- 
-         if(!in_array($ticket->getState(),[\CoreBundle\Model\Ticket::STATE_DOING,\CoreBundle\Model\Ticket::STATE_STOP])) {
-             return new JsonResponse(['success' => false, 'error' => 'Не удалось запустить таймер 2']);
-         }
-         $user = $this->getUser();
-         if($ticket && (!$ticket->getAssigned() || $ticket->getAssigned()->getId() != $user->getId())) {
-             return new JsonResponse(['success' => false, 'error' => 'Не удалось запустить таймер. Задача назначена на другого пользователя']);
-         }
-         if(!$user) {
-             return new JsonResponse(['success' => false, 'error' => 'Не удалось запустить таймер 3']);
-         }
-         $userTimers = $this->em->getRepository(TicketTime::class)->findBy(['user' => $user, 'date_end' => null]);
-         if(count($userTimers)) {
-             foreach ($userTimers as $timer) {
-                 $timer->setDateEnd(new DateTime());
-                 $tTicket = $timer->getTicket();
-                 $tTicket->setState(\CoreBundle\Model\Ticket::STATE_STOP);
-                 $this->em->persist($timer);
-                 $this->em->persist($tTicket);
-             }
- 
-         }
-         $nTimer = new TicketTime();
-         $startDate = new DateTime();
-         $nTimer->setDateStart($startDate);
-         $nTimer->setUser($user);
-         $nTimer->setTicket($ticket);
-         $ticket->setState(\CoreBundle\Model\Ticket::STATE_DOING);
-         $this->em->persist($nTimer);
-         $this->em->persist($ticket);
-         $this->em->flush();
-         $this->ticketModel->sendChangeStatusNotify($ticket);
-         $tickets = $this->em->getRepository(Ticket::class)->getByState([],[\CoreBundle\Model\Ticket::STATE_APPROVED]);
-         $ticketsArray = $this->ticketsToArray($tickets);
-         return new JsonResponse(['success' => true, 'tickets' => $ticketsArray]);
-     }
- 
-     public function timerStop(Request $request)
-     {
-         $timerId = $request->get('id');
-         $user = $this->getUser();
-         if(!$timerId || !$user) {
-             return new JsonResponse(['success' => false, 'error' => 'Не удалось остановить таймер']);
-         }
-         $timer = $this->em->getRepository(TicketTime::class)->find($timerId);
-         if(!$timer || !$timer->getTicket()->getAssigned() || $timer->getTicket()->getAssigned()->getId() != $user->getId()) {
-             return new JsonResponse(['success' => false, 'error' => 'Не удалось остановить таймер']);
-         }
-         $timer->setDateEnd(new DateTime());
-         $tTicket = $timer->getTicket();
-         $tTicket->setState(\CoreBundle\Model\Ticket::STATE_STOP);
-         $this->em->persist($timer);
-         $this->em->persist($tTicket);
-         $this->em->flush();
-         $this->ticketModel->sendChangeStatusNotify($tTicket);
-         $tickets = $this->em->getRepository(Ticket::class)->getByState([],[\CoreBundle\Model\Ticket::STATE_APPROVED]);
-         $ticketsArray = $this->ticketsToArray($tickets);
-         return new JsonResponse(['success' => true, 'tickets' => $ticketsArray]);
-     }
- 
-     public function addComment(Request $request, MailerInterface $mailer, RouterInterface $router): JsonResponse
-     {
-         $comment = $request->get('comment');
-         $ticketId = $request->get('id');
-         if(!$ticketId) {
-             return new JsonResponse(['success' => false]);
-         }
-         $ticket = $this->em->getRepository(Ticket::class)->find($ticketId);
-         if(!$ticket) {
-             return new JsonResponse(['success' => false]);
-         }
- 
-         $commentI = new TicketComment();
-         $commentI->setTicket($ticket);
-         $commentI->setUser($this->getUser());
-         $commentI->setContent($comment);
-         $commentI->setDateCreate(new DateTime());
-         $this->em->persist($commentI);
-         $this->em->flush($commentI);
- 
-         $files = $request->files->get('fileInput') ?? [];
-         foreach ($files as $file) {
-             $fileName = $this->upload($file);
-             if($fileName) {
-                 $ticketCommentFile = new TicketCommentFile();
-                 $ticketCommentFile->setFile($fileName);
-                 $ticketCommentFile->setComment($commentI);
-                 $commentI->addFile($ticketCommentFile);
-                 $this->em->persist($ticketCommentFile);
-                 $this->em->persist($commentI);
-                 $this->em->flush();
-             }
-         }
- 
-         $commentCreator = $commentI->getUser();
-         $ticketCreator = $ticket->getCreator();
-         $assigned = $ticket->getAssigned();
- 
-         $mailBody = 'К задаче <b>'.$ticket->getTitle().'</b> добавлен новый комментарий.<br><b>'.$commentCreator->getFullName().':</b> '.$comment.'<br><a href="https://admin.vidi.ua'.$this->adminPool->getAdminByAdminCode('admin.ticket')->generateUrl('show',['id' => $ticket->getId()]).'">Подробнее</a>';
-         $message = (new Email())
-             ->subject('Новый коментарий к задачи.')
-             ->from(new Address($_ENV['DEFAULT_EMAIL_FROM'], 'TicketNotify'))
-             ->html($mailBody)
-         ;
- 
-         if($commentCreator->getId() != $ticketCreator->getId()) {
-             $message->addTo($ticketCreator->getEmail());
-         }
- 
-         if($assigned && $commentCreator->getId() != $assigned->getId()) {
-             $message->addTo($assigned->getEmail());
-         }
- 
-         if ($message->getTo()){
-             $mailer->send($message);
-         }
- 
-         $comment = [
-             'user' => $commentI->getUser()->getFullName(),
-             'date' => $commentI->getDateCreate()->format('d.m.Y H:i'),
-             'content' => $commentI->getContent(),
-             'files' => [],
-         ];
- 
- 
-         if(count($commentI->getFiles())) {
-             foreach ($commentI->getFiles() as $file) {
-                 $comment['files'][] = [
-                     'name' => basename($file->getFile()),
-                     'href' => $router->generate('ticket_comment_file_download',['id' => $file->getId()])
-                 ];
-             }
-         }
-         return new JsonResponse(['success' => true, 'comment' => $comment]);
-     }
- 
-     public function init(): JsonResponse
-     {
-         $states = [
-             \CoreBundle\Model\Ticket::STATE_NEW,
-             \CoreBundle\Model\Ticket::STATE_CANCELED,
-             \CoreBundle\Model\Ticket::STATE_DONE,
-             \CoreBundle\Model\Ticket::STATE_STOP,
-             \CoreBundle\Model\Ticket::STATE_DOING,
-         ];
- 
-         $users = [];
-         $creators = [];
- 
-         $Tickets = $this->em->getRepository(Ticket::class)->getToInit($states);
-         /** @var Ticket $ticket */
-         foreach($Tickets as $ticket) {
-             $user = $ticket->getDealer();
-             $creator = $ticket->getCreator();
-             if($user) {
-                 $users[$user->getId()] = $user->getName();
-             }
-             $creators[$creator->getId()] = $creator->getFullName();
-         }
-         $ticketsResult = $this->ticketsToArray($Tickets);
- 
-         $allStates = \CoreBundle\Model\Ticket::$state;
-         foreach ($allStates as $key => $row) {
-             if(!in_array($key,$states) && $key != \CoreBundle\Model\Ticket::STATE_APPROVED) {
-                 unset($allStates[$key]);
-             }
-         }
- 
-         return new JsonResponse([
-             'userId' => $this->getUser()->getId(),
-             'userName' => $this->getUser()->getFullName(),
-             'tickets' => $ticketsResult,
-             'states' => $allStates,
-             'dealers' => $users,
-             'creators' => $creators,
-             'types' => \CoreBundle\Model\Ticket::$works,
-             'priority' => \CoreBundle\Model\Ticket::$priority,
-         ]);
-     }
- }
-