<?php
namespace App\Controller;
use App\Entity\AbsenceCounter;
use App\Entity\AbsenceCounterTeam;
use App\Entity\Client\Client;
use App\Entity\Collaborator;
use App\Entity\DeliveryAddress;
use App\Entity\Inventory\InventoryOrder;
use App\Entity\Inventory\InventoryStock;
use App\Entity\Invoicing\Credit;
use App\Entity\Invoicing\Invoice;
use App\Entity\Opportunity\Activity;
use App\Entity\Opportunity\Opportunity;
use App\Entity\Project\Project;
use App\Entity\Project\Task;
use App\Entity\RH\Absence;
use App\Entity\RH\Expense;
use App\Entity\Supplier\SupplierCommand;
use App\Manager\Inventory\InventoryOrderManager;
use App\Manager\RH\ScoreManager;
use App\Repository\Supplier\SupplierCommandRepository;
use App\Repository\Supplier\SupplierShippingNotificationRepository;
use App\Utils\ClassUtils;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Component\Yaml\Yaml;
use Translation\Bundle\Catalogue\CatalogueFetcher;
use Translation\Bundle\Catalogue\CatalogueManager;
use Translation\Bundle\Model\CatalogueMessage;
use Translation\Bundle\Service\CacheClearer;
use Translation\Bundle\Service\ConfigurationManager;
class DefaultController extends AbstractController
{
/**
* @Route("/", name="app_homepage")
*/
public function index(ScoreManager $manager, SupplierCommandRepository $supplierCommandRepository, SupplierShippingNotificationRepository $notifRepo): Response
{
$myCollab = $this->getUser()->getCollaborator();
$total_collab = $manager->getRepository(Collaborator::class)->countEnabled();
$total_absence = $manager->getRepository(Absence::class)->countInFuture($myCollab);
$total_expense_report = $manager->getRepository(Expense::class)->totalByYearAndCollab($myCollab);
$today_absences = $manager->getRepository(Absence::class)->getByCollaboratorAndDay(date('Ymd'), null, [Absence::VALID]);
$collab_to_deleg = $manager->getRepository(Collaborator::class)->getMyDelegationsForToday($myCollab);
$hasDelegation = $manager->getRepository(Collaborator::class)->hasDelegateForToday($myCollab);
$opportunities = $manager->getRepository(Opportunity::class)->findMyOpportunitiesNotClosed($myCollab);
$activities = $manager->getRepository(Activity::class)->findMyActivities($myCollab);
$commandsToReview = $supplierCommandRepository->findBy(['reviewer' => $this->getUser()->getCollaborator(), 'status' => SupplierCommand::COMMAND_REVIEW]);
$demandsToReview = $supplierCommandRepository->findBy(['reviewer' => $this->getUser()->getCollaborator(), 'demandStatus' => SupplierCommand::DEMAND_REVIEW]);
$shippingNotifications = $notifRepo->findBy(['collaborator' => $this->getUser()->getCollaborator(), 'hasBeenSeen' => false]);
$commandToValidate = null;
if($this->isGranted('ROLE_ADMIN')) {
$commandToValidate = $supplierCommandRepository->findBy(['status' => SupplierCommand::COMMAND_AWAIT_VALID]);
$commandToValidate = count($commandToValidate) > 0 ? $commandToValidate : null;
}
return $this->render('default/index.html.twig', [
'total_collab' => $total_collab,
'total_absence' => $total_absence,
'total_expense_report' => $total_expense_report,
'today_absences' => $today_absences,
'activities' => $activities,
'collab_to_deleg' => $collab_to_deleg,
'hasDelegation' => $hasDelegation,
'opportunities' => $opportunities,
'restToScored' => $manager->getJaugeCollab(),
'holidays' => array_map(function ($date) {
return $date->format('Ymd');
}, ClassUtils::getPublicHolidays(null, false)),
'commandsToReview' => count($commandsToReview) > 0 ? $commandsToReview : null,
'demandsToReview' => count($demandsToReview) > 0 ? $demandsToReview : null,
'commandToValidate' => $commandToValidate,
'shippingNotifications' => count($shippingNotifications) > 0 ? $shippingNotifications : null,
'orders_to_prepare' => $manager->getRepository(InventoryOrder::class)->getToPrepare($this->getUser()->getCollaborator()),
'orders_blocked' => $manager->getRepository(InventoryOrder::class)->getBlocked($this->getUser()->getCollaborator()),
'orders_prepared' => $manager->getRepository(InventoryOrder::class)->getPrepared($this->getUser()->getCollaborator()),
'stocks_to_valid'=> $manager->getRepository(DeliveryAddress::class)->getStocksToValidate($this->getUser()->getCollaborator()),
]);
}
/**
* @Route("/tableau-de-bord-ca", name="dashboard_ca")
*/
public function dashboard_ca(EntityManagerInterface $em): Response
{
if(!$this->getUser()->getCollaborator()->getViewFinancialDashboard())
{
$this->addFlash('danger', 'Vous n\'avez pas les droits pour accéder à cette page');
return $this->redirectToRoute('app_homepage');
}
return $this->render('default/dashboard_ca.html.twig', [
'clients'=>$em->getRepository(Client::class)->findBy(['enabled'=>true])
]);
}
/**
* @Route("/stat_ca", name="app_dashboard_stat_ca", options={"expose"=true})
*/
public function statCaAction(Request $request,EntityManagerInterface $em)
{
$format_cas=[];
$total_ca=0;
//period1
list($start,$end)=explode(' - ',$request->request->get('period1'));
$start=\DateTime::createFromFormat('d/m/Y',$start);
$end=\DateTime::createFromFormat('d/m/Y',$end);
$cas=$em->getRepository(Invoice::class)->findCAByMonth($start,$end,$request->request->get('client'));
$cas=$em->getRepository(Credit::class)->findCAByMonth($start,$end,$cas,$request->request->get('client'));
foreach ($cas as $key=>$ca){
$total_ca+=$ca;
$month=new \DateTime($key.'01');
$format_cas[$month->format('m/Y')]=$ca;
}
return $this->render(
'default/stat_ca.html.twig',
[
'statsCa'=>json_encode($format_cas),
'total_ca'=>$total_ca,
/*'statsCa2'=>json_encode($format_cas2),
'total_ca2'=>$total_ca2,
'is_compare'=> $request->request->get('year_compare'),*/
]
);
}
/**
* @Route("/comming_soon", name="to_do")
* @Route("/purchases/comming_soon", name="to_do_supplier")
*/
public function toDo(): Response
{
return $this->render('default/to_do.html.twig', [
'controller_name' => 'DefaultController',
]);
}
/**
* @Route("/clearTrad", name="admin_clear_trad", methods={"GET","POST"},options={"expose"=true})
* @IsGranted("ROLE_ADMIN")
*/
public function clearTrad(Request $request, CacheClearer $cacheClearer)
{
$cacheClearer->clearAndWarmUp($request->getLocale());
return $this->redirect($request->headers->get('referer'));
}
/**
* @Route("/public/translation.js", name="translation_js")
*/
public function translationJs(Request $request,$projectDir, ConfigurationManager $configurationManager,CatalogueManager $catalogueManager,CatalogueFetcher $catalogueFetcher)
{
$config = $configurationManager->getConfiguration();
// Get a catalogue manager and load it with all the catalogues
$catalogueManager->load($catalogueFetcher->getCatalogues($config));
$locale = $request->getLocale();
/** @var CatalogueMessage[] $messages */
$messages = $catalogueManager->getMessages($locale, 'messages');
\usort($messages, function (CatalogueMessage $a, CatalogueMessage $b) {
return \strcmp($a->getKey(), $b->getKey());
});
$messages_format=[];
foreach ($messages as $message){
$messages_format[$message->getKey()]=$message->getMessage();
}
/*
$file = $projectDir.'/translations/messages.'.$locale.'.xlf';
$parsed = XliffFileLoader::parse(file_get_contents($file));*/
$translations = $this->renderView(
'translation/translation.js.twig',
array(
'json' => json_encode($messages_format)
)
);
return new Response($translations, 200,
array('Content-Type' => 'text/javascript')
);
}
// /**
// * @Route("/", name="old_app_homepage")
// */
// public function old_index(): Response
// {
//
// //$total_collab=$this->getDoctrine()->getRepository(Collaborator::class)->countEnabled();
// $total_absence=$this->getDoctrine()->getRepository(Absence::class)->countInFuture($this->getUser()->getCollaborator());
// $total_expense_report=$this->getDoctrine()->getRepository(Expense::class)->totalByYearAndCollab($this->getUser()->getCollaborator());
// $today_absences=$this->getDoctrine()->getRepository(Absence::class)->getByCollaboratorAndDay(date('Ymd'),null,[Absence::VALID,Absence::PENDING]);
// $tasks=$this->getDoctrine()->getRepository(Task::class)->findMyTasks($this->getUser()->getCollaborator());
//
// $collab_to_deleg=$this->getDoctrine()->getRepository(Collaborator::class)->getMyDelegationsForToday($this->getUser()->getCollaborator());
// $hasDelegation=$this->getDoctrine()->getRepository(Collaborator::class)->hasDelegateForToday($this->getUser()->getCollaborator());
//
// $absenceCounter=$this->getDoctrine()->getRepository(AbsenceCounter::class)->findOneBy(['name'=>'Jours de repos']);
//
// /*$total_working_days=$this->getUser()->getCollaborator()->getWorkingDayCount();
// $holidays=ClassUtils::getWorkingDays();
// $total_working_days-=$holidays;*/
//
// if ($absenceCounter){
//
// $counterCollab=$this->getDoctrine()->getRepository(AbsenceCounterTeam::class)->getByPeriodAndCollabAndReason(date('Y'),$this->getUser()->getCollaborator(),null,$absenceCounter);
// if($counterCollab){
// $pris_today=$this->getDoctrine()->getRepository(Absence::class)->getSoldeCongesByCollaborator($counterCollab);
//
// $planned=$this->getDoctrine()->getRepository(Absence::class)->getSoldeCongesByCollaborator($counterCollab,'planned');
// $planned+=$this->getDoctrine()->getRepository(Absence::class)->getSoldeCongesByCollaborator($counterCollab,'planned_a_cheval');
// $solde_today=$counterCollab->getDefaultValue()-$pris_today;
//
// //$total_working_days+=$solde_today-$planned;
//
// }
//
// }
//
// return $this->render('default/index.html.twig', [
// //'total_collab' => $total_collab,
// 'total_absence' => $total_absence,
// 'total_expense_report' => $total_expense_report,
// 'today_absences'=>$today_absences,
// 'tasks'=>$tasks,
// 'collab_to_deleg'=>$collab_to_deleg,
// 'hasDelegation'=>$hasDelegation,
// //"total_working_days"=>$total_working_days
// ]);
// }
/**
* @Route("/inventory/order/pdf/{publicToken}", name="inventory_order_preview_pdf", methods={"GET","POST"}, options={"expose"=true}, defaults={"id" = null})
*/
public function previewPdf(InventoryOrderManager $manager, string $publicToken)
{
$inventoryOrder = $manager->getEntityManager()->getRepository(InventoryOrder::class)->findOneBy(['publicToken' => $publicToken]);
if($inventoryOrder === null) {
throw new AccessDeniedException('The token is invalid.');
}
if($inventoryOrder->getNum() === null) {
$this->addFlash('danger','fichier inexistant ou pas encore généré en pdf');
return $this->redirectToRoute("inventory_order_index");
}
if ($this->isGranted('ROLE_COLLAB'))
{
$manager->generatePdf($inventoryOrder);
}
$file = $manager->getPdfPath($inventoryOrder);
$response = new BinaryFileResponse($file);
return $response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$inventoryOrder->getNum().'.pdf'
);
}
}