<?php
namespace App\Controller;
use App\Entity\Hours;
use App\Entity\User;
use App\Form\HoursInputType;
use App\Repository\ContractRepository;
use App\Repository\HoursRepository;
use App\Service\AirtableHelper;
use App\Service\Stats\Loader;
use Doctrine\ORM\EntityManagerInterface;
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\IsGranted;
use DateTime;
class IndexController extends AbstractController
{
#[Route('/', name: 'dashboard')]
#[IsGranted(User::ROLE_USER)]
public function index(
Request $request,
HoursRepository $hoursRepository,
AirtableHelper $airtableHelper,
Loader $loader
): Response
{
$userId = $this->getUser()->getId();
$result = $loader->load($this->getUser());
$hours = (new Hours())
->setDate(new \DateTimeImmutable());
$form = $this->createForm(HoursInputType::class, $hours, [
'projects' => $result->getProjects(),
'userId' => $userId
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$hour = $hoursRepository->findOneBy(['contract' => $hours->getContract(), 'date' => $hours->getDate()]);
if ($hour) {
$hour
->setHours($hours->getHours())
->setNote($hours->getNote())
->setStatus($hours->getStatus())
;
$data = $hour;
} else {
$data = $hours;
}
$airtableHelper->sync($data);
$projectName = $hours->getContract()->getProject()->getCompany()->getName() . ' ' . $hours->getContract()->getProject()->getName();
$message = sprintf("%d hours has been set for \"%s\" project @%s", $hours->getHours(), $projectName, $hours->getDate()->format("Y-m-d"));
$this->addFlash('success', $message);
return $this->redirectToRoute('dashboard');
}
$data = [
'form' => $form->createView(),
'month' => date('M'),
'year' => date('Y'),
'dataGrid' => $result,
];
return $this->render('index.html.twig', $data);
}
/**
* @Route("/write-week/{date}", name="writeWeek")
* @IsGranted("ROLE_USER")
*/
public function writeWeek(
string $date,
EntityManagerInterface $entityManager,
ContractRepository $contractRepository,
HoursRepository $hoursRepository,
AirtableHelper $airtableHelper
): Response
{
$dObj = new DateTime($date);
$userId = $this->getUser()->getId();
$contracts = $hoursRepository->getContractHours($userId, $dObj);
foreach ($contracts as $cData) {
if ($cData['hour_id']) {
$hour = $hoursRepository->find($cData['hour_id']);
} else {
$contract = $contractRepository->find($cData['contract_id']);
$hour = (new Hours())
->setContract($contract)
->setHours(0)
->setDate($dObj);
}
$hour->setStatus(Hours::STATUS_CLOSED);
$airtableHelper->sync($hour);
}
$this->addFlash('success', $dObj->format('Y-m-d'));
return $this->redirectToRoute('dashboard');
}
}