<?php
namespace App\Controller;
use App\Document\Agent;
use App\Document\Assignment;
use App\Document\Flight;
use App\Document\HomepageChecklist;
use App\Document\HomepageNote;
use App\Document\LgoEvent;
use App\Document\LgoEventCalendar;
use App\Document\LgoEventStatus;
use App\Document\LocalAirport;
use App\Document\Location;
use App\Document\Pole;
use App\Document\Supplier;
use App\Document\Tracking;
use App\Entity\AppParameter;
use App\Service\TrackingService;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
/**
* @IsGranted("ROLE_ADMIN")
*/
class CalendarController extends AbstractController
{
/**
* @Route("/", name="app_root")
*/
public function index(): Response
{
return $this->redirectToRoute('app_homepage');
}
/**
* @Route("/calendar", name="app_calendar")
*/
public function calendar(DocumentManager $manager, Request $request, SessionInterface $session, TrackingService $trackingService, EntityManagerInterface $entityManager): Response
{
$start = new \DateTime(date('Y-m-d'));
$end = new \DateTime(date('Y-m-d')." 23:59");
$statusCategories = ["A VENIR", "EN COURS", "TERMINE"];
if($request->get("displayMode")){
$displayMode = $request->get("displayMode");
$session->set("displayMode", $displayMode);
} else {
if($session->get("displayMode")) {
$displayMode = $session->get("displayMode");
} else {
$displayMode = "agenda";
}
}
if($request->get("displayView")){
$displayView = $request->get("displayView");
$session->set("displayView", $displayView);
} else {
if($session->get("displayView")) {
$displayView = $session->get("displayView");
} else {
$displayView = "timeline1";
}
}
if($request->get("date")){
$start = new \DateTime($request->get("date"));
$end = new \DateTime($request->get("date")." 23:59");
}
if($request->get("idEvent")){
$session->set('lastShownEventId', $request->get("idEvent") );
}
$lgoEventCalendars = $manager->getRepository(LgoEventCalendar::class)->findBy([], ["position" => "ASC"]);
if($request->get("calendar")){
$checkedCalendarIds = $request->get("calendar");
$session->set("checkedCalendarIds", $checkedCalendarIds);
} else {
if($session->get("checkedCalendarIds")){
$checkedCalendarIds = $session->get("checkedCalendarIds");
} else {
$checkedCalendarIds = [];
foreach($lgoEventCalendars as $calendar){
if($calendar->getName() != "MASQUES" AND $calendar->getName() != "RESAS NON CONFIRMEES"){
$checkedCalendarIds[] = $calendar->getId();
}
}
}
}
if($request->get("airport")){
$checkedAirportsCodes = $request->get("airport");
$session->set("checkedAirportsCodes", $checkedAirportsCodes);
} else {
if($session->get("checkedAirportsCodes")){
$checkedAirportsCodes = $session->get("checkedAirportsCodes");
} else {
$checkedAirportsCodes = ["AUTRE","SBH","SXM","SJU","PTP", "ANU", "AXA"];
}
}
if($request->get("statusCategory")){
$checkedStatutCategories2 = $request->get("statusCategory");
$session->set("checkedStatutCategories", $checkedStatutCategories2);
} else {
if($session->get("checkedStatutCategories")){
$checkedStatutCategories2 = $session->get("checkedStatutCategories");
} else {
$checkedStatutCategories2 = $statusCategories;
}
}
$vipSuppliers = $manager->getRepository(Supplier::class)->findBy(["isVipSupplier" => true]);
// if($request->get("vipSupplier")){
// $checkedVipSuppliers2 = $request->get("vipSupplier");
// $session->set("checkedVipSuppliers", $checkedVipSuppliers2);
// } else {
// if($session->get("checkedVipSuppliers")){
// $checkedVipSuppliers2 = $session->get("checkedVipSuppliers");
// } else {
// $checkedVipSuppliers2 = $vipSuppliers;
// foreach($vipSuppliers as $vipSupplier){
// $checkedVipSuppliers2[] = $vipSupplier->getId();
// }
// }
// }
#----
$checkedCalendars = [];
foreach($lgoEventCalendars as $calendar){
if(in_array($calendar->getId(), $checkedCalendarIds)){
$checkedCalendars[] = $calendar;
}
}
#----
$localAirports = $manager->getRepository(LocalAirport::class)->findBy([], ["id" => "ASC"]);
$checkedAirports = [];
foreach($localAirports as $airport){
if(in_array($airport->getIataCode(), $checkedAirportsCodes)){
$checkedAirports[] = $airport;
}
}
#----
$checkedStatutCategories = [];
$checkedStatutCategoriesObjects = [];
foreach($statusCategories as $statusCategory){
if(in_array($statusCategory, $checkedStatutCategories2)){
$checkedStatutCategories[] = $statusCategory;
foreach($manager->getRepository(LgoEventStatus::class)->findBy(["category" => $statusCategory]) as $lgoEventStatus){
$checkedStatutCategoriesObjects[] = $lgoEventStatus;
}
}
}
#----
// $checkedVipSuppliers = [];
// $checkedVipSuppliersObjects = [];
// foreach($vipSuppliers as $vipSupplier){
// if(in_array($vipSupplier->getId(), $checkedVipSuppliers2)){
// $checkedVipSuppliers[] = $vipSupplier->getId();
// $checkedVipSuppliersObjects[] = $vipSupplier;
// }
// }
$checkedVipSuppliers = null;
if($this->getUser()->getUserIdentifier()){
if($this->getUser()->getUserIdentifier() == "VIP EASYWAY"){
$checkedVipSuppliers = $manager->getRepository(Supplier::class)->findOneBy(["name" => "HALLEY AVIATION - HA"]);
}
}
#----
$nextDate = clone $start;
$nextDate->add(new \DateInterval('P1D'));
$prevDate = clone $start;
$prevDate->sub(new \DateInterval('P1D'));
$flights = $manager->getRepository(Flight::class)->findByDateAndAirport($start,$checkedAirports);
$events = $manager->getRepository(LgoEvent::class)->findByDate($start,null, $checkedCalendars, $flights, $checkedStatutCategoriesObjects, $checkedVipSuppliers);
#$events = $manager->getRepository(LgoEvent::class)->findByDate($start,$end);
#$events = $manager->getRepository(LgoEvent::class)->findByDate($start,null, $checkedCalendars);
/**@var \App\Entity\LgoEvent $event */
$selectedEvents = [];
foreach($events as $event){
if($event->getBooking()){
if($event->getBooking()->getStatus()->getLabel() != 'Request'){
$selectedEvents[] = $event;
}
} else {
$selectedEvents[] = $event;
}
}
#--- Remove events if airport is not in airport filter ---
// $selectedEventsAfterAirportFilter = [];
// foreach ($selectedEvents as $event){
// if($event->getFlight() AND $event->getFlight()->getAirport() AND in_array($event->getFlight()->getAirport()->getIataCode(), $checkedAirportsCodes)){
// $selectedEventsAfterAirportFilter[] = $event;
// } elseif($event->getFlight() == null){ /* For Handling events */
// $selectedEventsAfterAirportFilter[] = $event;
// }
// }
#--- Remove events if status is not in status filter ---
// $selectedEventsAfterStatusFilter = [];
// foreach ($selectedEventsAfterAirportFilter as $event){
// if($event->getStatus() AND in_array($event->getStatus()->getCategory(), $checkedStatutCategories2)){
// $selectedEventsAfterStatusFilter[] = $event;
// }
// }
#-------
if($start->format("Ymd") < date('Ymd')){
$agents = $manager->getRepository(Agent::class)->findAll();
} else {
$agents = $manager->getRepository(Agent::class)->findBy(["isActive" => 1]);
}
$planningAgent = [];
foreach($events as $event){
$agentNumbers = $event->getAgents()->count();
if($agentNumbers > 0){
foreach($event->getAgents() as $agent){
$planningAgent[$agent->getId()][] = $event;
}
} else {
$planningAgent[0][] = $event;
}
}
$listAgentAffectation = [];
$listAgentAffectation[0] = "NON AFFECTE";
foreach($agents as $agent){
$listAgentAffectation[$agent->getId()] = $agent->getLastName().' '.$agent->getFirstName();
}
/**@var \App\Document\LgoEvent $event */
$planningSupplier = [];
foreach($events as $event){
if($event->getFlight()){
if($event->getFlight()->getSupplier()){
$planningSupplier[$event->getFlight()->getSupplier()->getId()][] = $event;
}
}
if($event->getConnectingFlight()){
if($event->getConnectingFlight()->getSupplier()){
$planningSupplier[$event->getConnectingFlight()->getSupplier()->getId()][] = $event;
}
}
}
$tailsNumbers = [];
$tailsNumbersPerSupplier = [];
$suppliers = $manager->getRepository(Supplier::class)->findAll();
foreach($suppliers as $supplier){
foreach($supplier->getTailNumbers() as $tail){
$tailsNumbers[$tail] = $supplier->getName();
}
}
ksort($tailsNumbers);
#--- Used to open last displayed Event Canvas-
$lastShownEventId = null;
if($request->get('lastShownEventId')){
$lastShownEventId = $request->get('lastShownEventId');
}
if($session->get('lastShownEventId')){
$lastShownEventId = $session->get('lastShownEventId');
$session->set('lastShownEventId', null );
}
#-----
$lastSyncParameter = $entityManager->getRepository(AppParameter::class)->findOneBy(["name" => "LAST_LGS_SYNC"]);
$lastSyncDate = new \DateTime($lastSyncParameter->getValue());
// $dateInterval = $lasySyncDate->diff(new \DateTime());
// if($dateInterval->i > 10){
// $lastSyncMessage = 'Dernière syn'
// };
/*foreach($selectedEvents as $event){
if($event->getIdLgs() == 29268){
dump($event);
}
}
dd($selectedEvents);*/
$firstDayOfMonth = clone $start;
$firstDayOfMonth = $firstDayOfMonth->modify('first day of this month');
$firstDayOfCalendar = clone $firstDayOfMonth;
$firstDayOfCalendar = $firstDayOfCalendar->modify('Monday this week');
$lastDayOfMonth = clone $start;
$lastDayOfMonth = $lastDayOfMonth->modify('last day of this month');
$lastDayOfCalendar = clone $lastDayOfMonth;
$lastDayOfCalendar = $lastDayOfCalendar->modify('Sunday this week');
$datesArray = [];
$tempDate = clone $firstDayOfCalendar;
while($tempDate <= $lastDayOfCalendar){
$datesArray[] = new \DateTime($tempDate->format('Y-m-d'));
$tempDate->add(new \DateInterval('P1D'));
}
$prevMonth = clone $firstDayOfMonth;
$prevMonth->modify('first day of last month');
$nextMonth = clone $lastDayOfMonth;
$nextMonth->modify("tomorrow");
return $this->render('admin/calendar/index.html.twig', [
'date' => $start->format('Y-m-d'),
'events' => $selectedEvents,
'nextDate' => $nextDate,
'prevDate' => $prevDate,
'agents' => $agents,
'lgoEventCalendars' => $lgoEventCalendars,
'localAirports' => $localAirports,
'checkedCalendars' => $checkedCalendars,
'checkedAirports' => $checkedAirports,
#'checkedVipSuppliers' => $checkedVipSuppliers,
'allEventStatus' => $manager->getRepository(LgoEventStatus::class)->findAll(),
'allCalendars' => $manager->getRepository(LgoEventCalendar::class)->findBy([], ["position" => "ASC"]),
'allLocations' => $manager->getRepository(Location::class)->findBy([], ["name" => "ASC"]),
'planningAgent' => $planningAgent,
'listAgentAffectation' => $listAgentAffectation,
'displayMode' => $displayMode,
'displayView' => $displayView,
'tailsNumbers' => $tailsNumbers,
'allSuppliers' => $manager->getRepository(Supplier::class)->findBy([],["name"=>"ASC"]),
'planningSupplier' => $planningSupplier,
'trackings' => $trackingService->getAllTrackings($start),
'statusCategories' => $statusCategories,
'checkedStatutCategories' => $checkedStatutCategories,
'lastShownEventId' => $lastShownEventId,
'lastSyncDate' => $lastSyncDate,
'vipSuppliers' => $vipSuppliers,
'datesArray' => $datesArray,
'prevMonth' => $prevMonth,
'nextMonth' => $nextMonth,
]);
}
/**
* @Route("/reconfirmation", name="app_lgo_reconfirmation", methods={"GET"})
*/
public function reconfirmation(DocumentManager $manager, Request $request, SessionInterface $session, TrackingService $trackingService, EntityManagerInterface $entityManager): Response
{
$start = new \DateTime(date('Y-m-d'));
$end = new \DateTime(date('Y-m-d')." 23:59");
if($request->get("date")){
$start = new \DateTime($request->get("date"));
$end = new \DateTime($request->get("date")." 23:59");
}
#----
$nextDate = clone $start;
$nextDate->add(new \DateInterval('P1D'));
$prevDate = clone $start;
$prevDate->sub(new \DateInterval('P1D'));
/**@var LgoEvent $event **/
$selectedEvents = new ArrayCollection();
$calendars = $manager->getRepository(LgoEventCalendar::class)->findBy([], ["position" => "ASC"]);
$calendars = new ArrayCollection($calendars);
$calendars->removeElement($manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "ANNULE"]));
$calendars->removeElement($manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "MASQUES"]));
$calendars->removeElement($manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "RESAS NON CONFIRMEES"]));
//-- removed because should be grouped with arrival / departures --
$calendars->removeElement($manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "ARRIVEES JET"]));
$calendars->removeElement($manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "DEPARTS JET"]));
$type = "tousSaufHandling";
if($request->get('type')){
$type = $request->get('type');
}
if($type == "handling"){
$calendars = $manager->getRepository(LgoEventCalendar::class)->findBy(["name" => "HANDLING"]);
} else {
$calendars->removeElement($manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "HANDLING"]));
}
foreach($calendars as $calendar){
if($calendar->getName() == "ARRIVEES"){
$selectedCalendars = [$calendar, $manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "ARRIVEES JET"])];
} elseif($calendar->getName() == "DEPARTS"){
$selectedCalendars = [$calendar, $manager->getRepository(LgoEventCalendar::class)->findOneBy(["name" => "DEPARTS JET"])];
} else {
$selectedCalendars = [$calendar];
}
$flights = $manager->getRepository(Flight::class)->findByDateAndAirport($start);
$events = $manager->getRepository(LgoEvent::class)->findByDate($start, $end, $selectedCalendars, $flights);
foreach ($events as $event) {
$selectedEvents->add($event);
}
}
#--- SEARCH IN CONTACT OR LOCATION ---
if($request->get("search")){
$search = strtolower($request->get("search"));
foreach($selectedEvents as $event){
$keepInArray = false;
#-- LOCATION --
if($event->getLocations()){
foreach($event->getLocations() as $location){
if(str_contains(strtolower($location->getName()), $search)){
$keepInArray = true;
}
}
}
#-- CONTACT --
if($event->getBooking()){
if(str_contains(strtolower($event->getBooking()->getContactFreeText()), $search)) {
$keepInArray = true;
}
if($event->getBooking()->getLocalContact()){
if(str_contains(strtolower($event->getBooking()->getLocalContact()->getName()), $search)){
$keepInArray = true;
}
}
}
#-- REMOVE FROM ARRAY --
if($keepInArray == false){
$selectedEvents->removeElement($event);
}
}
}
return $this->render('admin/calendar/reconfirmation.html.twig', [
'date' => $start->format('Y-m-d'),
'events' => $selectedEvents,
'nextDate' => $nextDate,
'prevDate' => $prevDate,
'calendars' => $calendars,
]);
}
/**
* @Route("/mini-calendar/{date}", name="app_calendar_mini")
*/
public function miniCalendar($date, Request $request): Response
{
$date = new \DateTime($date);
$firstDayOfMonth = clone $date;
$firstDayOfMonth = $firstDayOfMonth->modify('first day of this month');
$firstDayOfCalendar = clone $firstDayOfMonth;
$firstDayOfCalendar = $firstDayOfCalendar->modify('Monday this week');
$lastDayOfMonth = clone $date;
$lastDayOfMonth = $lastDayOfMonth->modify('last day of this month');
$lastDayOfCalendar = clone $lastDayOfMonth;
$lastDayOfCalendar = $lastDayOfCalendar->modify('Sunday this week');
$datesArray = [];
$tempDate = clone $firstDayOfCalendar;
while($tempDate <= $lastDayOfCalendar){
$datesArray[] = new \DateTime($tempDate->format('Y-m-d'));
$tempDate->add(new \DateInterval('P1D'));
}
$prevMonth = clone $firstDayOfMonth;
$prevMonth->modify('first day of last month');
$nextMonth = clone $lastDayOfMonth;
$nextMonth->modify("tomorrow");
return $this->render('admin/calendar/mini-calendar.html.twig', [
'date' => $date,
'datesArray' => $datesArray,
'prevMonth' => $prevMonth,
'nextMonth' => $nextMonth,
]);
}
/**
* @Route("/homepage", name="app_homepage")
*/
public function homepage(Request $request, DocumentManager $manager): Response
{
$date = new \DateTime(date('Y-m-d'));
if($request->get("date")){
$date = new \DateTime($request->get("date"));
}
$end = clone $date;
$end->setTime(23,59);
$events = $manager->getRepository(LgoEvent::class)->findByDate($date, $end);
$otherEvents = [];
$missingBagsEvents = [];
$extras = [];
$indicators = [];
$indicators["ARRIVALS"] = 0;
$indicators["DEPARTURES"] = 0;
$indicators["HANDLINGS"] = 0;
$lastMinuteEvents = [];
/**@var \App\Document\LgoEvent $event **/
foreach($events as $event){
if($event->isIsCancelled() === false){
if($event->getCalendar()){
$name = $event->getCalendar()->getName();
if($name == "ARRIVEES" OR $name == "ARRIVEES JET"){
$indicators["ARRIVALS"]++;
} elseif($name == "DEPARTS" OR $name == "DEPARTS JET") {
$indicators["DEPARTURES"]++;
} elseif($name == "HANDLING") {
$indicators["HANDLINGS"]++;
} elseif($name == "AUTRE"){
if($event->isMissingBag()){
$missingBagsEvents[] = $event;
} else {
$otherEvents[] = $event;
}
}
}
foreach($event->getServiceItems() as $serviceItem){
if($serviceItem->getService()->isIsExtra()){
$extras[] = $serviceItem;
}
}
if($event->getBooking()){
if($event->getBooking()->getCreatedAt()->format("Y-m-d") == date('Y-m-d')){
$lastMinuteEvents[] = $event;
}
}
}
}
$checklist = $manager->getRepository(HomepageChecklist::class)->findOneBy(["date" => $date]);
if(!$checklist){
$checklist = new HomepageChecklist();
$checklist->setDate($date);
$manager->persist($checklist);
$manager->flush();
}
#---- PLANNING / POLES ----
$poles = $manager->getRepository(Pole::class)->findBy([], ["position" => "ASC"]);
$assignmentsPole = [];
foreach($poles as $pole){
$assignmentsPole[$pole->getId()] = [];
$assignments = $manager->getRepository(Assignment::class)->findByCriterias($date, $end, $pole);
$assignmentsPole[$pole->getId()] = $assignments->toArray();
}
$poleDemandesOff = $manager->getRepository(Pole::class)->findOneBy(["name" => "Demande Off"]);
$assignmentsDemandesOff = $manager->getRepository(Assignment::class)->findBy(["pole" => $poleDemandesOff]);
#---- ESPACE PERSO ----
$myAgent = $manager->getRepository(Agent::class)->findOneBy(["idLgs" => $this->getUser()->getUserIdentifier()]);
$myAssignmentsDemandesOff = $manager->getRepository(Assignment::class)->findBy(["pole" => $poleDemandesOff, "agent" => $myAgent ]);
return $this->render('admin/calendar/homepage.html.twig', [
'date' => $date,
'indicators' => $indicators,
'otherEvents' => $otherEvents,
'extras' => $extras,
'missingBagsEvents' => $missingBagsEvents,
'lastMinuteEvents' => $lastMinuteEvents,
'checklist' => $checklist,
'homepageNotes' => $manager->getRepository(HomepageNote::class)->findBy(["date" => $date]),
'agents' => $manager->getRepository(Agent::class)->findBy(["isActive" => true], ["firstname" => "ASC", "lastname" => "ASC"]),
'poles' => $poles,
'assignmentsPole' => $assignmentsPole,
'assignmentsDemandesOff' => $assignmentsDemandesOff,
'myAssignmentsDemandesOff' => $myAssignmentsDemandesOff,
]);
}
/**
* @Route("/homepage/add-note", name="app_homepage_add_note")
*/
public function addNote(Request $request, DocumentManager $manager): Response
{
$note = new HomepageNote();
$note->setNote($request->get("note"));
$note->setDate(new \DateTime($request->get("date")));
$manager->persist($note);
$manager->flush();
return $this->redirectToRoute('app_homepage', ["date" => $note->getDate()->format("Y-m-d")]);
}
/**
* @Route("/homepage/delete-note/{id}", name="app_homepage_delete_note")
*/
public function deleteNote($id, Request $request, DocumentManager $manager): Response
{
$note = $manager->getRepository(HomepageNote::class)->find($id);
$manager->remove($note);
$manager->flush();
return $this->redirectToRoute('app_homepage', ["date" => $note->getDate()->format("Y-m-d")]);
}
/**
* @Route("/homepage/update-checklist", name="app_homepage_update_checklist")
*/
public function updateChecklist(Request $request, DocumentManager $manager): Response
{
$checklist = $manager->getRepository(HomepageChecklist::class)->find($request->get("id"));
if($checklist){
$itemName = $request->get("itemName");
if($itemName == "agent"){
$checklist->setAgent(null);
$agent = $manager->getRepository(Agent::class)->find($request->get("value"));
if($agent){
$checklist->setAgent($agent);
}
}
if($itemName == "isLgsCheckPerformed"){
$checklist->setIsLgsCheckPerformed($request->get("value"));
}
if($itemName == "isOperationCheckPerformed"){
$checklist->setIsOperationCheckPerformed($request->get("value"));
}
if($itemName == "isEmailsCheckPerformed"){
$checklist->setIsEmailsCheckPerformed($request->get("value"));
}
}
$manager->persist($checklist);
$manager->flush();
return $this->redirectToRoute('app_homepage', ["date" => $checklist->getDate()->format("Y-m-d")]);
}
}