src/Controller/Accounting/AccountingExpenseController.php line 853

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Accounting;
  3. use Knp\Snappy\Pdf;
  4. use App\Entity\User;
  5. use DateTimeImmutable;
  6. use App\Service\SMSSender;
  7. use App\Entity\AccountingExpense;
  8. use App\Repository\UserRepository;
  9. use App\Entity\FoundingNotification;
  10. use App\Entity\TreasuryCashMovement;
  11. use App\Entity\TreasuryCheckout;
  12. use Knp\Component\Pager\PaginatorInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use App\Form\Accounting\AccountingExpenseType;
  15. use App\Repository\TreasuryCheckoutRepository;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use App\Repository\AccountingExpenseRepository;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use App\Repository\TreasuryCashRegisterRepository;
  20. use App\Repository\AccountingExpenseCategoryRepository;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. /**
  25.  * @Route("/accounting/expense")
  26.  */
  27. class AccountingExpenseController extends AbstractController
  28. {
  29.     /**
  30.      * @Route("/index", name="accounting_expense_index", methods={"GET"})
  31.     */
  32.     public function index(Request $requestAccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  33.     {
  34.         /**@var User $user */
  35.         $user $this->getUser();
  36.         $establishment $user->getEstablishment();
  37.         $createdBy intval($request->get('createdBy'));
  38.         $checkout $treasuryCheckoutRepository->findOneBy(['id' => intval($request->get('checkout'))], []);
  39.         $treasuryCheckouts $treasuryCheckoutRepository->findByEtsGroup($establishment);
  40.         
  41.         //statistiques
  42.         /* $totalSoumis = $accountingExpenseRepository->getTotalByStatus($establishment, 1, 0, 0, 0);
  43.         $totalAprouve = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 1, 0, 0);
  44.         $totalCanceled = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 1, 0);
  45.         $totalPaid = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 0, 1); */
  46.         
  47.         return $this->render('accounting/accounting_expense/index.html.twig', [
  48.             'userRepository' => $userRepository,
  49.             'createdBy' => $userRepository->findOneBy(['id' => $createdBy], []),
  50.             'checkouts' => $treasuryCheckouts,
  51.             'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
  52.             /* 'totalSoumis' => $totalSoumis,
  53.             'totalAprouve' => $totalAprouve,
  54.             'totalPaid' => $totalPaid,
  55.             'totalCanceled' => $totalCanceled, */
  56.             'startDate' => $request->get('startDate'),
  57.             'endDate' => $request->get('endDate'),
  58.             'checkout' => $checkout,
  59.         ]);
  60.     }
  61.     /**
  62.      * @Route("/_searh-table", name="accounting_expense_searh_table", methods={"GET","POST"})
  63.      */
  64.     public function _searh_table(Request $requestAccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepository): Response
  65.     {
  66.         /**@var User $user */
  67.         $user $this->getUser();
  68.         $establishment $this->getUser()->getEstablishment();
  69.         $schoolYear $user->getSchoolYear();
  70.         $createdBy intval($request->get('createdBy'));
  71.         $startDate $request->get('startDate');
  72.         $endDate $request->get('endDate');
  73.         $checkout $treasuryCheckoutRepository->findOneBy(['id' => intval($request->get('checkout'))], []);
  74.         $treasuryCheckouts $treasuryCheckoutRepository->findByEtsGroup($establishment);
  75.         $submited_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment$createdBy$checkout$startDate$endDate1000null);   
  76.         $aproved_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment$createdBy$checkout$startDate$endDate0100null);   
  77.         $canceled_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment$createdBy$checkout$startDate$endDate0010null);   
  78.         $paid_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment$createdBy$checkout$startDate$endDate0001null);   
  79.         //dd($submited_accounting_expenses);
  80.         $accounting_expenses = new ArrayCollection();
  81.         foreach ($submited_accounting_expenses as $key => $submited_accounting_expense) {
  82.             $accounting_expenses->add($submited_accounting_expense);
  83.         }
  84.         foreach ($aproved_accounting_expenses as $key => $aproved_accounting_expense) {
  85.             $accounting_expenses->add($aproved_accounting_expense);
  86.         }
  87.         foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
  88.             $accounting_expenses->add($paid_accounting_expense);
  89.         }
  90.         foreach ($canceled_accounting_expenses as $key => $canceled_accounting_expense) {
  91.             $accounting_expenses->add($canceled_accounting_expense);
  92.         }
  93.         
  94.         //statistiques
  95.         $totalSoumis $accountingExpenseRepository->getTotalByStatus($establishment1000);
  96.         $totalAprouve $accountingExpenseRepository->getTotalByStatus($establishment0100);
  97.         $totalCanceled $accountingExpenseRepository->getTotalByStatus($establishment0010);
  98.         $totalPaid $accountingExpenseRepository->getTotalByStatus($establishment0001);
  99.         return $this->renderForm('accounting/accounting_expense/_searh_table.html.twig', [
  100.             'accounting_expenses' => $accounting_expenses,
  101.             'accounting_expenses' => $accounting_expenses,
  102.             'userRepository' => $userRepository,
  103.             'createdBy' => $userRepository->findOneBy(['id' => $createdBy], []),
  104.             'checkouts' => $treasuryCheckouts,
  105.             'totalSoumis' => $totalSoumis,
  106.             'totalAprouve' => $totalAprouve,
  107.             'totalPaid' => $totalPaid,
  108.             'totalCanceled' => $totalCanceled,
  109.             'startDate' => $request->get('startDate'),
  110.             'endDate' => $request->get('endDate'),
  111.             'checkout' => $checkout,
  112.         ]);
  113.     }
  114.     /**
  115.      * @Route("/_searh-statistiques", name="accounting_expense_searh_statistiques", methods={"GET","POST"})
  116.      */
  117.     public function _searh_statistiques(AccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepository): Response
  118.     {
  119.         /**@var User $user */
  120.         $user $this->getUser();
  121.         $establishment $user->getEstablishment();
  122.         //statistiques
  123.         $totalSoumis $accountingExpenseRepository->getTotalByStatus($establishment1000);
  124.         $totalAprouve $accountingExpenseRepository->getTotalByStatus($establishment0100);
  125.         $totalCanceled $accountingExpenseRepository->getTotalByStatus($establishment0010);
  126.         $totalPaid $accountingExpenseRepository->getTotalByStatus($establishment0001);
  127.         return $this->renderForm('accounting/accounting_expense/_searh_statistiques.html.twig', [
  128.             'totalSoumis' => $totalSoumis,
  129.             'totalAprouve' => $totalAprouve,
  130.             'totalPaid' => $totalPaid,
  131.             'totalCanceled' => $totalCanceled,
  132.         ]);
  133.     }
  134.     /**
  135.      * @Route("/aproved", name="accounting_expense_aproved", methods={"GET"})
  136.     */
  137.     public function aproved(Request $requestPaginatorInterface $paginatorAccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  138.     {
  139.         /**@var User $user */
  140.         $user $this->getUser();
  141.         $establishment $user->getEstablishment();
  142.         $startDate $request->get('startDate');
  143.         $endDate $request->get('endDate');
  144.         $treasuryCheckout $treasuryCheckoutRepository->findOneBy(['id' => $request->get('checkout')], []);
  145.         $treasuryCheckouts $treasuryCheckoutRepository->findByEtsGroup($establishment);
  146.   
  147.         $aproved_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$treasuryCheckout$startDate$endDate0100null);   
  148.         $paid_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$treasuryCheckout$startDate$endDate0001null);   
  149.         $accounting_expenses = new ArrayCollection();
  150.         
  151.         foreach ($aproved_accounting_expenses as $key => $aproved_accounting_expense) {
  152.             $accounting_expenses->add($aproved_accounting_expense);
  153.         }
  154.         foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
  155.             $accounting_expenses->add($paid_accounting_expense);
  156.         }
  157.         //statistiques
  158.         $totalAprouve $accountingExpenseRepository->getTotalByStatus($establishment0100);
  159.         $totalPaid $accountingExpenseRepository->getTotalByStatus($establishment0001);
  160.         
  161.         return $this->render('accounting/accounting_expense/aproved.html.twig', [
  162.             'accounting_expenses' => $accounting_expenses,
  163.             'userRepository' => $userRepository,
  164.             'totalAprouve' => ($totalAprouve $totalPaid),
  165.             'totalPaid' => $totalPaid,
  166.             'checkouts' => $treasuryCheckouts,
  167.             'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
  168.             'startDate' => $request->get('startDate'),
  169.             'endDate' => $request->get('endDate'),
  170.             'checkout' => $treasuryCheckout,
  171.         ]);
  172.     }
  173.     /**
  174.      * @Route("/paids", name="accounting_expense_paids", methods={"GET"})
  175.     */
  176.     public function paids(Request $requestPaginatorInterface $paginatorAccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  177.     {
  178.         /**@var User $user */
  179.         $user $this->getUser();
  180.         $establishment $user->getEstablishment();
  181.         $startDate $request->get('startDate');
  182.         $endDate $request->get('endDate');
  183.         $treasuryCheckout $treasuryCheckoutRepository->findOneBy(['id' => $request->get('checkout')], []);
  184.         $treasuryCheckouts $treasuryCheckoutRepository->findByEtsGroup($establishment);
  185.   
  186.         $paid_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$treasuryCheckout$startDate$endDate0001null);   
  187.         $accounting_expenses = new ArrayCollection();
  188.         foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
  189.             $accounting_expenses->add($paid_accounting_expense);
  190.         }
  191.         
  192.         return $this->render('accounting/accounting_expense/paid.html.twig', [
  193.             'accounting_expenses' => $accounting_expenses,
  194.             'checkouts' => $treasuryCheckouts,
  195.             'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
  196.             'userRepository' => $userRepository,
  197.             'startDate' => $request->get('startDate'),
  198.             'endDate' => $request->get('endDate'),
  199.             'checkout' => $treasuryCheckout,
  200.         ]);
  201.     }
  202.     /**
  203.      * @Route("/canceleds", name="accounting_expense_canceleds", methods={"GET"})
  204.     */
  205.     public function canceleds(Request $requestPaginatorInterface $paginatorAccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  206.     {
  207.         /**@var User $user */
  208.         $user $this->getUser();
  209.         $establishment $user->getEstablishment();
  210.         $startDate $request->get('startDate');
  211.         $endDate $request->get('endDate');
  212.         $treasuryCheckout $treasuryCheckoutRepository->findOneBy(['id' => $request->get('checkout')], []);
  213.         $treasuryCheckouts $treasuryCheckoutRepository->findByEtsGroup($establishment);
  214.         $canceled_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$treasuryCheckout$startDate$endDate0010null);   
  215.         //dd($submited_accounting_expenses);
  216.         $accounting_expenses = new ArrayCollection();
  217.         foreach ($canceled_accounting_expenses as $key => $canceled_accounting_expense) {
  218.             $accounting_expenses->add($canceled_accounting_expense);
  219.         }
  220.         
  221.         return $this->render('accounting/accounting_expense/canceled.html.twig', [
  222.             'accounting_expenses' => $accounting_expenses,
  223.             'userRepository' => $userRepository,
  224.             'checkouts' => $treasuryCheckouts,
  225.             'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
  226.             'startDate' => $request->get('startDate'),
  227.             'endDate' => $request->get('endDate'),
  228.             'checkout' => $treasuryCheckout,
  229.         ]);
  230.     }
  231.     /**
  232.      * @Route("/new", name="accounting_expense_new", methods={"GET","POST"})
  233.     */
  234.     public function new(Request $requestSMSSender $smsSenderTreasuryCheckoutRepository $treasuryCheckoutRepository): Response
  235.     {
  236.         /**@var User $user */
  237.         $user $this->getUser();
  238.         $schoolYear $user->getSchoolYear();
  239.         $establishment $user->getEstablishment();
  240.         $accountingExpense = new AccountingExpense();
  241.         $form $this->createForm(AccountingExpenseType::class, $accountingExpense)
  242.         ->add('checkout'EntityType::class, [
  243.             'class' => TreasuryCheckout::class,
  244.             'choices' => $treasuryCheckoutRepository->findBy(['created_by' => $user->getId()])
  245.             //'choices' => $treasuryCheckoutRepository->findBy(['schoolYear' => $schoolYear, 'created_by' => $user->getId()])
  246.         ]);
  247.         $form->handleRequest($request);
  248.         if ($form->isSubmitted() && $form->isValid()) {
  249.             if (null == $accountingExpense->getCheckout()) {
  250.                 $this->addFlash('warning'"Veuillez selectionner une caisse SVP.");
  251.                 return $this->redirectToRoute('accounting_expense_new');
  252.             }
  253.             $entityManager $this->getDoctrine()->getManager();
  254.             $accountingExpense->setEstablishment($establishment);
  255.             $accountingExpense->setSchoolYear($schoolYear);
  256.             $entityManager->persist($accountingExpense);
  257.             try {
  258.                 $entityManager->flush();
  259.                 $this->addFlash('success'"Une dépense à été ajoutée.");
  260.                 $message "Nouvelle depense soumise: ".$accountingExpense->getLabel().' '.$accountingExpense->getDescription().", Montant : ".number_format($accountingExpense->getAmount(), 0','' ').' Date: '.$accountingExpense->getCreateDate()->format('d/m/Y').'. Soumise par: '.$this->getUser()->getUserIdentifier();
  261.                 $contacts = [];
  262.                 $contacts[] = '225'.str_replace(' ''',trim($establishment->getSmsBankPayment()));
  263.                 $response $smsSender->sendSmsByEstablishment($establishment$message$contacts$smsSender::UNICODE_CHARSET);
  264.             } catch (\Throwable $th) {
  265.                 $this->addFlash('warning'"Une erreure est survenue lors de l'ajout de la dépense.");
  266.                 $this->addFlash('info'$th->getMessage());
  267.             }
  268.             return $this->redirectToRoute('accounting_expense_index', [], Response::HTTP_SEE_OTHER);
  269.         }
  270.         return $this->renderForm('accounting/accounting_expense/new.html.twig', [
  271.             'accounting_expense' => $accountingExpense,
  272.             'form' => $form,
  273.         ]);
  274.     }
  275.     /**
  276.      * @Route("/{id}/edit", name="accounting_expense_edit", methods={"GET","POST"})
  277.      */
  278.     public function edit(Request $requestAccountingExpense $accountingExpenseUserRepository $userRepositoryTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  279.     {
  280.         /**@var User $user */
  281.         $user $this->getUser();
  282.         $schoolYear $user->getSchoolYear();
  283.         $establishment $user->getEstablishment();
  284.         $establishment $this->getUser()->getEstablishment();
  285.         
  286.         $treasuryCheckouts $treasuryCheckoutRepository->createQueryBuilder('entity')
  287.         ->innerJoin('entity.establishment''establishment')
  288.         ->addSelect('establishment')
  289.         ->andWhere('establishment.establishmentGroup = :establishmentGroup')
  290.         ->setParameter('establishmentGroup'$establishment->getEstablishmentGroup())
  291.         ->orderBy('entity.label''ASC')
  292.         ->getQuery()
  293.         ->getResult();
  294.         $form $this->createForm(AccountingExpenseType::class, $accountingExpense)
  295.         ->add('checkout'EntityType::class, [
  296.             'class' => TreasuryCheckout::class,
  297.             'choices' => $treasuryCheckoutRepository->findBy(['created_by' => $accountingExpense->getCreatedBy()]),
  298.             'required' => false
  299.         ]);
  300.         $form->handleRequest($request);
  301.         if ($form->isSubmitted() && $form->isValid()) {
  302.             if (null == $accountingExpense->getCheckout()) {
  303.                 $this->addFlash('warning'"Veuillez selectionner une caisse SVP.");
  304.                 return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()], Response::HTTP_SEE_OTHER);
  305.             }
  306.             try {
  307.                 $this->getDoctrine()->getManager()->flush();
  308.                 $this->addFlash('success'"la dépense a été éditée.");
  309.             } catch (\Throwable $th) {
  310.                 $this->addFlash('warning'"Une erreure est survenue lors de l'édition de la dépense.");
  311.                 $this->addFlash('info'$th->getMessage());
  312.             }
  313.             return $this->redirectToRoute('accounting_expense_index', [], Response::HTTP_SEE_OTHER);
  314.         }
  315.         return $this->renderForm('accounting/accounting_expense/edit.html.twig', [
  316.             'accounting_expense' => $accountingExpense,
  317.             'form' => $form,
  318.             'userRepository' => $userRepository,
  319.             'treasury_checkouts' => $treasuryCheckouts,
  320.             'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
  321.         ]);
  322.     }
  323.     /**
  324.      * @Route("/set-category/{id}", name="accounting_expense_set_category", methods={"GET", "POST"})
  325.     */
  326.     public function set_category(Request $requestAccountingExpense $accountingExpenseAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  327.     {
  328.         /**@var User $user */
  329.         $user $this->getUser();
  330.         $establishment $user->getEstablishment();
  331.         $accounting_expense_category intval($request->request->get('accounting_expense_category'));
  332.         $accountingExpenseCategory $accountingExpenseCategoryRepository->findOneBy(['id' => $accounting_expense_category], []);
  333.         if (null == $accountingExpenseCategory) {
  334.             $this->addFlash('warning'"Veuillez selectionner une catégorie SVP.");
  335.             return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
  336.         }
  337.         $accountingExpense->setAccountingExpenseCategory($accountingExpenseCategory);
  338.         $entityManager $this->getDoctrine()->getManager();
  339.         try {
  340.             $entityManager->flush();
  341.             $this->addFlash('success'"Traitement effectué");
  342.             
  343.         } catch (\Throwable $th) {
  344.             //$th->getMessage()
  345.             $this->addFlash('warning'$th->getMessage());
  346.         }
  347.         return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
  348.     }
  349.     /**
  350.      * @Route("/aprove/{id}", name="accounting_expense_aprove", methods={"POST", "GET"})
  351.     */
  352.     public function aprove(Request $requestAccountingExpense $entitySMSSender $smsSenderTreasuryCheckoutRepository $treasuryCheckoutRepository): Response
  353.     {
  354.         /*$idCheckout = intval($request->request->get('checkout'));
  355.         $checkout = $treasuryCheckoutRepository->findOneBy(['id' => $idCheckout], []);*/
  356.         if (null == $entity->getCheckout()) {
  357.             $this->addFlash('warning'"Aucune caisse n'est associé à cette dépense.");
  358.             return $this->json(['code' => 500'message' => "Aucune caisse n'est associé à cette dépense."], 200);
  359.         }
  360.         $establishment $this->getUser()->getEstablishment();
  361.         $entityManager $this->getDoctrine()->getManager();
  362.         $entity->setIsAproved(true);
  363.         $entity->setAprovedBy($this->getUser()->getId());
  364.         $entity->setAprovedAt(new DateTimeImmutable());
  365.         $entity->setCheckout($entity->getCheckout());
  366.         //notification fondateur
  367.         $foundingNotification = new FoundingNotification();
  368.         $foundingNotification->setCreateDate(new DateTimeImmutable());
  369.         $foundingNotification->setAction("Approuvé");
  370.         $foundingNotification->setElement("Dépense: #".$entity->getId());
  371.         $foundingNotification->setDescription($entity->getLabel().' Mt: '.number_format($entity->getAmount(), 0' '',').' Date: '.$entity->getCreatedAt()->format('d/m/Y').' Caisse: '.$entity->getCheckout()->getLabel());
  372.         $foundingNotification->setEstablishment($entity->getEstablishment());
  373.         $foundingNotification->setIpAddress($request->getClientIp());
  374.         $foundingNotification->setSchoolYear($entity->getSchoolYear());
  375.         $foundingNotification->setUsername($this->getUser()->getUserIdentifier());
  376.         $entityManager->persist($foundingNotification);
  377.         /*---------------------------------------------*/
  378.         try {
  379.             $entityManager->flush();
  380.             $this->addFlash('success'"Traitement effectué");
  381.             $message "Dépense approuvée: ".$entity->getLabel().' '.$entity->getDescription().", Montant : ".number_format($entity->getAmount(), 0','' ').' Date: '.$entity->getCreateDate()->format('d/m/Y').'. Approuvée par: '.$this->getUser()->getUserIdentifier();
  382.             $contacts = [];
  383.             $contacts[] = '225'.str_replace(' ''',trim($establishment->getSmsBankPayment()));
  384.             $response $smsSender->sendSmsByEstablishment($establishment$message$contacts$smsSender::UNICODE_CHARSET);
  385.             return $this->json(['code' => 200'message' => "Traitement effectué :)"], 200);
  386.             
  387.         } catch (\Throwable $th) {
  388.             //$th->getMessage()
  389.             $this->addFlash('warning'$th->getMessage());
  390.             return $this->json(['code' => 500'message' => $th->getMessage()], 200);
  391.         }
  392.         
  393.         //$this->addFlash('warning', "Traitement non effectué");
  394.         return $this->json(['code' => 500'message' => "Traitement non effectué"], 200);
  395.         //return $this->redirectToRoute('accounting_expense_index');
  396.     }
  397.     /**
  398.      * @Route("/cancel/{id}", name="accounting_expense_cancel", methods={"GET"})
  399.     */
  400.     public function cancel(AccountingExpense $entity): Response
  401.     {
  402.         if ($entity->getCashRegister() != null) {
  403.             return $this->json(['code' => 500'message' => "Impossible un paiement à été effectué sur cette dépense."], 200);
  404.         }
  405.         
  406.         $entityManager $this->getDoctrine()->getManager();
  407.         $entity->setIsAproved(true);
  408.         $entity->setIsCanceled(true);
  409.         $entity->setIsPaid(false);
  410.         $entity->setCheckout(null);
  411.         try {
  412.             $entityManager->flush();
  413.             $this->addFlash('success'"Traitement effectué");
  414.             return $this->json(['code' => 200'message' => "Traitement effectué :)"], 200);
  415.         } catch (\Throwable $th) {
  416.             //$th->getMessage()
  417.             $this->addFlash('warning'$th->getMessage());
  418.         }
  419.         
  420.         $this->addFlash('warning'"Traitement non effectué");
  421.         return $this->json(['code' => 500'message' => "Traitement non effectué"], 200);
  422.     }
  423.     /**
  424.      * @Route("/paid/{id}/{idCashRegister}", name="accounting_expense_paid", methods={"GET"})
  425.     */
  426.     public function paid(Request $requestAccountingExpense $entity$idCashRegisterTreasuryCashRegisterRepository $treasuryCashRegisterRepositorySMSSender $smsSender): Response
  427.     {
  428.         $establishment $this->getUser()->getEstablishment();
  429.         $entityManager $this->getDoctrine()->getManager();
  430.         $cashRegister $treasuryCashRegisterRepository->find($idCashRegister);
  431.         
  432.         /*
  433.          * 20/08/2022
  434.          * si le solde de la caisse est insuffisant pour payer la dépense 
  435.          * le fondateur à demande de désactiver cette option pour permeetre
  436.          * une sortir de caisse même si le solde est insuffisant
  437.          * 
  438.             if ($cashRegister->toForward($treasuryCashRegisterRepository) < $entity->getAmount()) {
  439.                 return $this->json(['code' => 500, 'message' => "Le solde de la caisse est insuffisant"], 200);
  440.             } 
  441.         */
  442.         $entity->setIsPaid(true);
  443.         $entity->setCreateDate(new DateTimeImmutable());
  444.         $entity->setCashRegister($cashRegister);
  445.         // mouvement de caisse
  446.         $cashMovement = new TreasuryCashMovement();
  447.         $cashMovement->setAmount($entity->getAmount());
  448.         $cashMovement->setAccountingExpense($entity);
  449.         $cashMovement->setCashRegister($cashRegister);
  450.         $cashMovement->setCode($entity->getId().'-'.time());
  451.         $cashMovement->setEstablishment($entity->getEstablishment());
  452.         $cashMovement->setType('out');
  453.         $cashMovement->setLabel($entity->getLabel());
  454.         $entityManager->persist($cashMovement);
  455.         /*---------------------------------------------*/
  456.         //notification fondateur
  457.         $foundingNotification = new FoundingNotification();
  458.         $foundingNotification->setCreateDate(new DateTimeImmutable());
  459.         $foundingNotification->setAction("Paiement");
  460.         $foundingNotification->setElement("Dépense: #".$entity->getId());
  461.         $foundingNotification->setDescription($entity->getLabel().' Mt: '.number_format($entity->getAmount(), 0' '',').' Date: '.$entity->getCreatedAt()->format('d/m/Y'));
  462.         $foundingNotification->setEstablishment($entity->getEstablishment());
  463.         $foundingNotification->setIpAddress($request->getClientIp());
  464.         $foundingNotification->setSchoolYear($entity->getSchoolYear());
  465.         $foundingNotification->setUsername($this->getUser()->getUserIdentifier());
  466.         $entityManager->persist($foundingNotification);
  467.         /*---------------------------------------------*/
  468.         try {
  469.             $entityManager->flush();
  470.             $this->addFlash('success'"Traitement effectué");
  471.             $message "Dépense payée: ".$entity->getLabel().' '.$entity->getDescription().", Montant : ".number_format($entity->getAmount(), 0','' ').' Date: '.$entity->getCreateDate()->format('d/m/Y').'. Payée par: '.$this->getUser()->getUserIdentifier().'. Caisse: '.$cashRegister->getCheckout()->getLabel();
  472.             $contacts = [];
  473.             $contacts[] = '225'.str_replace(' ''',trim($establishment->getSmsBankPayment()));
  474.             $response $smsSender->sendSmsByEstablishment($establishment$message$contacts$smsSender::UNICODE_CHARSET);
  475.             return $this->json(['code' => 200'message' => "Traitement effectué :)"], 200);
  476.         } catch (\Throwable $th) {
  477.             //$th->getMessage()
  478.             $this->addFlash('warning'$th->getMessage());
  479.         }
  480.         
  481.         $this->addFlash('warning'"Traitement non effectué");
  482.         return $this->json(['code' => 500'message' => "Traitement non effectué"], 200);
  483.     }
  484.     /**
  485.      * @Route("/delete-selection", name="accounting_expenses_selected_delete", methods={"GET"})
  486.     */
  487.     public function deleteSelected(Request $requestAccountingExpenseRepository $entityRepository): Response
  488.     {
  489.         $list $request->get('entities');
  490.         $entityManager $this->getDoctrine()->getManager();
  491.         $errors 0;
  492.         foreach ($list as $key => $id) {
  493.             $entity $entityRepository->findOneBy(['id' => intval($id)], []);
  494.             if ($entity != null) {
  495.                 if (!$entity->getIsAproved()) {
  496.                     $entityManager->remove($entity);
  497.                 }
  498.             }
  499.         }
  500.         try {
  501.             $entityManager->flush();
  502.             $this->addFlash('success'"Traitement effectué");
  503.             return $this->json(['code' => 200'message' => "Traitement effectué :)"], 200);
  504.         } catch (\Throwable $th) {
  505.             //$th->getMessage()
  506.             $this->addFlash('warning'$th->getMessage());
  507.         }
  508.         
  509.         $this->addFlash('warning'"Traitement non effectué");
  510.         return $this->json(['code' => 500'message' => "Traitement non effectué"], 200);
  511.     }
  512.     /**
  513.      * @Route("/report/print", name="accounting_expense_report_print")
  514.     */
  515.     public function print_report(Pdf $knpSnappyPdfRequest $requestTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpenseRepository $accountingExpenseRepositoryUserRepository $userRepositoryAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  516.     {
  517.         /**@var User $user */
  518.         $user $this->getUser();
  519.         $schoolYear $user->getSchoolYear();
  520.         $establishment $user->getEstablishment();
  521.         $dateStart = new DateTimeImmutable($request->get('dateStart'));
  522.         $dateEnd = new DateTimeImmutable($request->get('dateEnd'));
  523.         $show_state $request->get('show_state');
  524.         $checkout $treasuryCheckoutRepository->findOneBy(['id' => intval($request->get('checkout'))], []);
  525.         $accounting_expense_category intval($request->get('accounting_expense_category'));
  526.         $accountingExpenseCategory $accountingExpenseCategoryRepository->findOneBy(['id' => $accounting_expense_category], []);
  527.         
  528.         $checkouts $treasuryCheckoutRepository->findByEtsGroup($establishment);
  529.         $submited_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$checkout$dateStart$dateEnd1000$accountingExpenseCategory);   
  530.         $aproved_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$checkout$dateStart$dateEnd0100$accountingExpenseCategory);   
  531.         $canceled_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$checkout$dateStart$dateEnd0010$accountingExpenseCategory);   
  532.         $paid_accounting_expenses $accountingExpenseRepository->getQueryByStatus($establishment0$checkout$dateStart$dateEnd0001$accountingExpenseCategory);   
  533.         $accounting_expenses = new ArrayCollection();
  534.         foreach ($submited_accounting_expenses as $key => $submited_accounting_expense) {
  535.             $accounting_expenses->add($submited_accounting_expense);
  536.         }
  537.         foreach ($aproved_accounting_expenses as $key => $aproved_accounting_expense) {
  538.             $accounting_expenses->add($aproved_accounting_expense);
  539.         }
  540.         foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
  541.             $accounting_expenses->add($paid_accounting_expense);
  542.         }
  543.         foreach ($canceled_accounting_expenses as $key => $canceled_accounting_expense) {
  544.             $accounting_expenses->add($canceled_accounting_expense);
  545.         }
  546.         $html $this->renderView('accounting/print/expenses.html.twig', [
  547.             'checkouts' => $checkouts,
  548.             'accounting_expenses' => $accounting_expenses,
  549.             'accountingExpenseCategory' => $accountingExpenseCategory,
  550.             'userRepository' => $userRepository,
  551.             
  552.             'dateStart' => $dateStart,
  553.             'dateEnd' => $dateEnd,
  554.             'checkout' => $checkout,
  555.             'show_state' => $show_state,
  556.             
  557.             'school_year' => $schoolYear,
  558.             'setting' => $establishment,
  559.             'isPaid' => $request->get('isPaid'),
  560.             'isAproved' => $request->get('isAproved'),
  561.             'isSubmited' => $request->get('isSubmited'),
  562.             'isCanceled' => $request->get('isCanceled'),
  563.         ]);
  564.         $file_name "RAPPORT_DEPENSES_.pdf";
  565.         $footer $this->renderView('print/footer.html.twig', ['setting' => $establishment]);
  566.         $header $this->renderView('print/header.html.twig', ['setting' => $establishment]);
  567.         $options = [
  568.             'orientation' => 'Portrait',
  569.             'header-html' => $header,
  570.             'footer-html' => $footer,
  571.             'footer-right' => "Page [page] / [toPage]"
  572.         ];
  573.         
  574.         $knpSnappyPdf->generateFromHtml($html$this->getParameter('app.app_directory').'/downloads/rapport/' $file_name$optionstrue);
  575.         return $this->redirectToRoute('preview', [
  576.             'file' => $file_name,
  577.             'dir' => 'rapport',
  578.         ]);
  579.     }
  580.     /**
  581.      * @Route("/api/aprove", name="api_accounting_expense_aprove", methods={"GET"})
  582.      * Modifié le 15/04/2024
  583.     */
  584.     public function api_aprove(Request $requestAccountingExpenseRepository $entityRepositorySMSSender $smsSenderTreasuryCheckoutRepository $treasuryCheckoutRepository): Response
  585.     {
  586.         /*$idCheckout = intval($request->get('checkout'));
  587.         $checkout = $treasuryCheckoutRepository->findOneBy(['id' => $idCheckout], []);
  588.         if (null == $checkout) {
  589.             $this->addFlash('warning', "Veuillez selectionner une caisse SVP.");
  590.             return $this->json(['code' => 500, 'message' => "Veuillez selectionner une caisse SVP."], 200);
  591.         }*/
  592.         $establishment $this->getUser()->getEstablishment();
  593.         $entityManager $this->getDoctrine()->getManager();
  594.         $list $request->get('entities');
  595.         $errors 0;
  596.         $success 0;
  597.         foreach ($list as $key => $id) {
  598.             $entity $entityRepository->findOneBy(['id' => intval($id)], []);
  599.             if ($entity != null) {
  600.                 if (null != $entity->getCheckout()) {
  601.                     if (!$entity->getIsAproved()) {
  602.                         $success++;
  603.                         $entity->setIsAproved(true);
  604.                         $entity->setAprovedBy($this->getUser()->getId());
  605.                         $entity->setAprovedAt(new DateTimeImmutable());
  606.                         $entity->setCheckout($entity->getCheckout());
  607.                         //notification fondateur
  608.                         $foundingNotification = new FoundingNotification();
  609.                         $foundingNotification->setCreateDate(new DateTimeImmutable());
  610.                         $foundingNotification->setAction("Approuvé");
  611.                         $foundingNotification->setElement("Dépense: #".$entity->getId());
  612.                         $foundingNotification->setDescription($entity->getLabel().' Mt: '.number_format($entity->getAmount(), 0' '',').' Date: '.$entity->getCreatedAt()->format('d/m/Y').' Caisse: '.$entity->getCheckout()->getLabel());
  613.                         $foundingNotification->setEstablishment($entity->getEstablishment());
  614.                         $foundingNotification->setIpAddress($request->getClientIp());
  615.                         $foundingNotification->setSchoolYear($entity->getSchoolYear());
  616.                         $foundingNotification->setUsername($this->getUser()->getUserIdentifier());
  617.                         $entityManager->persist($foundingNotification);
  618.                         try {
  619.                             $entityManager->flush();
  620.                             $message "Dépense approuvée: ".$entity->getLabel().' '.$entity->getDescription().", Montant : ".number_format($entity->getAmount(), 0','' ').' Date: '.$entity->getCreateDate()->format('d/m/Y').'. Approuvée par: '.$this->getUser()->getUserIdentifier();
  621.                             $contacts = [];
  622.                             $contacts[] = '225'.str_replace(' ''',trim($establishment->getSmsBankPayment()));
  623.                             $response $smsSender->sendSmsByEstablishment($establishment$message$contacts$smsSender::UNICODE_CHARSET);
  624.                             
  625.                         } catch (\Throwable $th) {
  626.                             //$th->getMessage()
  627.                             $this->addFlash('warning'$th->getMessage());
  628.                         }
  629.                     }else {
  630.                         $errors++;
  631.                     }
  632.                 }else {
  633.                     $errors++;
  634.                 }
  635.             }
  636.         }
  637.         
  638.         /*---------------------------------------------*/
  639.         try {
  640.             $entityManager->flush();
  641.             $this->addFlash('success'"Traitement effectué, " $success "dépense(s) approuvée(s).");/* 
  642.             $message = "Dépense approuvée: ".$entity->getLabel().' '.$entity->getDescription().", Montant : ".number_format($entity->getAmount(), 0, ',', ' ').' Date: '.$entity->getCreateDate()->format('d/m/Y').'. Approuvée par: '.$this->getUser()->getUserIdentifier();
  643.             $contacts = [];
  644.             $contacts[] = '225'.str_replace(' ', '',trim($establishment->getSmsBankPayment()));
  645.             $response = $smsSender->sendSmsByEstablishment($establishment, $message, $contacts, $smsSender::UNICODE_CHARSET); */
  646.             return $this->json(['code' => 200'message' => "Traitement effectué :), " $success " dépense(s) approuvée(s)."], 200);
  647.             
  648.         } catch (\Throwable $th) {
  649.             //$th->getMessage()
  650.             $this->addFlash('warning'$th->getMessage());
  651.             return $this->json(['code' => 500'message' => $th->getMessage()], 200);
  652.         }
  653.         
  654.         //$this->addFlash('warning', "Traitement non effectué");
  655.         return $this->json(['code' => 500'message' => "Traitement non effectué"], 200);
  656.         //return $this->redirectToRoute('accounting_expense_index');
  657.     }
  658.     /**
  659.      * @Route("/api/cancel", name="api_accounting_expense_cancel", methods={"GET"})
  660.     */
  661.     public function api_cancel(Request $requestAccountingExpenseRepository $entityRepository): Response
  662.     {
  663.         $establishment $this->getUser()->getEstablishment();
  664.         $entityManager $this->getDoctrine()->getManager();
  665.         $list $request->get('entities');
  666.         $errors 0;
  667.         $success 0;
  668.         foreach ($list as $key => $id) {
  669.             $entity $entityRepository->findOneBy(['id' => intval($id)], []);
  670.             if ($entity != null) {
  671.                 if ($entity->getCashRegister() == null) {
  672.                     if (!$entity->getIsPaid()) {
  673.                         if ($entity->getIsAproved()) {
  674.                             if (!$entity->getIsCanceled()) {
  675.                                 $success++;
  676.                                 $entity->setIsAproved(true);
  677.                                 $entity->setIsCanceled(true);
  678.                                 $entity->setIsPaid(false);
  679.                                 $entity->setCheckout(null);
  680.                             }else {
  681.                                 $errors++;
  682.                             }
  683.                         }else {
  684.                             $errors++;
  685.                         }
  686.                     }else {
  687.                         $errors++;
  688.                     }
  689.                 }else {
  690.                     $errors++;
  691.                 }
  692.             }else {
  693.                 $errors++;
  694.             }
  695.         }
  696.         try {
  697.             $entityManager->flush();
  698.             $this->addFlash('success'$success " dépense annulée(s)");
  699.             return $this->json(['code' => 200'message' => $success " dépense annulée(s)"], 200);
  700.         } catch (\Throwable $th) {
  701.             //$th->getMessage()
  702.             $this->addFlash('warning'$th->getMessage());
  703.             return $this->json(['code' => 500'message' => $th->getMessage()], 200);
  704.         }
  705.         
  706.         $this->addFlash('warning'"Traitement non effectué");
  707.         return $this->json(['code' => 500'message' => "Traitement non effectué"], 200);
  708.     }
  709.     /**
  710.      * @Route("/restaure/{id}/{idCheckout}", name="accounting_expense_restaure", methods={"GET", "POST"})
  711.     */
  712.     public function restaure($idCheckoutTreasuryCheckoutRepository $treasuryCheckoutRepositoryAccountingExpense $accountingExpenseAccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
  713.     {
  714.         /**@var User $user */
  715.         $user $this->getUser();
  716.         $treasuryCheckout $treasuryCheckoutRepository->findOneBy(['id' => $idCheckout], []);
  717.         if (null == $treasuryCheckout) {
  718.             $this->addFlash('warning'"Caisse introuvable!");
  719.             return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
  720.         }
  721.         if ($accountingExpense->getCashRegister() != null) {
  722.             $this->addFlash('warning'"cette dépense est déjà payé.");
  723.             return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
  724.         }
  725.         $accountingExpense->setIsAproved(true);
  726.         $accountingExpense->setIsCanceled(false);
  727.         $accountingExpense->setIsPaid(false);
  728.         $accountingExpense->setCheckout($treasuryCheckout);
  729.         $entityManager $this->getDoctrine()->getManager();
  730.         try {
  731.             $entityManager->flush();
  732.             $this->addFlash('success'"Traitement effectué");
  733.             
  734.         } catch (\Throwable $th) {
  735.             //$th->getMessage()
  736.             $this->addFlash('warning'$th->getMessage());
  737.         }
  738.         return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
  739.     }
  740.     /**
  741.      * @Route("/api/chart-expense-by-month", name="api_chart_accounting_expense_by_month")
  742.     */
  743.     public function api_chart_expense_by_month(Request $requestAccountingExpenseRepository $accountingExpenseRepository): Response
  744.     {
  745.         /**@var User $user */
  746.         $user $this->getUser();
  747.         $schoolYear $user->getSchoolYear();
  748.         $establishment $user->getEstablishment();
  749.         $year =  $request->get('year');
  750.         //$year =  date('Y');
  751.         $expense_months = [];
  752.         $expense_year 0;
  753.         $accountingExpenses $accountingExpenseRepository->createQueryBuilder('entity')
  754.         ->innerJoin('entity.establishment''establishment')
  755.         ->addSelect('establishment')
  756.         ->andWhere('establishment.establishmentGroup = :establishmentGroup')
  757.         ->setParameter('establishmentGroup'$establishment->getEstablishmentGroup())
  758.         ->andWhere('entity.is_canceled = :is_canceled')
  759.         ->setParameter('is_canceled'0)
  760.         ->andWhere('entity.is_paid = :is_paid')
  761.         ->setParameter('is_paid'1)
  762.         ->andWhere('entity.create_date BETWEEN :startDate AND :endDate')
  763.         ->setParameter('startDate'$year.'-01-01')
  764.         ->setParameter('endDate'$year.'-12-31')
  765.         ->getQuery()
  766.         ->getResult();
  767.         $max 0;
  768.         for ($i=1$i <= 12$i++) { 
  769.             $_year 0;
  770.             $_months 0;
  771.             foreach ($accountingExpenses as $key => $accountingExpense) {
  772.                 if ($accountingExpense->getCreateDate()->format('Y-m') == $year.'-'.sprintf("%'02s"$i)) {
  773.                     $_year += $accountingExpense->getAmount();
  774.                     $_months += $accountingExpense->getAmount();
  775.                 }
  776.             }
  777.             if ($_months $max) {
  778.                 $max $_months;
  779.             }
  780.             $expense_year += $_year;
  781.             $expense_months[] = intval($_months);
  782.         }
  783.         return $this->json([
  784.             'code' => 200
  785.             'message' => "ok"
  786.             'expense_months' => $expense_months
  787.             'expense_year' => intval($expense_year), 
  788.             'max' => intval($max), 
  789.             'interval' => intval($max 10), 
  790.             'year' => intval($year), 
  791.         ], 200);
  792.     }
  793. }