<?php
namespace App\Controller\Admin;
use App\Entity\Article;
use App\Entity\CommandArticle;
use App\Entity\Commande;
use App\Entity\User;
use App\Service\NotificationManager;
use DateTime;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use App\Form\CommandArticleType;
use App\Repository\AdresseRepository;
use App\Repository\GouvernoratRepository;
use App\Repository\UniteRegionalRepository;
use Doctrine\ORM\EntityManager;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\RequestStack;
use Knp\Component\Pager\PaginatorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
use EasyCorp\Bundle\EasyAdminBundle\Config\Asset;
use EasyCorp\Bundle\EasyAdminBundle\Field\HiddenField;
use App\Service\ExportExl;
use EasyCorp\Bundle\EasyAdminBundle\Filter\ArrayFilter;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
class CommandeCrudController extends AbstractCrudController
{
public $em;
private $adminUrlGenerator;
private $request;
/**
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em, RequestStack $request, AdminUrlGenerator $adminUrlGenerator)
{
$this->em = $em;
$this->adminUrlGenerator = $adminUrlGenerator;
}
public static function getEntityFqcn(): string
{
return Commande::class;
}
public function configureAssets(Assets $assets): Assets
{
return $assets->addJsFile(Asset::new('js/commandJs.js')->defer());
}
public function configureFields(string $pageName): iterable
{
return [
HiddenField::new('id')->hideOnIndex(),
AssociationField::new('user', 'nom utilisateur')->hideOnForm(),
DateField::new('date', 'Date')->setFormTypeOption('disabled', 'disabled')->setFormTypeOption('disabled', 'disabled'),
Field::new('tel','Tel')->setFormTypeOption('disabled', 'disabled')->setFormTypeOptions(["attr" => ['min' => '0', 'maxlength' => 8 ,'pattern'=>'\d{8}', 'oninput'=>"this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"]])->setRequired(true),
TextField::new('email', 'Email')->setFormTypeOption('disabled', 'disabled'),
TextField::new('etat', 'Etat')->setFormTypeOption('disabled', 'disabled'),
// TextareaField::new('motifs', 'Motif de refus')->hideOnIndex(),
NumberField::new('totalPrice')->setFormTypeOption('disabled', 'disabled')->hideOnIndex(),
// CollectionField::new('commandes', 'Commandes')
// ->allowAdd(true)
// ->allowDelete(true)
// ->setEntryIsComplex(true)
// ->setEntryType(CommandArticleType::class)
// ->setFormTypeOptions([
// 'by_reference' => 'true',
// 'mapped' => true,
// 'required' => true
// ])->hideOnIndex()
];
}
public function configureActions(Actions $actions): Actions
{
$excelExport = Action::new('excelExport', 'Excel')
->setIcon('fa fa-download')
->linkToCrudAction('excelExport')
->setCssClass('btn')
->createAsGlobalAction();
$actions->add(Crud::PAGE_INDEX, Action::DETAIL)
->add(Crud::PAGE_INDEX, $excelExport)
->remove(Crud::PAGE_INDEX, Action::NEW)
->remove(Crud::PAGE_DETAIL, Action::EDIT)
->remove(Crud::PAGE_EDIT, Action::SAVE_AND_CONTINUE)
->remove(Crud::PAGE_EDIT, Action::SAVE_AND_RETURN)
->remove(Crud::PAGE_INDEX, Action::DETAIL)
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->setLabel('Visualiser');
})
->update(Crud::PAGE_NEW, Action::SAVE_AND_RETURN, function (Action $action) {
return $action->setLabel('Enregistrer');
});
;
$valider = Action::new('valider', 'Valider', 'fa fa-check-circle')
->linkToCrudAction('validerLCommande')->displayIf(static function ($entity) {
return $entity->getEtat() == 'En cours';
});
$refuser = Action::new('refuser', 'Refuser', 'fa fa-ban')
->linkToUrl("#")->setHtmlAttributes(['id' => 'refuseBtn'])->displayIf(static function ($entity) {
return $entity->getEtat() == 'En cours';
});
return $actions
->add(Crud::PAGE_EDIT, $valider)
// ->add(Crud::PAGE_EDIT, $refuser)
->add(Crud::PAGE_INDEX, $valider)
;
}
public function validerLCommande(EntityManagerInterface $entityManager, RouterInterface $router ,AdminContext $context , NotificationManager $notificationManager)
{
$lcommande = $context->getEntity()->getInstance();
$lCommandArticle = $entityManager->getRepository(CommandArticle::class)->findBy([
'Commande' => $lcommande->getId()
]);
foreach ($lCommandArticle as $commandArticle) {
$qnt = 0;
$qnt = $commandArticle->getQuantite();
$article = $commandArticle->getArticle()->getId();
$larticleRepository = $entityManager->getRepository(Article::class);
$larticleRepository->updateArticleQuantity($commandArticle);
}
$lcommande->setEtat('Valide');
$entityManager->persist($lcommande);
$entityManager->flush();
$url = $this->adminUrlGenerator
->setController(CommandeCrudController::class)
->setAction(Action::INDEX)
->setEntityId($lcommande->getId())
->generateUrl();
$urlCommande = $router->generate('command_detail', ['id' => $lcommande->getId()]);
$user = $entityManager->getRepository(User::class)->find($lcommande->getUser());
$notification_message = 'Votre Commande a été validée !' . $lcommande->getId() . ' ';
$notificationManager->pushMessage('Votre Commande a été validée !', $notification_message, $user, $urlCommande);
return $this->redirect($url);
}
// public function refuserLCommande(RequestStack $request, EntityManagerInterface $entityManager, AdminContext $context)
// {
// $lcommande = $context->getEntity()->getInstance();
// // $lcommande->setMotifs($context->getEntity()->getInstance()->getMotifs());
// $lcommande->setEtat('Refuse');
// $entityManager->persist($lcommande);
// $entityManager->flush();
// $url = $this->adminUrlGenerator
// ->setController(CommandeCrudController::class)
// ->setAction(Action::EDIT)
// ->setEntityId($lcommande->getId())
// ->generateUrl();
// return $this->redirect($url);
// }
final public function configureCrud(Crud $crud): Crud
{
return $crud
->setPageTitle(Crud::PAGE_INDEX, 'Liste des Commandes')
->overrideTemplates([
//'crud/new' => 'admin/Commande/Commande_edit.html.twig',
'crud/edit' => 'admin/commande/commande_edit.html.twig',
]);
}
#[Route('/delete/command/article/{id}/{parentId}', name: 'delete_command_article')]
public function showByEquipeDetail(CommandArticle $commande, $parentId, Request $request, EntityManagerInterface $entityManager): Response
{
$id = $commande->getId();
$url = $this->adminUrlGenerator
->setController(CommandeCrudController::class)
->setAction(Action::EDIT)
->setEntityId($parentId)
->generateUrl();
$entityManager->remove($commande);
$entityManager->flush();
return $this->redirect($url);
}
#[Route('/show/cart', name: 'show_cart')]
public function showCart(RequestStack $requestStack, EntityManagerInterface $entityManager): Response
{
$session = $requestStack->getSession();
$listCommand = $session->get('listCommand', []);
$somme = 0;
$newList = [];
foreach ($listCommand as $elem) {
$ca = new CommandArticle();
$find = $entityManager->getRepository(Article::class)->find($elem['id']);
$ca->setArticle($find);
$ca->setQuantite($elem['quantity']);
$somme = $somme + ($find->getPrix() * $elem['quantity']);
$ca->setPrixUnitaire($find->getPrix());
array_push($newList, $ca);
}
return $this->render('commande/index.html.twig', ['listCommand' => $newList, 'somme' => $somme]);
}
#[Route('/make/command/delete/{id}', name: 'make_command_delete')]
public function deleteCommand($id, RequestStack $requestStack): Response
{
$session = $requestStack->getSession();
$listCommand = $session->get('listCommand', []);
$exist = false;
$i = 0;
while ($i < count($listCommand) && $exist == false) {
if ($listCommand[$i]['id'] == $id) {
$exist = true;
array_splice($listCommand, $i, 1);
} else {
$i++;
}
}
$session->set('listCommand', $listCommand);
//return $this->render('commande/index.html.twig',['listCommand' => $listCommand]);
return $this->redirectToRoute('show_cart');
}
#[Route('/make/article/delete/{id}', name: 'make_article_delete')]
public function deleteCommand2(CommandArticle $command, EntityManagerInterface $entityManager): JsonResponse
{
$entityManager->remove($command);
$entityManager->flush();
return new JsonResponse(['data' => $command], Response::HTTP_OK, ['Content-Type', 'application/json']);
}
#[Route('/delete/command/{id}', name: 'delete_command')]
public function deleteCommand3(Commande $command, EntityManagerInterface $entityManager): Response
{
//dd($command);
$entityManager->remove($command);
$entityManager->flush();
return $this->redirectToRoute('index_article');
}
/**
* @Route("/make/command", name="make_command", methods={"POST"})
*/
public function add(Request $request, RequestStack $requestStack, SerializerInterface $serializer, Security $security): JsonResponse
{
$session = $requestStack->getSession();
$listCommand = $session->get('listCommand', []);
$data = json_decode($request->getContent(), true);
$exist = false;
$i = 0;
while ($i < count($listCommand) && $exist == false) {
if ($listCommand[$i]['id'] == $data['id']) {
$exist = true;
} else {
$i++;
}
}
if ($exist == true) {
$listCommand[$i]['quantity'] = $data["quantity"];
} else {
array_push($listCommand, $data);
}
$session->set('listCommand', $listCommand);
return new JsonResponse(['data' => $listCommand], Response::HTTP_OK, ['Content-Type', 'application/json']);
}
/**
* @Route("/make/command/after/save/{id}/{quantity}", name="make_command_after_save", methods={"POST"})
*/
public function addAfterSave(CommandArticle $command, $quantity, Request $request, EntityManagerInterface $entityManager): JsonResponse
{
$command->setQuantite($quantity);
$entityManager->persist($command);
$entityManager->flush();
return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type', 'application/json']);
}
/**
* @Route("/refuse/command/{id}/{motifs}", name="refuse_command", methods={"POST"})
*/
public function refuseCommand(Commande $command, $motifs, Request $request, EntityManagerInterface $entityManager): JsonResponse
{
$command->setMotifs($motifs);
$command->setEtat('Refuse');
$entityManager->persist($command);
$entityManager->flush();
return new JsonResponse(['data' => 'done'], Response::HTTP_OK, ['Content-Type', 'application/json']);
}
#[Route('/make/command/confirm', name: 'make_command_confirm')]
public function showByArticleDetail(Request $request, EntityManagerInterface $entityManager,
Security $security, RequestStack $requestStack,
GouvernoratRepository $gouvernoratRepository,
UniteRegionalRepository $uniteRegionalRepository,
AdresseRepository $adresseRepository,
NotificationManager $notificationManager
): Response
{
// $data = json_decode($request->getContent(), true);
$session = $requestStack->getSession();
$listCommandArticle = $session->get('listCommand', []);
$edit_demande_url = $this->adminUrlGenerator
->setController(CommandeCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
if (count($listCommandArticle) > 0) {
$commande = new Commande();
$sommeT = 0;
foreach ($listCommandArticle as $elem) {
$somme = 0;
$commandeArticle = new CommandArticle();
$find = $entityManager->getRepository(Article::class)->find($elem['id']);
$commandeArticle->setArticle($find);
$commandeArticle->setQuantite($elem['quantity']);
$somme = $somme + ($find->getPrix() * $elem['quantity']);
$commandeArticle->setPrixUnitaire($find->getPrix());
// $entityManager->persist($commandeArticle);
$commande->addCommande($commandeArticle);
$sommeT = $sommeT + $somme;
}
$commande->setTotalPrice($sommeT);
$commande->setDate(new \DateTime());
$commande->setMotifs("");
$commande->setEmail($request->request->get('email', ' '));
$commande->setAdresse($request->request->get('adresse', ' '));
$commande->setTel($request->request->get('tel', ' '));
$commande->setUser($security->getUser());
$uniteRegionals = $uniteRegionalRepository->findAll();
foreach($uniteRegionals as $uniteRegional){
$adresse = $adresseRepository->findOneBy(
[
'id' => $uniteRegional->getAdresse(),
'gouvernorat' => (int)$request->request->get('gouvernourat', null)
]);
}
$gouv = $gouvernoratRepository->findOneBy(['id' => (int)$request->request->get('gouvernourat', null)]);
$commande->setGouvernorat($gouv);
if($adresse){
$commande->setAdresseUNITE($adresse->getAdresse());
$commande->setCODEPOSTALUNITE($adresse->getCodePostale());
}
$listCommand = [];
$session->set('listCommand', $listCommand);
$this->addFlash('success', 'votre commande a bien été envoyée!');
$entityManager->persist($commande);
$entityManager->flush();
$notification_message = 'Nouvelle Commande ! ';
$admins = $this->em->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach($admins as $admin){
$notificationManager->pushMessage('Nouvelle Commande !', $notification_message, $admin, $edit_demande_url);
}
}
//return $this->render('commande/index.html.twig',['listCommand' => $listCommand, 'somme' => $sommeT]);
//return $this->redirectToRoute('show_article_detail', ['id' => $article->getId()]);
return $this->redirectToRoute('show_cart');
}
#[Route('/command/detail/{id}', name: 'command_detail')]
public function detailCommand(Commande $command,
EntityManagerInterface $entityManager,
UniteRegionalRepository $uniteRegionalRepository,
AdresseRepository $adresseRepository
): Response
{
$somme = 0;
foreach ($command->getCommandes() as $elem) {
$somme = $somme + ($elem->getPrixUnitaire() * $elem->getQuantite());
}
$command->setTotalPrice($somme);
$entityManager->persist($command);
$entityManager->flush();
$gouv = $command->getGouvernorat()->getId();
$unite_regional = $uniteRegionalRepository->findByGouvernorat($gouv);
if (!empty($unite_regional)) {
$adresse = $adresseRepository->findById($unite_regional[0]->getAdresse()->getId());
$adresse = $adresse[0]; // Access the first element if it exists
$unite_regional = $unite_regional[0];
$adresseEtat = true;
} else {
// Handle the case when the address is not found
// You can set $adresse to a default value or show an error message.
// For example, you can set $adresse to an empty array:
$adresse = [];
$unite_regional=[];
$adresseEtat = false;
}
return $this->render('commande/commande_detail.html.twig', [
'command' => $command,
'unite_regional' =>$unite_regional,
'adresseEtat' =>$adresseEtat,
'adresse' => $adresse]);
}
#[Route('/command/history/', name: 'command_history')]
public function historyCommand(Security $security, Request $request, EntityManagerInterface $entityManager, PaginatorInterface $paginator): Response
{
$donnees = $entityManager->getRepository(Commande::class)->findBy(["user" => $security->getUser()], ['id' => 'DESC']);
$commands = $paginator->paginate(
$donnees,
$request->query->getInt('page', 1),
10
);
return $this->render('commande/commande_history.html.twig', ['commands' => $commands]);
}
public function excelExport(EntityManagerInterface $entityManager, ExportExl $exportExlService) {
$data = $entityManager->getRepository(Commande::class)->findAll();
$file_full_name = $exportExlService->xlsExportModel($data);
return $this->file($file_full_name);
}
public function configureFilters(Filters $filters): Filters
{
return $filters
->add(ArrayFilter::new('etat', 'Etat')->setChoices(array_combine(Commande::STATUS_ARRAY, Commande::STATUS_ARRAY)));
}
#[Route('/notif/countCommandArticleByUser', name: 'count_command_article_by_user')]
public function countCommandArticleByUser(RequestStack $requestStack, EntityManagerInterface $entityManager): JsonResponse
{
$session = $requestStack->getSession();
$listCommand = $session->get('listCommand', []);
$count = 0;
$newList = [];
foreach ($listCommand as $elem) {
$ca = new CommandArticle();
$find = $entityManager->getRepository(Article::class)->find($elem['id']);
$ca->setArticle($find);
$ca->setQuantite($elem['quantity']);
$count = $count + 1;
}
return $this->json(['count' => $count]);
}
}