<?php
namespace App\EventSubscriber;
use App\Entity\ProductLigneFacture;
use App\Entity\ProductStock;
use App\Entity\ProductStockMouvement;
use App\Event\Produit\ReceptionProduitEvent;
use App\Event\Produit\StockMvtEvent;
use App\Repository\ProductLigneFactureRepository;
use App\Repository\ProductStockRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ReceptionProduitSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var ProductLigneFactureRepository
*/
private $productLigneFactureRepository;
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
public function __construct(EntityManagerInterface $entityManager, ProductLigneFactureRepository $productLigneFactureRepository,
EventDispatcherInterface $eventDispatcher)
{
$this->entityManager = $entityManager;
$this->productLigneFactureRepository = $productLigneFactureRepository;
$this->eventDispatcher = $eventDispatcher;
}
public static function getSubscribedEvents(): array
{
return [
ReceptionProduitEvent::class => ['onReceptionProduit', 100],
];
}
// Ajout des produits en stock lors de la récpetion
public function onReceptionProduit(ReceptionProduitEvent $event)
{
$facture = $event->getFacture();
$commande = $facture->getCommande();
$request = $event->getRequest();
$lignes = $facture->getCommande()->getLignes();
// Enregistrement des produits reçus
foreach ($lignes as $ligne) {
$ligneFacture = $this->productLigneFactureRepository->findOneBy(['facture' => $facture, 'ligne' => $ligne]);
$quantiteRecu = (int)$request->get('qte_'.$ligne->getId());
$mouvementdestock = $quantiteRecu;
if ($quantiteRecu > 0) {
$prixFacture = (float)$request->get('montant_'.$ligne->getId());
if (!$ligneFacture) {
$ligneFacture = new ProductLigneFacture();
$ligneFacture->setFacture($facture)
->setLigne($ligne);
} else {
$mouvementdestock = $quantiteRecu - $ligneFacture->getQuantiteRecue();
}
$ligneFacture->setQuantiteRecue($quantiteRecu)
->setPrixFactureHt($prixFacture);
$this->entityManager->persist($ligneFacture);
if ($mouvementdestock != 0) {
// Ajout des produits en stock
$mvt = new ProductStockMouvement();
$mvt->setProduct($ligne->getProduct())
->setStructure($commande->getStructure())
->setDateMouvement(new \Datetime())
->setQuantite(abs($mouvementdestock))
->setTypeMouvement($mouvementdestock > 0 ? 'in' : 'out')
->setCommentaire('Réception commande '.$commande->getId());
$this->entityManager->persist($mvt);
$this->entityManager->persist($mvt);
$this->entityManager->flush();
$this->eventDispatcher->dispatch(new StockMvtEvent($mvt));
}
}
}
}
}