<?php
namespace App\Controller\Accounting;
use Knp\Snappy\Pdf;
use App\Entity\User;
use DateTimeImmutable;
use App\Service\SMSSender;
use App\Entity\AccountingExpense;
use App\Repository\UserRepository;
use App\Entity\FoundingNotification;
use App\Entity\TreasuryCashMovement;
use App\Entity\TreasuryCheckout;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use App\Form\Accounting\AccountingExpenseType;
use App\Repository\TreasuryCheckoutRepository;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\AccountingExpenseRepository;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\TreasuryCashRegisterRepository;
use App\Repository\AccountingExpenseCategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* @Route("/accounting/expense")
*/
class AccountingExpenseController extends AbstractController
{
/**
* @Route("/index", name="accounting_expense_index", methods={"GET"})
*/
public function index(Request $request, AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $user->getEstablishment();
$createdBy = intval($request->get('createdBy'));
$checkout = $treasuryCheckoutRepository->findOneBy(['id' => intval($request->get('checkout'))], []);
$treasuryCheckouts = $treasuryCheckoutRepository->findByEtsGroup($establishment);
//statistiques
/* $totalSoumis = $accountingExpenseRepository->getTotalByStatus($establishment, 1, 0, 0, 0);
$totalAprouve = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 1, 0, 0);
$totalCanceled = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 1, 0);
$totalPaid = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 0, 1); */
return $this->render('accounting/accounting_expense/index.html.twig', [
'userRepository' => $userRepository,
'createdBy' => $userRepository->findOneBy(['id' => $createdBy], []),
'checkouts' => $treasuryCheckouts,
'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
/* 'totalSoumis' => $totalSoumis,
'totalAprouve' => $totalAprouve,
'totalPaid' => $totalPaid,
'totalCanceled' => $totalCanceled, */
'startDate' => $request->get('startDate'),
'endDate' => $request->get('endDate'),
'checkout' => $checkout,
]);
}
/**
* @Route("/_searh-table", name="accounting_expense_searh_table", methods={"GET","POST"})
*/
public function _searh_table(Request $request, AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $this->getUser()->getEstablishment();
$schoolYear = $user->getSchoolYear();
$createdBy = intval($request->get('createdBy'));
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$checkout = $treasuryCheckoutRepository->findOneBy(['id' => intval($request->get('checkout'))], []);
$treasuryCheckouts = $treasuryCheckoutRepository->findByEtsGroup($establishment);
$submited_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, $createdBy, $checkout, $startDate, $endDate, 1, 0, 0, 0, null);
$aproved_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, $createdBy, $checkout, $startDate, $endDate, 0, 1, 0, 0, null);
$canceled_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, $createdBy, $checkout, $startDate, $endDate, 0, 0, 1, 0, null);
$paid_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, $createdBy, $checkout, $startDate, $endDate, 0, 0, 0, 1, null);
//dd($submited_accounting_expenses);
$accounting_expenses = new ArrayCollection();
foreach ($submited_accounting_expenses as $key => $submited_accounting_expense) {
$accounting_expenses->add($submited_accounting_expense);
}
foreach ($aproved_accounting_expenses as $key => $aproved_accounting_expense) {
$accounting_expenses->add($aproved_accounting_expense);
}
foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
$accounting_expenses->add($paid_accounting_expense);
}
foreach ($canceled_accounting_expenses as $key => $canceled_accounting_expense) {
$accounting_expenses->add($canceled_accounting_expense);
}
//statistiques
$totalSoumis = $accountingExpenseRepository->getTotalByStatus($establishment, 1, 0, 0, 0);
$totalAprouve = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 1, 0, 0);
$totalCanceled = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 1, 0);
$totalPaid = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 0, 1);
return $this->renderForm('accounting/accounting_expense/_searh_table.html.twig', [
'accounting_expenses' => $accounting_expenses,
'accounting_expenses' => $accounting_expenses,
'userRepository' => $userRepository,
'createdBy' => $userRepository->findOneBy(['id' => $createdBy], []),
'checkouts' => $treasuryCheckouts,
'totalSoumis' => $totalSoumis,
'totalAprouve' => $totalAprouve,
'totalPaid' => $totalPaid,
'totalCanceled' => $totalCanceled,
'startDate' => $request->get('startDate'),
'endDate' => $request->get('endDate'),
'checkout' => $checkout,
]);
}
/**
* @Route("/_searh-statistiques", name="accounting_expense_searh_statistiques", methods={"GET","POST"})
*/
public function _searh_statistiques(AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $user->getEstablishment();
//statistiques
$totalSoumis = $accountingExpenseRepository->getTotalByStatus($establishment, 1, 0, 0, 0);
$totalAprouve = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 1, 0, 0);
$totalCanceled = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 1, 0);
$totalPaid = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 0, 1);
return $this->renderForm('accounting/accounting_expense/_searh_statistiques.html.twig', [
'totalSoumis' => $totalSoumis,
'totalAprouve' => $totalAprouve,
'totalPaid' => $totalPaid,
'totalCanceled' => $totalCanceled,
]);
}
/**
* @Route("/aproved", name="accounting_expense_aproved", methods={"GET"})
*/
public function aproved(Request $request, PaginatorInterface $paginator, AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $user->getEstablishment();
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$treasuryCheckout = $treasuryCheckoutRepository->findOneBy(['id' => $request->get('checkout')], []);
$treasuryCheckouts = $treasuryCheckoutRepository->findByEtsGroup($establishment);
$aproved_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $treasuryCheckout, $startDate, $endDate, 0, 1, 0, 0, null);
$paid_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $treasuryCheckout, $startDate, $endDate, 0, 0, 0, 1, null);
$accounting_expenses = new ArrayCollection();
foreach ($aproved_accounting_expenses as $key => $aproved_accounting_expense) {
$accounting_expenses->add($aproved_accounting_expense);
}
foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
$accounting_expenses->add($paid_accounting_expense);
}
//statistiques
$totalAprouve = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 1, 0, 0);
$totalPaid = $accountingExpenseRepository->getTotalByStatus($establishment, 0, 0, 0, 1);
return $this->render('accounting/accounting_expense/aproved.html.twig', [
'accounting_expenses' => $accounting_expenses,
'userRepository' => $userRepository,
'totalAprouve' => ($totalAprouve + $totalPaid),
'totalPaid' => $totalPaid,
'checkouts' => $treasuryCheckouts,
'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
'startDate' => $request->get('startDate'),
'endDate' => $request->get('endDate'),
'checkout' => $treasuryCheckout,
]);
}
/**
* @Route("/paids", name="accounting_expense_paids", methods={"GET"})
*/
public function paids(Request $request, PaginatorInterface $paginator, AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $user->getEstablishment();
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$treasuryCheckout = $treasuryCheckoutRepository->findOneBy(['id' => $request->get('checkout')], []);
$treasuryCheckouts = $treasuryCheckoutRepository->findByEtsGroup($establishment);
$paid_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $treasuryCheckout, $startDate, $endDate, 0, 0, 0, 1, null);
$accounting_expenses = new ArrayCollection();
foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
$accounting_expenses->add($paid_accounting_expense);
}
return $this->render('accounting/accounting_expense/paid.html.twig', [
'accounting_expenses' => $accounting_expenses,
'checkouts' => $treasuryCheckouts,
'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
'userRepository' => $userRepository,
'startDate' => $request->get('startDate'),
'endDate' => $request->get('endDate'),
'checkout' => $treasuryCheckout,
]);
}
/**
* @Route("/canceleds", name="accounting_expense_canceleds", methods={"GET"})
*/
public function canceleds(Request $request, PaginatorInterface $paginator, AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $user->getEstablishment();
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$treasuryCheckout = $treasuryCheckoutRepository->findOneBy(['id' => $request->get('checkout')], []);
$treasuryCheckouts = $treasuryCheckoutRepository->findByEtsGroup($establishment);
$canceled_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $treasuryCheckout, $startDate, $endDate, 0, 0, 1, 0, null);
//dd($submited_accounting_expenses);
$accounting_expenses = new ArrayCollection();
foreach ($canceled_accounting_expenses as $key => $canceled_accounting_expense) {
$accounting_expenses->add($canceled_accounting_expense);
}
return $this->render('accounting/accounting_expense/canceled.html.twig', [
'accounting_expenses' => $accounting_expenses,
'userRepository' => $userRepository,
'checkouts' => $treasuryCheckouts,
'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
'startDate' => $request->get('startDate'),
'endDate' => $request->get('endDate'),
'checkout' => $treasuryCheckout,
]);
}
/**
* @Route("/new", name="accounting_expense_new", methods={"GET","POST"})
*/
public function new(Request $request, SMSSender $smsSender, TreasuryCheckoutRepository $treasuryCheckoutRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$schoolYear = $user->getSchoolYear();
$establishment = $user->getEstablishment();
$accountingExpense = new AccountingExpense();
$form = $this->createForm(AccountingExpenseType::class, $accountingExpense)
->add('checkout', EntityType::class, [
'class' => TreasuryCheckout::class,
'choices' => $treasuryCheckoutRepository->findBy(['created_by' => $user->getId()])
//'choices' => $treasuryCheckoutRepository->findBy(['schoolYear' => $schoolYear, 'created_by' => $user->getId()])
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if (null == $accountingExpense->getCheckout()) {
$this->addFlash('warning', "Veuillez selectionner une caisse SVP.");
return $this->redirectToRoute('accounting_expense_new');
}
$entityManager = $this->getDoctrine()->getManager();
$accountingExpense->setEstablishment($establishment);
$accountingExpense->setSchoolYear($schoolYear);
$entityManager->persist($accountingExpense);
try {
$entityManager->flush();
$this->addFlash('success', "Une dépense à été ajoutée.");
$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();
$contacts = [];
$contacts[] = '225'.str_replace(' ', '',trim($establishment->getSmsBankPayment()));
$response = $smsSender->sendSmsByEstablishment($establishment, $message, $contacts, $smsSender::UNICODE_CHARSET);
} catch (\Throwable $th) {
$this->addFlash('warning', "Une erreure est survenue lors de l'ajout de la dépense.");
$this->addFlash('info', $th->getMessage());
}
return $this->redirectToRoute('accounting_expense_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('accounting/accounting_expense/new.html.twig', [
'accounting_expense' => $accountingExpense,
'form' => $form,
]);
}
/**
* @Route("/{id}/edit", name="accounting_expense_edit", methods={"GET","POST"})
*/
public function edit(Request $request, AccountingExpense $accountingExpense, UserRepository $userRepository, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$schoolYear = $user->getSchoolYear();
$establishment = $user->getEstablishment();
$establishment = $this->getUser()->getEstablishment();
$treasuryCheckouts = $treasuryCheckoutRepository->createQueryBuilder('entity')
->innerJoin('entity.establishment', 'establishment')
->addSelect('establishment')
->andWhere('establishment.establishmentGroup = :establishmentGroup')
->setParameter('establishmentGroup', $establishment->getEstablishmentGroup())
->orderBy('entity.label', 'ASC')
->getQuery()
->getResult();
$form = $this->createForm(AccountingExpenseType::class, $accountingExpense)
->add('checkout', EntityType::class, [
'class' => TreasuryCheckout::class,
'choices' => $treasuryCheckoutRepository->findBy(['created_by' => $accountingExpense->getCreatedBy()]),
'required' => false
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if (null == $accountingExpense->getCheckout()) {
$this->addFlash('warning', "Veuillez selectionner une caisse SVP.");
return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()], Response::HTTP_SEE_OTHER);
}
try {
$this->getDoctrine()->getManager()->flush();
$this->addFlash('success', "la dépense a été éditée.");
} catch (\Throwable $th) {
$this->addFlash('warning', "Une erreure est survenue lors de l'édition de la dépense.");
$this->addFlash('info', $th->getMessage());
}
return $this->redirectToRoute('accounting_expense_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('accounting/accounting_expense/edit.html.twig', [
'accounting_expense' => $accountingExpense,
'form' => $form,
'userRepository' => $userRepository,
'treasury_checkouts' => $treasuryCheckouts,
'accounting_expense_categories' => $accountingExpenseCategoryRepository->findBy([], ['name' => 'ASC']),
]);
}
/**
* @Route("/set-category/{id}", name="accounting_expense_set_category", methods={"GET", "POST"})
*/
public function set_category(Request $request, AccountingExpense $accountingExpense, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$establishment = $user->getEstablishment();
$accounting_expense_category = intval($request->request->get('accounting_expense_category'));
$accountingExpenseCategory = $accountingExpenseCategoryRepository->findOneBy(['id' => $accounting_expense_category], []);
if (null == $accountingExpenseCategory) {
$this->addFlash('warning', "Veuillez selectionner une catégorie SVP.");
return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
}
$accountingExpense->setAccountingExpenseCategory($accountingExpenseCategory);
$entityManager = $this->getDoctrine()->getManager();
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué");
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
}
return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
}
/**
* @Route("/aprove/{id}", name="accounting_expense_aprove", methods={"POST", "GET"})
*/
public function aprove(Request $request, AccountingExpense $entity, SMSSender $smsSender, TreasuryCheckoutRepository $treasuryCheckoutRepository): Response
{
/*$idCheckout = intval($request->request->get('checkout'));
$checkout = $treasuryCheckoutRepository->findOneBy(['id' => $idCheckout], []);*/
if (null == $entity->getCheckout()) {
$this->addFlash('warning', "Aucune caisse n'est associé à cette dépense.");
return $this->json(['code' => 500, 'message' => "Aucune caisse n'est associé à cette dépense."], 200);
}
$establishment = $this->getUser()->getEstablishment();
$entityManager = $this->getDoctrine()->getManager();
$entity->setIsAproved(true);
$entity->setAprovedBy($this->getUser()->getId());
$entity->setAprovedAt(new DateTimeImmutable());
$entity->setCheckout($entity->getCheckout());
//notification fondateur
$foundingNotification = new FoundingNotification();
$foundingNotification->setCreateDate(new DateTimeImmutable());
$foundingNotification->setAction("Approuvé");
$foundingNotification->setElement("Dépense: #".$entity->getId());
$foundingNotification->setDescription($entity->getLabel().' Mt: '.number_format($entity->getAmount(), 0, ' ', ',').' Date: '.$entity->getCreatedAt()->format('d/m/Y').' Caisse: '.$entity->getCheckout()->getLabel());
$foundingNotification->setEstablishment($entity->getEstablishment());
$foundingNotification->setIpAddress($request->getClientIp());
$foundingNotification->setSchoolYear($entity->getSchoolYear());
$foundingNotification->setUsername($this->getUser()->getUserIdentifier());
$entityManager->persist($foundingNotification);
/*---------------------------------------------*/
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué");
$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();
$contacts = [];
$contacts[] = '225'.str_replace(' ', '',trim($establishment->getSmsBankPayment()));
$response = $smsSender->sendSmsByEstablishment($establishment, $message, $contacts, $smsSender::UNICODE_CHARSET);
return $this->json(['code' => 200, 'message' => "Traitement effectué :)"], 200);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
return $this->json(['code' => 500, 'message' => $th->getMessage()], 200);
}
//$this->addFlash('warning', "Traitement non effectué");
return $this->json(['code' => 500, 'message' => "Traitement non effectué"], 200);
//return $this->redirectToRoute('accounting_expense_index');
}
/**
* @Route("/cancel/{id}", name="accounting_expense_cancel", methods={"GET"})
*/
public function cancel(AccountingExpense $entity): Response
{
if ($entity->getCashRegister() != null) {
return $this->json(['code' => 500, 'message' => "Impossible un paiement à été effectué sur cette dépense."], 200);
}
$entityManager = $this->getDoctrine()->getManager();
$entity->setIsAproved(true);
$entity->setIsCanceled(true);
$entity->setIsPaid(false);
$entity->setCheckout(null);
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué");
return $this->json(['code' => 200, 'message' => "Traitement effectué :)"], 200);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
}
$this->addFlash('warning', "Traitement non effectué");
return $this->json(['code' => 500, 'message' => "Traitement non effectué"], 200);
}
/**
* @Route("/paid/{id}/{idCashRegister}", name="accounting_expense_paid", methods={"GET"})
*/
public function paid(Request $request, AccountingExpense $entity, $idCashRegister, TreasuryCashRegisterRepository $treasuryCashRegisterRepository, SMSSender $smsSender): Response
{
$establishment = $this->getUser()->getEstablishment();
$entityManager = $this->getDoctrine()->getManager();
$cashRegister = $treasuryCashRegisterRepository->find($idCashRegister);
/*
* 20/08/2022
* si le solde de la caisse est insuffisant pour payer la dépense
* le fondateur à demande de désactiver cette option pour permeetre
* une sortir de caisse même si le solde est insuffisant
*
if ($cashRegister->toForward($treasuryCashRegisterRepository) < $entity->getAmount()) {
return $this->json(['code' => 500, 'message' => "Le solde de la caisse est insuffisant"], 200);
}
*/
$entity->setIsPaid(true);
$entity->setCreateDate(new DateTimeImmutable());
$entity->setCashRegister($cashRegister);
// mouvement de caisse
$cashMovement = new TreasuryCashMovement();
$cashMovement->setAmount($entity->getAmount());
$cashMovement->setAccountingExpense($entity);
$cashMovement->setCashRegister($cashRegister);
$cashMovement->setCode($entity->getId().'-'.time());
$cashMovement->setEstablishment($entity->getEstablishment());
$cashMovement->setType('out');
$cashMovement->setLabel($entity->getLabel());
$entityManager->persist($cashMovement);
/*---------------------------------------------*/
//notification fondateur
$foundingNotification = new FoundingNotification();
$foundingNotification->setCreateDate(new DateTimeImmutable());
$foundingNotification->setAction("Paiement");
$foundingNotification->setElement("Dépense: #".$entity->getId());
$foundingNotification->setDescription($entity->getLabel().' Mt: '.number_format($entity->getAmount(), 0, ' ', ',').' Date: '.$entity->getCreatedAt()->format('d/m/Y'));
$foundingNotification->setEstablishment($entity->getEstablishment());
$foundingNotification->setIpAddress($request->getClientIp());
$foundingNotification->setSchoolYear($entity->getSchoolYear());
$foundingNotification->setUsername($this->getUser()->getUserIdentifier());
$entityManager->persist($foundingNotification);
/*---------------------------------------------*/
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué");
$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();
$contacts = [];
$contacts[] = '225'.str_replace(' ', '',trim($establishment->getSmsBankPayment()));
$response = $smsSender->sendSmsByEstablishment($establishment, $message, $contacts, $smsSender::UNICODE_CHARSET);
return $this->json(['code' => 200, 'message' => "Traitement effectué :)"], 200);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
}
$this->addFlash('warning', "Traitement non effectué");
return $this->json(['code' => 500, 'message' => "Traitement non effectué"], 200);
}
/**
* @Route("/delete-selection", name="accounting_expenses_selected_delete", methods={"GET"})
*/
public function deleteSelected(Request $request, AccountingExpenseRepository $entityRepository): Response
{
$list = $request->get('entities');
$entityManager = $this->getDoctrine()->getManager();
$errors = 0;
foreach ($list as $key => $id) {
$entity = $entityRepository->findOneBy(['id' => intval($id)], []);
if ($entity != null) {
if (!$entity->getIsAproved()) {
$entityManager->remove($entity);
}
}
}
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué");
return $this->json(['code' => 200, 'message' => "Traitement effectué :)"], 200);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
}
$this->addFlash('warning', "Traitement non effectué");
return $this->json(['code' => 500, 'message' => "Traitement non effectué"], 200);
}
/**
* @Route("/report/print", name="accounting_expense_report_print")
*/
public function print_report(Pdf $knpSnappyPdf, Request $request, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpenseRepository $accountingExpenseRepository, UserRepository $userRepository, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$schoolYear = $user->getSchoolYear();
$establishment = $user->getEstablishment();
$dateStart = new DateTimeImmutable($request->get('dateStart'));
$dateEnd = new DateTimeImmutable($request->get('dateEnd'));
$show_state = $request->get('show_state');
$checkout = $treasuryCheckoutRepository->findOneBy(['id' => intval($request->get('checkout'))], []);
$accounting_expense_category = intval($request->get('accounting_expense_category'));
$accountingExpenseCategory = $accountingExpenseCategoryRepository->findOneBy(['id' => $accounting_expense_category], []);
$checkouts = $treasuryCheckoutRepository->findByEtsGroup($establishment);
$submited_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $checkout, $dateStart, $dateEnd, 1, 0, 0, 0, $accountingExpenseCategory);
$aproved_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $checkout, $dateStart, $dateEnd, 0, 1, 0, 0, $accountingExpenseCategory);
$canceled_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $checkout, $dateStart, $dateEnd, 0, 0, 1, 0, $accountingExpenseCategory);
$paid_accounting_expenses = $accountingExpenseRepository->getQueryByStatus($establishment, 0, $checkout, $dateStart, $dateEnd, 0, 0, 0, 1, $accountingExpenseCategory);
$accounting_expenses = new ArrayCollection();
foreach ($submited_accounting_expenses as $key => $submited_accounting_expense) {
$accounting_expenses->add($submited_accounting_expense);
}
foreach ($aproved_accounting_expenses as $key => $aproved_accounting_expense) {
$accounting_expenses->add($aproved_accounting_expense);
}
foreach ($paid_accounting_expenses as $key => $paid_accounting_expense) {
$accounting_expenses->add($paid_accounting_expense);
}
foreach ($canceled_accounting_expenses as $key => $canceled_accounting_expense) {
$accounting_expenses->add($canceled_accounting_expense);
}
$html = $this->renderView('accounting/print/expenses.html.twig', [
'checkouts' => $checkouts,
'accounting_expenses' => $accounting_expenses,
'accountingExpenseCategory' => $accountingExpenseCategory,
'userRepository' => $userRepository,
'dateStart' => $dateStart,
'dateEnd' => $dateEnd,
'checkout' => $checkout,
'show_state' => $show_state,
'school_year' => $schoolYear,
'setting' => $establishment,
'isPaid' => $request->get('isPaid'),
'isAproved' => $request->get('isAproved'),
'isSubmited' => $request->get('isSubmited'),
'isCanceled' => $request->get('isCanceled'),
]);
$file_name = "RAPPORT_DEPENSES_.pdf";
$footer = $this->renderView('print/footer.html.twig', ['setting' => $establishment]);
$header = $this->renderView('print/header.html.twig', ['setting' => $establishment]);
$options = [
'orientation' => 'Portrait',
'header-html' => $header,
'footer-html' => $footer,
'footer-right' => "Page [page] / [toPage]"
];
$knpSnappyPdf->generateFromHtml($html, $this->getParameter('app.app_directory').'/downloads/rapport/' . $file_name, $options, true);
return $this->redirectToRoute('preview', [
'file' => $file_name,
'dir' => 'rapport',
]);
}
/**
* @Route("/api/aprove", name="api_accounting_expense_aprove", methods={"GET"})
* Modifié le 15/04/2024
*/
public function api_aprove(Request $request, AccountingExpenseRepository $entityRepository, SMSSender $smsSender, TreasuryCheckoutRepository $treasuryCheckoutRepository): Response
{
/*$idCheckout = intval($request->get('checkout'));
$checkout = $treasuryCheckoutRepository->findOneBy(['id' => $idCheckout], []);
if (null == $checkout) {
$this->addFlash('warning', "Veuillez selectionner une caisse SVP.");
return $this->json(['code' => 500, 'message' => "Veuillez selectionner une caisse SVP."], 200);
}*/
$establishment = $this->getUser()->getEstablishment();
$entityManager = $this->getDoctrine()->getManager();
$list = $request->get('entities');
$errors = 0;
$success = 0;
foreach ($list as $key => $id) {
$entity = $entityRepository->findOneBy(['id' => intval($id)], []);
if ($entity != null) {
if (null != $entity->getCheckout()) {
if (!$entity->getIsAproved()) {
$success++;
$entity->setIsAproved(true);
$entity->setAprovedBy($this->getUser()->getId());
$entity->setAprovedAt(new DateTimeImmutable());
$entity->setCheckout($entity->getCheckout());
//notification fondateur
$foundingNotification = new FoundingNotification();
$foundingNotification->setCreateDate(new DateTimeImmutable());
$foundingNotification->setAction("Approuvé");
$foundingNotification->setElement("Dépense: #".$entity->getId());
$foundingNotification->setDescription($entity->getLabel().' Mt: '.number_format($entity->getAmount(), 0, ' ', ',').' Date: '.$entity->getCreatedAt()->format('d/m/Y').' Caisse: '.$entity->getCheckout()->getLabel());
$foundingNotification->setEstablishment($entity->getEstablishment());
$foundingNotification->setIpAddress($request->getClientIp());
$foundingNotification->setSchoolYear($entity->getSchoolYear());
$foundingNotification->setUsername($this->getUser()->getUserIdentifier());
$entityManager->persist($foundingNotification);
try {
$entityManager->flush();
$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();
$contacts = [];
$contacts[] = '225'.str_replace(' ', '',trim($establishment->getSmsBankPayment()));
$response = $smsSender->sendSmsByEstablishment($establishment, $message, $contacts, $smsSender::UNICODE_CHARSET);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
}
}else {
$errors++;
}
}else {
$errors++;
}
}
}
/*---------------------------------------------*/
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué, " . $success . "dépense(s) approuvée(s).");/*
$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();
$contacts = [];
$contacts[] = '225'.str_replace(' ', '',trim($establishment->getSmsBankPayment()));
$response = $smsSender->sendSmsByEstablishment($establishment, $message, $contacts, $smsSender::UNICODE_CHARSET); */
return $this->json(['code' => 200, 'message' => "Traitement effectué :), " . $success . " dépense(s) approuvée(s)."], 200);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
return $this->json(['code' => 500, 'message' => $th->getMessage()], 200);
}
//$this->addFlash('warning', "Traitement non effectué");
return $this->json(['code' => 500, 'message' => "Traitement non effectué"], 200);
//return $this->redirectToRoute('accounting_expense_index');
}
/**
* @Route("/api/cancel", name="api_accounting_expense_cancel", methods={"GET"})
*/
public function api_cancel(Request $request, AccountingExpenseRepository $entityRepository): Response
{
$establishment = $this->getUser()->getEstablishment();
$entityManager = $this->getDoctrine()->getManager();
$list = $request->get('entities');
$errors = 0;
$success = 0;
foreach ($list as $key => $id) {
$entity = $entityRepository->findOneBy(['id' => intval($id)], []);
if ($entity != null) {
if ($entity->getCashRegister() == null) {
if (!$entity->getIsPaid()) {
if ($entity->getIsAproved()) {
if (!$entity->getIsCanceled()) {
$success++;
$entity->setIsAproved(true);
$entity->setIsCanceled(true);
$entity->setIsPaid(false);
$entity->setCheckout(null);
}else {
$errors++;
}
}else {
$errors++;
}
}else {
$errors++;
}
}else {
$errors++;
}
}else {
$errors++;
}
}
try {
$entityManager->flush();
$this->addFlash('success', $success . " dépense annulée(s)");
return $this->json(['code' => 200, 'message' => $success . " dépense annulée(s)"], 200);
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
return $this->json(['code' => 500, 'message' => $th->getMessage()], 200);
}
$this->addFlash('warning', "Traitement non effectué");
return $this->json(['code' => 500, 'message' => "Traitement non effectué"], 200);
}
/**
* @Route("/restaure/{id}/{idCheckout}", name="accounting_expense_restaure", methods={"GET", "POST"})
*/
public function restaure($idCheckout, TreasuryCheckoutRepository $treasuryCheckoutRepository, AccountingExpense $accountingExpense, AccountingExpenseCategoryRepository $accountingExpenseCategoryRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$treasuryCheckout = $treasuryCheckoutRepository->findOneBy(['id' => $idCheckout], []);
if (null == $treasuryCheckout) {
$this->addFlash('warning', "Caisse introuvable!");
return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
}
if ($accountingExpense->getCashRegister() != null) {
$this->addFlash('warning', "cette dépense est déjà payé.");
return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
}
$accountingExpense->setIsAproved(true);
$accountingExpense->setIsCanceled(false);
$accountingExpense->setIsPaid(false);
$accountingExpense->setCheckout($treasuryCheckout);
$entityManager = $this->getDoctrine()->getManager();
try {
$entityManager->flush();
$this->addFlash('success', "Traitement effectué");
} catch (\Throwable $th) {
//$th->getMessage()
$this->addFlash('warning', $th->getMessage());
}
return $this->redirectToRoute('accounting_expense_edit', ['id' => $accountingExpense->getId()]);
}
/**
* @Route("/api/chart-expense-by-month", name="api_chart_accounting_expense_by_month")
*/
public function api_chart_expense_by_month(Request $request, AccountingExpenseRepository $accountingExpenseRepository): Response
{
/**@var User $user */
$user = $this->getUser();
$schoolYear = $user->getSchoolYear();
$establishment = $user->getEstablishment();
$year = $request->get('year');
//$year = date('Y');
$expense_months = [];
$expense_year = 0;
$accountingExpenses = $accountingExpenseRepository->createQueryBuilder('entity')
->innerJoin('entity.establishment', 'establishment')
->addSelect('establishment')
->andWhere('establishment.establishmentGroup = :establishmentGroup')
->setParameter('establishmentGroup', $establishment->getEstablishmentGroup())
->andWhere('entity.is_canceled = :is_canceled')
->setParameter('is_canceled', 0)
->andWhere('entity.is_paid = :is_paid')
->setParameter('is_paid', 1)
->andWhere('entity.create_date BETWEEN :startDate AND :endDate')
->setParameter('startDate', $year.'-01-01')
->setParameter('endDate', $year.'-12-31')
->getQuery()
->getResult();
$max = 0;
for ($i=1; $i <= 12; $i++) {
$_year = 0;
$_months = 0;
foreach ($accountingExpenses as $key => $accountingExpense) {
if ($accountingExpense->getCreateDate()->format('Y-m') == $year.'-'.sprintf("%'02s", $i)) {
$_year += $accountingExpense->getAmount();
$_months += $accountingExpense->getAmount();
}
}
if ($_months > $max) {
$max = $_months;
}
$expense_year += $_year;
$expense_months[] = intval($_months);
}
return $this->json([
'code' => 200,
'message' => "ok",
'expense_months' => $expense_months,
'expense_year' => intval($expense_year),
'max' => intval($max),
'interval' => intval($max / 10),
'year' => intval($year),
], 200);
}
}