<?php
namespace App\EventSubscriber;
use App\Entity\Product;
use App\Event\Produit\ProductCommandeEvent;
use App\Repository\EtatLivraisonRepository;
use App\Repository\ProductCommandeRepository;
use App\Repository\ProductRepository;
use App\Service\ProductHelper;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductCommandeSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var EtatLivraisonRepository
*/
private $etatLivraisonRepository;
/**
* @var ProductHelper
*/
private $productHelper;
/**
* @var ProductRepository
*/
private $productRepository;
/**
* @var ProductCommandeRepository
*/
private $commandeRepository;
public function __construct(EntityManagerInterface $entityManager, EtatLivraisonRepository $etatLivraisonRepository, ProductHelper $productHelper,
ProductRepository $productRepository, ProductCommandeRepository $commandeRepository)
{
$this->entityManager = $entityManager;
$this->etatLivraisonRepository = $etatLivraisonRepository;
$this->productHelper = $productHelper;
$this->productRepository = $productRepository;
$this->commandeRepository = $commandeRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductCommandeEvent::class => ['onCommandeCreated', 100],
];
}
public function onCommandeCreated(ProductCommandeEvent $event)
{
$commande = $event->getCommande();
$request = $event->getRequest()->get('new_commande_produit');
$etat = $this->etatLivraisonRepository->findOneBy(['identifiant' => 'pre-commande']);
if ($request && isset($request['product'])) {
// On ajoute la ligne du produit, on recherche le meilleur tarif
/**
* @var Product $product
*/
$product = $this->productRepository->find($request['product']);
$quantite = (int)$request['quantite'];
$bestTarif = $this->productHelper->getBestTarif($product);
$commande->setFournisseur($bestTarif->getFournisseur());
$this->productHelper->add_pre_order($product->getId(), $commande->getStructure()->getId(), $commande->getFournisseur()->getId(), $quantite, $commande->getId());
}
// On ajoute les mails par défaut pour l'envoi de la commande
// Mail du fournisseur + mail du créateur de la commande
$emails = [$commande->getFournisseur()->getEmail(), $commande->getUser()->getLogin()];
$commande->setEmail(implode(",", array_filter(array_unique($emails))));
// On ajoute l'état de pré commande
$commande->setEtat($etat);
// Numéro de commande
$numero = $this->commandeRepository->getNextNumero();
$commande->setNumero($numero);
// Mise à jour du montant total
$ttc = $ht = 0;
foreach ($commande->getLignes() as $l) {
$ttc += $l->getTotalTtc();
$ht += $l->getTotalHt();
}
$commande->setTotalHt($ht)->setTotalTtc($ttc);
$this->entityManager->persist($commande);
$this->entityManager->flush();
}
}