src/Controller/RecetteController.php line 72

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Prestation;
  4. use App\Entity\Recette;
  5. use App\Entity\Paiement;
  6. use App\Repository\CategorieRepository;
  7. use App\Repository\PrestationRepository;
  8. use App\Repository\RecetteRepository;
  9. use App\Repository\TypePaiementRepository;
  10. use App\Service\RecetteService;
  11. use App\Service\TelegramService;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use IntlDateFormatter;
  14. use Psr\Log\LoggerInterface;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. class RecetteController extends AbstractController
  21. {
  22.     public function __construct(
  23.         private readonly EntityManagerInterface $entityManager,
  24.         private readonly CategorieRepository    $categorieRepository,
  25.         private readonly PrestationRepository   $prestationRepository,
  26.         private readonly RecetteRepository      $recetteRepository,
  27.         private readonly TypePaiementRepository $typePaiementRepository,
  28.         private readonly RecetteService         $recetteService,
  29.         private readonly LoggerInterface        $logger
  30.     ) {}
  31.     /**
  32.      * @throws \Exception
  33.      */
  34.     #[Route('/admin/recette/'name'app_recette'methods: ['GET'])]
  35.     public function indexByDate(Request $request): Response
  36.     {
  37.         if (!$this->isGranted('ROLE_ADMIN')) {
  38.             return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
  39.         }
  40.         $dateParam $request->query->get('date');
  41.         $date $dateParam \DateTime::createFromFormat('d/m/Y'$dateParam) : new \DateTime();
  42.         if (!$date) {
  43.             throw new \Exception("Format de date invalide.");
  44.         }
  45.         $recettes $this->recetteRepository->findByDate($date);
  46.         $total $this->recetteService->calculateTotals($date);
  47.         // Récupérer uniquement les catégories non supprimées
  48.         $categories $this->categorieRepository->findBy(
  49.             ['deleted' => false],
  50.             ['nom' => 'ASC']
  51.         );
  52.         return $this->render('admin/recette.html.twig', [
  53.             'categories' => $categories,
  54.             'recettes' => $recettes,
  55.             'totalJour' => $total['totalJour'],
  56.             'totalAcompte' => $total['totalAcompte'],
  57.             'totalEspece' => $total['totalEspece'],
  58.             'totalCarteBancaire' => $total['totalCarteBancaire'],
  59.         ]);
  60.     }
  61.     #[Route('/admin/recette/ajax'name'app_recette_ajax'methods: ['POST'])]
  62.     public function handleAjax(Request $request): Response
  63.     {
  64.         if (!$this->isGranted('ROLE_ADMIN')) {
  65.             return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
  66.         }
  67.         $data json_decode($request->getContent(), true);
  68.         $processedData $this->recetteService->processRecetteData($data);
  69.         return new JsonResponse($processedData);
  70.     }
  71.     #[Route('/admin/delete/recette/{id}'name'delete_recette'methods: ['DELETE'])]
  72.     public function deleteRecette(int $id): JsonResponse
  73.     {
  74.         if (!$this->isGranted('ROLE_ADMIN')) {
  75.             return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
  76.         }
  77.         $recette $this->recetteRepository->find($id);
  78.         if (!$recette) {
  79.             return new JsonResponse(['error' => 'Recette non trouvée'], 404);
  80.         }
  81.         $date $recette->getDate();
  82.         $this->entityManager->remove($recette);
  83.         $this->entityManager->flush();
  84.         $totals $this->recetteService->calculateTotals($date);
  85.         return new JsonResponse(['status' => 'success''totals' => $totals]);
  86.     }
  87.     #[Route('/admin/prestations/{categorieId}'name'get_prestations_by_categorie'methods: ['GET'])]
  88.     public function getPrestationsByCategorie(
  89.         int $categorieId,
  90.         PrestationRepository $prestationRepository,
  91.         CategorieRepository $categorieRepository,
  92.         EntityManagerInterface $entityManager
  93.     ): JsonResponse
  94.     {
  95.         if (!$this->isGranted('ROLE_ADMIN')) {
  96.             return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
  97.         }
  98.         // Vérifier si la catégorie existe et n'est pas supprimée
  99.         $categorie $categorieRepository->findOneBy(['id' => $categorieId'deleted' => false]);
  100.         if (!$categorie) {
  101.             return new JsonResponse(['error' => 'Catégorie non trouvée ou supprimée'], Response::HTTP_NOT_FOUND);
  102.         }
  103.         // Initialiser toutes les prestations de la catégorie
  104.         $entityManager->initializeObject($categorie->getPrestations());
  105.         // Récupérer les prestations actives de la catégorie
  106.         $prestations $categorie->getPrestations()->filter(function($prestation) {
  107.             return !$prestation->isDeleted();
  108.         })->toArray();
  109.         // Trier les prestations par prix
  110.         usort($prestations, function($a$b) {
  111.             return $a->getPrix() <=> $b->getPrix();
  112.         });
  113.         $data = [];
  114.         foreach ($prestations as $prestation) {
  115.             $data[] = [
  116.                 'id' => $prestation->getId(),
  117.                 'nom' => $prestation->getNom(),
  118.                 'prix' => $prestation->getPrix(),
  119.             ];
  120.         }
  121.         return new JsonResponse($data);
  122.     }
  123.     private const CHAT_ID_A '936988470';
  124.     private const CHAT_ID_J '1078874149';
  125.     /**
  126.      * @throws \Exception
  127.      */
  128.     #[Route('/admin/recette/send'name'send_recette'methods: ['POST'])]
  129.     public function sendTelegramNotification(Request $request): JsonResponse
  130.     {
  131.         if (!$this->isGranted('ROLE_ADMIN')) {
  132.             return new JsonResponse(['error' => 'Accès non autorisé'], Response::HTTP_FORBIDDEN);
  133.         }
  134.         $telegramService = new TelegramService($_ENV['TELEGRAM_BOT_TOKEN']);
  135.         try {
  136.             $date json_decode($request->getContent(), true)['date'];
  137.             $date $date \DateTime::createFromFormat('d/m/Y'$date) : new \DateTime();
  138.             if (!$date) {
  139.                 throw new \Exception("Format de date invalide.");
  140.             }
  141.             $recettes $this->recetteRepository->findByDate($date);
  142.             $totals $this->recetteService->calculateTotals($date);
  143.             $prestations = [];
  144.             $nombreClientes count($recettes);
  145.             $prestationCounts = [];
  146.             foreach ($recettes as $recette) {
  147.                 $prestationDetails = [];
  148.                 foreach ($recette->getPrestations() as $prestation) {
  149.                     $prestationDetails[] = $prestation->getNom();
  150.                     $prestationCounts[$prestation->getNom()] = ($prestationCounts[$prestation->getNom()] ?? 0) + 1;
  151.                 }
  152.                 $prestations[] = "- {$recette->getNomClient()} :\n  " implode("\n  "$prestationDetails);
  153.             }
  154.             $prestationPopulaire = !empty($prestationCounts) ? array_search(max($prestationCounts), $prestationCounts) : 'Aucune';
  155.             $formatter = new IntlDateFormatter('fr_FR'IntlDateFormatter::FULLIntlDateFormatter::NONE);
  156.             $dateFormatee $formatter->format($date);
  157.             $dateFormatee ucwords(mb_strtolower($dateFormatee'UTF-8'));
  158.             $message "🌟 Récapitulatif des recettes du jour 🌟\n";
  159.             $message .= "📅 Date : " $dateFormatee "\n\n";
  160.             $message .= "💇‍♀️ Prestations réalisées :\n" . (!empty($prestations) ? implode("\n"$prestations) : "Aucune prestation") . "\n\n";
  161.             $message .= "💰 Totaux par mode de paiement :\n";
  162.             $message .= "💵 Espèces : {$totals['totalEspece']} €\n";
  163.             $message .= "💳 Carte Bancaire : {$totals['totalCarteBancaire']} €\n";
  164.             $message .= "🖥️ Planity : {$totals['totalAcompte']} €\n\n";
  165.             $message .= "🎉 Total du jour : {$totals['totalJour']} €\n\n";
  166.             $message .= "👩‍💼 Nombre de clientes : {$nombreClientes}\n\n";
  167.             $message .= "🔝 Prestation la plus demandée : {$prestationPopulaire}\n\n";
  168.             $telegramService->sendMessage(self::CHAT_ID_A$message);
  169.             $telegramService->sendMessage(self::CHAT_ID_J$message);
  170.             return new JsonResponse(['status' => 'Message envoyé']);
  171.         } catch (\Exception $e) {
  172.             $this->logger->error('Erreur lors de l\'envoi du message Telegram', ['error' => $e->getMessage()]);
  173.             return new JsonResponse(['error' => $e->getMessage()], 500);
  174.         }
  175.     }
  176. }