src/Controller/Accounting/AccountingExpenseController.php line 35

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