<?php
namespace App\Controller;
use App\Entity\Job;
use App\Entity\JobCheck;
use App\Entity\Project;
use App\Entity\Task;
use App\Entity\Document;
use App\Form\DocumentType;
use App\Form\TaskType;
use App\Form\TaskSearchType;
use App\Repository\ConfigurationRepository;
use App\Repository\DocumentRepository;
use App\Repository\JobRepository;
use App\Repository\ProjectRepository;
use App\Repository\TaskRepository;
use App\Repository\TierRepository;
use App\Repository\UserRepository;
use App\Service\FilActualite;
use App\Service\ThumbnailService;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Asana;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\Mime\FileinfoMimeTypeGuesser;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class TaskController extends AbstractController
{
/**
* @Route("/admin/task", name="task_index", methods={"GET","POST"})
* @Route("/api/task", name="api_task_index", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function index(PaginatorInterface $paginator, Request $request, ConfigurationRepository $configurationRepository,
TaskRepository $taskRepository, TranslatorInterface $translator, ProjectRepository $projectRepository,
TierRepository $tierRepository, UserRepository $userRepository): Response
{
$config = $configurationRepository->findOneById(1);
if (is_null($config)) {
$this->addFlash("warning", $translator->trans("Veuillez ajouter les éléments de configuration d'abord!"));
return $this->redirectToRoute('configuration_edit');
}
$client = $request->query->get('client') != '' ? $request->query->get('client') : null;
$form = $this->createForm(TaskSearchType::class, null,
['priorties' => $config->getTaskPriortiesValues(), 'status' => $config->getTaskStatusValues(), 'em' => $this->getDoctrine()->getManager(),'client' => $client]
);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$url = $this->buildSearchUrl($request->request->all());
if (!empty($url)) {
return $this->redirectToRoute('task_index', $url);
}
}
$limit = empty($request->query->get('limit')) ? 20 : $request->query->get('limit');
$tasks = $paginator->paginate(
$taskRepository->MyFindAll($request->query->all()), $request->query->getInt('page', 1), $limit
);
$nombreTask = count($taskRepository->MyFindAll($request->query->all())->getQuery()->getResult());
$nombrePage = ($nombreTask - ($nombreTask % $limit)) / $limit;
if ($nombreTask % $limit > 0) {
$nombrePage++;
}
if ($this->isApiRoute($request)) {
$resultat = [
'clients' => $this->getJsonClient($tierRepository),
'projects' => $this->getJsonProject($projectRepository),
'tasks' => $this->getJsonTasks($tasks),
'nombrePages' => $nombrePage
];
$response = new Response();
$response->setContent(json_encode($resultat));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
return $this->render('task/index.html.twig', [
'form' => $form->createView(),
'tasks' => $tasks,
'avatar_path' => $this->getParameter('app.path.avatars'),
'priorities' => $config->getTaskPriortiesValues(),
'status' => $config->getTaskStatusValues(),
'users' => $userRepository->findAll(),
'clients' => $tierRepository->findBy(['archived' => false], ['name' => 'asc']),
'projects' => $projectRepository->findBy(['archived' => false], ['name' => 'asc']),
]);
}
/**
* @Route("admin/task/new", name="task_new", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function new(Request $request, ProjectRepository $projectRepository, ConfigurationRepository $configurationRepository, TranslatorInterface $translator): Response
{
$config = $configurationRepository->findOneById(1);
if (is_null($config)) {
$this->addFlash("warning", $translator->trans("Veuillez ajouter les éléments de configuration d'abord!"));
return $this->redirectToRoute('configuration_edit');
}
$task = new Task();
$form = $this->createForm(TaskType::class, $task,
['priorties' => $config->getTaskPriortiesValues(), 'status' => $config->getTaskStatusValues(), 'em' => $this->getDoctrine()->getManager()]
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$project = $projectRepository->find($request->request->all()['task']['project']);
if ($project->getExternalService()) {
$asana = new Asana(array('personalAccessToken' => $project->getExternalService()->getKeyApi()));
$asana->getWorkspaces();
$workspaceId = $asana->getData()[0]->gid;
$projectId = $project->getIdExterne(); // The project where we want to save our task
// First we create the task
$result = $asana->createTask(array(
'workspace' => $workspaceId, // Workspace ID
'name' => $task->getName(), // Name of task
'assignee' => 'racem@nanogramme.fr', // Assign task to...
));
$taskId = $asana->getData()->gid; // Here we have the id of the task that have been created
// Now we do another request to add the task to a project
$asana->addProjectToTask($taskId, $projectId);
$task->setIdExterne($taskId);
}
$entityManager->persist($task);
$entityManager->flush();
$this->addFlash("warning", $translator->trans("Nouvelle tâche ajoutée avec succès"));
return $this->redirectToRoute('task_edit', [
'id' => $task->getId(),
]);
}
if (!$request->isXmlHttpRequest()) {
return $this->redirectToRoute('task_index', [
'a' => 'new'
]);
}
return $this->render('task/new.html.twig', [
'task' => $task,
'form' => $form->createView(),
]);
}
/**
* @Route("admin/task/new_ajax", name="new_task_ajax", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function newAjax(Request $request, TaskRepository $taskRepository, TranslatorInterface $translator): Response
{
$sub_task = $request->request->get('sub_task');
$id_parent_task = $request->request->get('parent_task');
$parent_task = $taskRepository->find($id_parent_task);
$task = clone $parent_task;
$task->setName($sub_task);
$task->setDescription('');
$task->setParent($parent_task);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($task);
$entityManager->flush();
$route_task_show = $this->get('router')->getRouteCollection()->get('task_show');
$path_task_show = str_replace('{id}', $task->getId(), $route_task_show->getPath());
$tab['path_task_show'] = $path_task_show;
$tab['task_id'] = $task->getId();
$tab['task_name'] = $task->getName();
return new Response(json_encode($tab));
}
/**
* @Route("admin/task/url_termine_task", name="url_termine_task", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function urlTermineTask(Request $request, TaskRepository $taskRepository, FilActualite $filActualite, TranslatorInterface $translator): Response
{
$task_id = $request->request->get('task_id');
$task_type = $request->request->get('task_type');
$termine = $request->request->get('termine');
$task = $taskRepository->find($task_id);
$entityManager = $this->getDoctrine()->getManager();
if (($task_type == 'principal_task' || $task_type == 'list_task') && $termine == 'oui') {
$task->setTermine(true);
foreach ($task->getChildren() as $child) {
$child->setTermine(true);
$entityManager->persist($child);
$entityManager->flush();
}
$entityManager->persist($task);
$entityManager->flush();
} elseif ($task_type == 'list_task' && $termine == 'non') {
$task->setTermine(false);
if ($task->getParent()) {
$task_parent = $task->getParent();
$task_parent->setTermine(false);
$entityManager->persist($task_parent);
$entityManager->flush();
}
$entityManager->persist($task);
$entityManager->flush();
} elseif ($task_type == 'sub_task' && $termine == 'oui') {
$task->setTermine(true);
$entityManager->flush();
} elseif ($task_type == 'sub_task' && $termine == 'non') {
$task->setTermine(false);
$parent_task = $task->getParent();
$parent_task->setTermine(false);
$entityManager->flush();
} elseif ($termine == 'non') {
$task->setTermine(false);
$entityManager->flush();
} elseif ($termine == 'oui') {
$task->setTermine(true);
$entityManager->flush();
}
$filActualite->closeReopenTask($task,$this->getUser());
return new Response('ok');
}
/**
* @Route("/task/start-new-job/{id}", name="task_start_new_job", methods={"GET"})
* @Security("is_granted('ROLE_USER')")
*/
public function TaskStartNewJob(Task $task, Request $request, TaskRepository $taskRepository, TranslatorInterface $translator, JobRepository $jobRepository): Response
{
$em = $this->getDoctrine()->getManager();
$oldJob = null;
if (is_null($task->getUser())) {
$task->setUser($this->getUser());
$em->flush();
}
$oldJob = $this->getLastJobForUser($jobRepository);
if (!is_null($oldJob)) {
$now = new \DateTime('now');
$end = new \DateTime();
$end->setTimestamp($now->getTimestamp());
$oldJob->setEnd($end);
$this->createjobCheck($em, $oldJob, []);
}
$job = $this->createJob($em, $task, $oldJob, []);
//Create JobCheck
$this->createjobCheck($em, $job, []);
$this->addFlash('success', 'Vous venez de démarrer un nouveau job sur cette tâche');
return $this->redirectToRoute('task_index', [
'a' => 'show',
'e' => $task->getId()
]);
}
/**
* @Route("/api/task/select", name="api_task_select", methods={"POST"})
*/
public function apiSelectTask(Request $request, TaskRepository $taskRepository, TranslatorInterface $translator, JobRepository $jobRepository): Response
{
$data = $request->request->all();
$em = $this->getDoctrine()->getManager();
$oldJob = null;
$task = $taskRepository->findOneById($data['task']);
if (is_null($task)) {
$response = new Response();
$response->setContent(json_encode(['Resultat' => 'NO']));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
//If check close old Job and open new Job
if (isset($data['depuis'])) {
$oldJob = $this->getLastJobForUser($jobRepository);
if (!is_null($oldJob)) {
$now = new \DateTime('now');
$end = new \DateTime();
$end->setTimestamp($now->getTimestamp() - $data['depuis']);
$oldJob->setEnd($end);
$this->createjobCheck($em, $oldJob, $data);
}
}
//create new JOB
$job = $this->createJob($em, $task, $oldJob, $data);
//Create JobCheck
$this->createjobCheck($em, $job, $data);
$response = new Response();
$response->setContent(json_encode(['task' => $task->getId(), 'job' => $job->getId()]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/api/closejob", name="api_close_job", methods={"GET"})
*/
public function apiCloseJob(Request $request, TaskRepository $taskRepository, TranslatorInterface $translator, JobRepository $jobRepository): Response
{
$data = $request->request->all();
$em = $this->getDoctrine()->getManager();
$oldJob = null;
$oldJob = $this->getLastJobForUser($jobRepository);
if (!is_null($oldJob) && is_null($oldJob->getEnd())) {
$now = new \DateTime('now');
$end = new \DateTime();
$end->setTimestamp($now->getTimestamp());
$oldJob->setEnd($end);
if (!isset($data['display_delay'])) {
$data['display_delay'] = 0;
}
if (!isset($data['window_type'])) {
$data['window_type'] = 11;
}
$this->createjobCheck($em, $oldJob, $data);
}
$response = new Response();
$response->setContent(json_encode(['result' => 'ok']));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/api/task/pause", name="api_task_pause", methods={"POST"})
*/
public
function apiPause(Request $request, JobRepository $jobRepository, TaskRepository $taskRepository, TranslatorInterface $translator): Response
{
$data = $request->request->all();
$em = $this->getDoctrine()->getManager();
$oldJob = null;
$file = __DIR__.'/../../private_documents/task.txt';
$tab = [];
if(file_exists($file)){
$tab = json_decode(file_get_contents($file),true);
}
$tab[] = $data;
file_put_contents($file,json_encode($data));
//Close old JOB
$oldJob = $this->getLastJobForUser($jobRepository);
if (is_null($oldJob)) {
$task = $taskRepository->findOneById(['user'=>$this->getUser()],['id'=>'DESC']);
$job = $this->createJob($em, $task, null, $data, false);
//Create JobCheck
$this->createjobCheck($em, $job, $data);
$response = new Response();
$response->setContent(json_encode(['task' => $task->getId(), 'job' => $job->getId()]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}elseif($oldJob->getId() != $data['job']){
$now = new \DateTime('now');
$time = $now->getTimestamp() - $oldJob->getStart()->getTimestamp();
$current = [
'Resultat' => 'OK',
'id' => $oldJob->getId(),
'jobDescription' => $oldJob->getDescription(),
'break' => ($oldJob->getBreak()) ? 'yes' : 'no',
'time' => $time,
'taskId' => $oldJob->getTask()->getId(),
'taskName' => $oldJob->getTask()->getName(),
'taskDescription' => $oldJob->getTask()->getDescription(),
'project' => is_null($oldJob->getTask()->getProject()) ? '' : $oldJob->getTask()->getProject()->getName(),
'client' => is_null($oldJob->getTask()->getClient()) ? '' : $oldJob->getTask()->getClient()->getName(),
];
$response = new Response();
$response->setContent(json_encode($current));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$now = new \DateTime('now');
$oldJob->setEnd($now);
$this->createjobCheck($em, $oldJob, $data);
$break = ($data['break'] == 'yes') ? true : false;
//create new JOB
$task = $taskRepository->findOneById($data['task']);
$job = $this->createJob($em, $task, $oldJob, $data, $break);
//Create JobCheck
$this->createjobCheck($em, $job, $data);
$response = new Response();
$response->setContent(json_encode(['task' => $task->getId(), 'job' => $job->getId()]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/api/task/new", name="api_task_new", methods={"POST"})
*/
public
function apiNew(Request $request, TranslatorInterface $translator, FilActualite $filActualite, JobRepository $jobRepository): Response
{
$data = $request->request->all();
$em = $this->getDoctrine()->getManager();
$oldJob = null;
//Created Task
$task = $this->createTask($data, $em);
$filActualite->createTask($task,$this->getUser());
//If check close old Job and open new Job
if (isset($data['depuis'])) {
$oldJob = $this->getLastJobForUser($jobRepository);
if (!is_null($oldJob)) {
$now = new \DateTime('now');
$end = new \DateTime();
$end->setTimestamp($now->getTimestamp() - $data['depuis']);
$oldJob->setEnd($end);
$this->createjobCheck($em, $oldJob, $data);
}
}
//create new JOB
$job = $this->createJob($em, $task, $oldJob, $data);
//Create JobCheck
$this->createjobCheck($em, $job, $data);
$response = new Response();
$response->setContent(json_encode(['task' => $task->getId(), 'job' => $job->getId()]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/api/jobcheck", name="api_job_check", methods={"POST"})
*/
public
function apiJobCheck(Request $request, JobRepository $jobRepository, TranslatorInterface $translator): Response
{
$data = $request->request->all();
$em = $this->getDoctrine()->getManager();
//$jobClient = $jobRepository->findOneById($data['job']);
$job = $jobRepository->findOneBy(['user' => $this->getUser(),'end'=>null], ['id' => 'desc']);
if (is_null($job)) {
$response = new Response();
$response->setContent(json_encode(['Resultat' => 'NO']));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$now = new \DateTime('now');
$time = $now->getTimestamp() - $job->getStart()->getTimestamp();
$this->createjobCheck($em, $job, $data);
$current = [
'Resultat' => 'OK',
'id' => $job->getId(),
'jobDescription' => $job->getDescription(),
'break' => ($job->getBreak()) ? 'yes' : 'no',
'time' => $time,
'taskId' => $job->getTask()->getId(),
'taskName' => $job->getTask()->getName(),
'taskDescription' => $job->getTask()->getDescription(),
'project' => is_null($job->getTask()->getProject()) ? '' : $job->getTask()->getProject()->getName(),
'client' => is_null($job->getTask()->getClient()) ? '' : $job->getTask()->getClient()->getName(),
];
$response = new Response();
$response->setContent(json_encode($current));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/api/currentjob", name="api_job_current", methods={"GET"})
*/
public
function apiCurrentJob(JobRepository $jobRepository, TranslatorInterface $translator): Response
{
$job = $jobRepository->findOneBy(['user' => $this->getUser()], ['id' => 'desc']);
if (is_null($job) or !is_null($job->getEnd())) {
$response = new Response();
$response->setContent(json_encode(['Resultat' => 'NO']));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$now = new \DateTime('now');
$time = $now->getTimestamp() - $job->getStart()->getTimestamp();
$current = [
'Resultat' => 'OK',
'id' => $job->getId(),
'jobDescription' => $job->getDescription(),
'break' => ($job->getBreak()) ? 'yes' : 'no',
'time' => $time,
'taskId' => $job->getTask()->getId(),
'taskName' => $job->getTask()->getName(),
'taskDescription' => $job->getTask()->getDescription(),
'project' => is_null($job->getTask()->getProject()) ? '' : $job->getTask()->getProject()->getName(),
'client' => is_null($job->getTask()->getClient()) ? '' : $job->getTask()->getClient()->getName(),
];
$response = new Response();
$response->setContent(json_encode($current));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/admin/task/task_search_advenced", name="task_search_advenced", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function taskSearchAdvenced(Request $request, ConfigurationRepository $configurationRepository, TranslatorInterface $translator): Response
{
$config = $configurationRepository->findOneById(1);
$task = new Task();
if (is_null($config)) {
$this->addFlash("warning", $translator->trans("Veuillez ajouter les éléments de configuration d'abord!"));
return $this->redirectToRoute('configuration_edit');
}
$form = $this->createForm(TaskSearchType::class, $task,
['priorties' => $config->getTaskPriortiesValuesSearch(), 'status' => $config->getTaskStatusValuesSearch(), 'em' => $this->getDoctrine()->getManager(), 'data' => $request->query->all()]
);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$url = $this->buildSearchUrl($request->request->all());
if (!empty($url)) {
return $this->redirectToRoute('task_index', $url);
}
}
return $this->render('task/recherche_avancer.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/admin/task/{id}", name="task_show", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function show(Task $task, ConfigurationRepository $configurationRepository, UserRepository $userRepository, Request $request,
DocumentRepository $documentRepository, ThumbnailService $thumbnailService, FilActualite $filActualite): Response
{
if (!$request->isXmlHttpRequest()) {
return $this->redirectToRoute('task_index', [
'a' => 'show',
'e' => $task->getId()
]);
}
$em = $this->getDoctrine()->getManager();
$document = new Document();
$form = $this->createForm(DocumentType::class, $document);
$form->handleRequest($request);
$documentPath = is_null($task->getProject()) ? 'x/'.$task->getId() : $task->getProject()->getId().'/'.$task->getId().'/';
if ($form->isSubmitted() && $form->isValid()) {
$data = $request->request->all();
//dump($data['document']['originalName']);exit;
$document->setTask($task);
$document->setOriginalName($data['document']['originalName']);
$em->persist($document);
$em->flush();
$thumbnailService->createThumbnail($document);
$filActualite->addFile($task,$this->getUser(),$document);
return $this->render('task/elements/documents.html.twig', [
'task' => $task,
'documentPath' => $this->getParameter("app.path.documents").$documentPath,
'imagePath' => substr($this->getParameter("app.path.documents_image"),1).$documentPath,
]);
}
$conf = $configurationRepository->findOneById(1);
return $this->render('task/show.html.twig', [
'task' => $task,
'priorities' => $conf->getTaskPriortiesValues(),
'status' => $conf->getTaskStatusValues(),
'avatar_path' => $this->getParameter('app.path.avatars'),
'users' => $userRepository->findAll(),
'cost' => $task->getDisplayDureeAndCostPerUser(),
'totaux' => $task->getTotaux(),
'conf' => $conf,
'form' => $form->createView(),
"commentaires" => $filActualite->getComments($task,$this->getUser()),
'documentPath' => $this->getParameter("app.path.documents").$documentPath,
'imagePath' => substr($this->getParameter("app.path.documents_image"),1).$documentPath,
]);
}
/**
* @Route("/admin/task/download/{name}", name="doc_download", methods={"GET"})
* @Security("is_granted('ROLE_USER')")
*/
public function downloadDoc(Document $document): Response
{
$folder = dirname(__FILE__).'/../..' . $this->getParameter('app.path.documents');
$folder .= $document->getTask()->getProject() ? $document->getTask()->getProject()->getId() : 'x';
$folder .= '/'. $document->getTask()->getId().'/';
$filename = $document->getName();
// This should return the file to the browser as response
$response = new BinaryFileResponse($folder.$filename);
// To generate a file download, you need the mimetype of the file
$mimeTypeGuesser = new FileinfoMimeTypeGuesser();
// Set the mimetype with the guesser or manually
if($mimeTypeGuesser->isGuesserSupported()){
// Guess the mimetype of the file according to the extension of the file
$response->headers->set('Content-Type', $mimeTypeGuesser->guessMimeType($folder.$filename));
}else{
// Set the mimetype of the file manually, in this case for a text file is text/plain
$response->headers->set('Content-Type', 'text/plain');
}
// Set content disposition inline of the file
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
return $response;
}
/**
* @Route("/admin/task/{id}/edit", name="task_edit", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
/*public
function edit(Request $request, Task $task, ConfigurationRepository $configurationRepository, TranslatorInterface $translator): Response
{
$config = $configurationRepository->findOneById(1);
if (is_null($config)) {
$this->addFlash("warning", $translator->trans("Veuillez ajouter les éléments de configuration d'abord!"));
return $this->redirectToRoute('configuration_edit');
}
$form = $this->createForm(TaskType::class, $task,
['priorties' => $config->getTaskPriortiesValues(), 'status' => $config->getTaskStatusValues(), 'em' => $this->getDoctrine()->getManager()]
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
$this->addFlash("warning", $translator->trans("Tâche modifiée avec succès"));
return $this->redirectToRoute('task_edit', [
'id' => $task->getId(),
]);
}
return $this->render('task/edit.html.twig', [
'task' => $task,
'form' => $form->createView(),
]);
}*/
/**
* @Route("/admin/task/{id}", name="task_delete", methods={"DELETE"})
*/
public
function delete(Request $request, Task $task, TranslatorInterface $translator): Response
{
if ($this->isCsrfTokenValid('delete' . $task->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($task);
$entityManager->flush();
$this->addFlash("success", $translator->trans("Tâche supprimée avec succès"));
}
return $this->redirectToRoute('task_index');
}
/**
* @param $data
* @return array
*/
private
function buildSearchUrl($data)
{
$tab = [];
$data = $data['task_search'];
$restriction = [];
foreach ($data as $key => $value) {
if ($value === '' or $key == '_token') {
continue;
}
if (!in_array($value, $restriction)) {
$tab[$key] = $value;
}
}
return $tab;
}
/**
* @param Request $request
* @return bool
*/
private
function isApiRoute(Request $request)
{
$route = $request->attributes->get('_route');
if (substr($route, 0, 4) === 'api_') {
return true;
}
return false;
}
private
function getJsonTasks($tasks)
{
$tab = [];
foreach ($tasks as $task) {
$tab[] = [
'id' => $task->getId(),
'name' => $task->getName(),
'priority' => $task->getPriority(),
'status' => $task->getStatus(),
'project' => is_null($task->getProject()) ? '' : $task->getProject()->getId(),
'client' => is_null($task->getClient()) ? '' : $task->getClient()->getId(),
];
}
return $tab;
}
private
function getJsonProject(ProjectRepository $projectRepository)
{
$tab = [];
$projects = $projectRepository->findAll();
foreach ($projects as $project) {
if (!$project->getArchived()) {
$tab[] = [
'id' => $project->getId(),
'name' => $project->getName(),
'client' => is_null($project->getClient()) ? '' : $project->getClient()->getId(),
];
}
}
return $tab;
}
private
function getJsonClient(TierRepository $tierRepository)
{
$tab = [];
$tiers = $tierRepository->findAll();
foreach ($tiers as $tier) {
if (!$tier->getArchived()) {
$tab[] = [
'id' => $tier->getId(),
'name' => $tier->getName(),
];
}
}
return $tab;
}
/**
* @param null $id
* @return |null
*/
private
function getProjectById($id = null)
{
if (empty($id)) {
return null;
}
$em = $this->getDoctrine()->getManager();
return $em->getRepository('App\Entity\Project')->findOneById($id);
}
/**
* @param null $id
* @return |null
*/
private
function getClientById($id = null)
{
if (empty($id)) {
return null;
}
$em = $this->getDoctrine()->getManager();
return $em->getRepository('App\Entity\Tier')->findOneById($id);
}
/**
* @return object[]
*/
private
function getLastJobForUser(JobRepository $jobRepository)
{
return $jobRepository->findOneBy(['user' => $this->getUser(),"end"=>null], ['id' => 'DESC']);
}
private
function createTask($data, EntityManager $entityManager)
{
$task = new Task();
$task->setName($data['name']);
$task->setDescription($data['description']);
$task->setClient($this->getClientById($data['client']));
$task->setProject($this->getProjectById($data['project']));
$task->setUser($this->getUser());
$entityManager->persist($task);
$entityManager->flush();
return $task;
}
private
function createJob(EntityManager $entityManager, Task $task, Job $oldJob = null, $data, $isBreak = false)
{
$job = new Job();
$job->setTask($task);
$job->setUser($this->getUser());
if (empty($data)) {
$data['jobDescription'] = '';
}
$start = !is_null($oldJob) ? $oldJob->getEnd() : new \DateTime('now');
$job->setStart($start);
$job->setDescription($data['jobDescription']);
$job->setBreak($isBreak);
$entityManager->persist($job);
$entityManager->flush();
return $job;
}
private
function createjobCheck(EntityManager $entityManager, Job $job, $data)
{
$check = new JobCheck();
$date = new \DateTime("now");
//$start = $job->getStart();
if (empty($data)) {
$data['display_delay'] = 0;
$data['window_type'] = 12;
}
$check->setUser($this->getUser());
$check->setJob($job);
$check->setClick($date);
$display = new \DateTime('now');
$display->setTimestamp($date->getTimestamp() - $data['display_delay']);
$check->setDisplay($display);
$check->setWindowType($data['window_type']);
$entityManager->persist($check);
$entityManager->flush();
return $check;
}
/**
* @Route("/save_user_task/{id}", name="save_user_task", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function saveUserTask(Task $task, UserRepository $userRepository, Request $request, FilActualite $filActualite): Response
{
$user_id = $request->request->all()['user_id'];
$user = $userRepository->find($user_id);
$task->setUser($user);
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'User');
return new Response('ok');
}
/**
* @Route("/update_status_ajax/{id}", name="update_status_ajax", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function updateStatusAjax(Task $task, Request $request, FilActualite $filActualite): Response
{
$status = $request->request->all()['status'];
$task->setStatus($status);
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'Status');
return new Response('ok');
}
/**
* @Route("/update_priority_ajax/{id}", name="update_priority_ajax", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function updatePriorityAjax(Task $task, Request $request, FilActualite $filActualite): Response
{
$priority = $request->request->all()['priority'];
$task->setPriority($priority);
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'Priority');
return new Response('ok');
}
/**
* @Route("/url_update_titre/{id}", name="url_update_titre", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function urlUpdateTitre(Task $task, Request $request, FilActualite $filActualite): Response
{
$titre = $request->request->all()['task_titre'];
$task->setName($titre);
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'Name');
return new Response('ok');
}
/**
* @Route("/url_update_description/{id}", name="url_update_description", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function urlUpdateDescription(Task $task, Request $request, FilActualite $filActualite): Response
{
$description = $request->request->all()['task_description'];
$task->setDescription($description);
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'Description');
return new Response('ok');
}
/**
* @Route("/url_update_date_echeance/{id}", name="url_update_date_echeance", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function urlUpdateDateEcheance(Task $task, Request $request, FilActualite $filActualite): Response
{
$date_ech = $request->request->all()['date_ech'];
if ($date_ech != '') {
$task->setDate(new \DateTime($date_ech));
} else {
$task->setDate(null);
}
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'Date');
return new Response('ok');
}
/**
* @Route("/url_update_client_project/{id}", name="url_update_client_project", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function urlUpdateClientProject(Task $task, Request $request, TierRepository $tierRepository, ProjectRepository $projectRepository, FilActualite $filActualite): Response
{
$oldProject = is_null($task->getProject()) ? 'x' : $task->getProject()->getId();
$data = $request->request->all();
if (isset($data['client_id'])) {
if ($data['client_id'] != 0) {
$client = $tierRepository->find($data['client_id']);
$task->setClient($client);
} else {
$task->setClient(null);
}
$task->setProject(null);
}
if (isset($data['project_id'])) {
if ($data['project_id'] != 0) {
$project = $projectRepository->find($data['project_id']);
$task->setProject($project);
} else {
$task->setProject(null);
}
}
$this->getDoctrine()->getManager()->flush();
$filActualite->modifyTask($task,$this->getUser(),'Project',$oldProject);
return new Response('ok');
}
/**
* @Route("/url_new_task_ajax", name="url_new_task_ajax", methods="GET|POST")
* @Security("is_granted('ROLE_USER')")
*/
public function newTaskAjax(Request $request, ConfigurationRepository $configurationRepository,
TierRepository $tierRepository, ProjectRepository $projectRepository,
UserRepository $userRepository, FilActualite $filActualite): Response
{
$config = $configurationRepository->find(1);
$priorities = $config->getTaskPriortiesValues();
$status = $config->getTaskStatusValues();
$task = new Task();
$data = $request->request->all();
$name_task = $data['name_task'];
$hide_col = $data['hide_col'];
if (isset($data['client']) && !empty($data['client'])) {
$client = $tierRepository->find($data['client']);
$task->setClient($client);
}
if (isset($data['project']) && !empty($data['project'])) {
$project = $projectRepository->find($data['project']);
$task->setProject($project);
$task->setClient($project->getClient());
}
if (isset($data['user']) && !empty($data['user'])) {
$user = $userRepository->find($data['user']);
$task->setUser($user);
}
$task->setName($name_task);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($task);
$entityManager->flush();
$filActualite->createTask($task,$this->getUser());
$color_border = '';
$project_name = '';
if ($task->getProject()) {
if ($task->getProject()->getColor() != '') {
$color_border = 'border-left: 3px solid ' . $task->getProject()->getColor();
}
$project_name = $task->getProject()->getName();
}
if (!$task->getUser()) {
$tab_jason['user_task'] = 'avatar_1';
} elseif ($task->getUser()->getAvatar() == '' || !file_exists(substr($this->getParameter('app.path.avatars'), 1) . $task->getUser()->getAvatar())) {
$tab_jason['user_task'] = 'avatar_2';
$tab_jason['user_task_color'] = $task->getUser()->getColor();
$tab_jason['user_task_name'] = $task->getUser()->getPrenomNom();
$tab_jason['user_task_abrv'] = $task->getUser()->getAbrev();
} else {
$tab_jason['user_task'] = 'avatar_3';
$tab_jason['user_task_avatar'] = $this->getParameter('app.path.avatars') . $task->getUser()->getAvatar();
$tab_jason['user_task_name'] = $task->getUser()->getPrenomNom();
}
if (isset($data['status']) && !empty($data['status'])) {
$tab_jason['status'] = 'status_1';
$tab_jason['status_background'] = $status[$data['status']]['background'];
$tab_jason['status_color'] = $status[$data['status']]['color'];
$tab_jason['status_value'] = $data['status'];
}else{
$tab_jason['status'] = 'status_2';
$tab_jason['status_value'] = '-';
}
if (isset($data['priority']) && !empty($data['priority'])) {
$tab_jason['status'] = 'priority_1';
$tab_jason['priority_background'] = $priorities[$data['priority']]['background'];
$tab_jason['priority_color'] = $priorities[$data['priority']]['color'];
$tab_jason['priority_value'] = $data['priority'];
}else{
$tab_jason['priority'] = 'priority_2';
$tab_jason['priority_value'] = '';
}
$tab_jason['task_id'] = $task->getId();
$tab_jason['color_border'] = $color_border;
$tab_jason['name_task'] = $task->getName();
$tab_jason['name_project'] = $project_name;
$tab_jason['hide_col'] = $hide_col;
return new Response(json_encode($tab_jason));
}
/**
* @Route("/save-comment/{id}", name="save_comment", methods="POST")
* @Security("is_granted('ROLE_USER')")
*/
public function saveComment(Request $request, Task $task, FilActualite $filActualite, UserRepository $userRepository): Response
{
$filActualite->saveComment($task, $this->getUser(), $request->request->get('comment'));
return $this->render('task/elements/commentaires.html.twig', [
'task' => $task,
'avatar_path' => $this->getParameter('app.path.avatars'),
'users' => $userRepository->findAll(),
"commentaires" => $filActualite->getComments($task,$this->getUser()),
]);
}
}