<?php
namespace App\Controller\Admin;
use App\Entity\Affaire;
use App\Entity\Proposition;
use App\Field\PropositionsField;
use App\Filter\AssociationFilter;
use App\Form\CommandeType;
use App\Form\DossierType;
use App\Form\FactureType;
use App\Form\PropositionType;
use App\Repository\AffaireRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityBuiltEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Filter\ArrayFilter;
use EasyCorp\Bundle\EasyAdminBundle\Filter\BooleanFilter;
use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
use EasyCorp\Bundle\EasyAdminBundle\Filter\TextFilter;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AffaireCrudController extends AbstractCrudController implements EventSubscriberInterface
{
private $affaireRepository;
/**
* @var AdminUrlGenerator
*/
private $adminUrlGenerator;
function __construct(AffaireRepository $affaireRepository, AdminUrlGenerator $adminUrlGenerator) {
$this->affaireRepository = $affaireRepository;
$this->adminUrlGenerator = $adminUrlGenerator;
}
public static function getEntityFqcn(): string
{
return Affaire::class;
}
public function configureFilters(Filters $filters): Filters
{
return $filters
->add(EntityFilter::new('client'))
->add(TextFilter::new('site'))
->add(TextFilter::new('siteContact'))
->add(EntityFilter::new('responsable'))
// ->add(TextFilter::new('responsable.nom'))
// ->add(TextFilter::new('responsable.trigramme'))
// ->add(TextFilter::new('avancement')->mapped(false))
->add(AssociationFilter::new('propositions'))
// ->add(BooleanFilter::new('isDeleted'))
;
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->setPageTitle('index', 'Affaires')
->setDefaultSort(['numeroAffaire' => 'DESC'])
->setSearchFields([
'numeroAffaire',
'objet',
'site',
'siteContact',
'client.societe',
'client.contactNom',
'client.contactPrenom',
'categorie.libelleCourt',
'categorie.libelleLong',
'responsable.nom',
'responsable.prenom',
'responsable.trigramme',
'propositions.objet',
'propositions.avancement',
'propositions.categorie',
])
->overrideTemplate('main_menu', 'admin/menu.html.twig')
;
}
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
$queryBuilder = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
$queryBuilder->andWhere("entity.isDeleted = 0 or entity.isDeleted is null");
return $queryBuilder;
}
public function configureFields(string $pageName): iterable
{
$fields = [
// Affaire généralités
FormField::addPanel(),
TextField::new('numeroAffaire')
->setLabel('Numéro')
->setTemplatePath('field/linkedit.html.twig')
->setFormTypeOption('disabled','disabled')
->setColumns(1),
AssociationField::new('responsable')->setLabel('Resp')->setFormTypeOption(
'query_builder', function (UserRepository $userRepository){
return $userRepository->findCollaborateurs();
})->setColumns(1),
AssociationField::new('agence')
->setLabel('Agence')
->setRequired(false)
->setColumns(2),
AssociationField::new('client')->setColumns(3),
TextField::new('site')
->setLabel('Site étude')
->addCssClass('site-field')
->setColumns(2),
TextField::new('siteContact')->setLabel('Site contact')->setColumns(3),
];
// Propositions - suivi commercial
$fields[] = PropositionsField::new('propositions')
->onlyOnIndex()
->setSortable(false);
$fields[] = CollectionField::new('propositions')
->hideOnIndex()
->formatValue(function ($value) {
return $value->getAvancement()->contains("validée") ? "validée" : "Pas validée";
})
->setEntryIsComplex()
->useEntryCrudForm(PropositionCrudController::class)
->setLabel('Proposition / Suivi commercial')
->setColumns(12);
$fieldsSuite = [
// Suivi technique / Rapports
CollectionField::new('dossiers')
->hideOnIndex()
->setEntryIsComplex()
->setEntryType(DossierType::class)
->setLabel('Dossier / Suivi technique')
->setColumns(12),
// Site
FormField::addPanel(),
BooleanField::new('copyClientSite')->setLabel('Copier les coordonnées du client')->hideOnIndex()->setColumns(12 ),
TextField::new('siteContactTel')->setLabel('Téléphone contact')->hideOnIndex()->setColumns(2),
TextField::new('siteContactMail')->setLabel('Mail contact')->hideOnIndex()->setColumns(3),
TextField::new('siteAdresse')->setLabel('Adresse')->hideOnIndex()->setColumns(4),
TextField::new('siteCodePostal')->setLabel('CP')->hideOnIndex()->setColumns(1),
TextField::new('siteVille')->setLabel('Ville')->hideOnIndex()->setColumns(2),
];
return array_merge($fields, $fieldsSuite);
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['addAffaire'],
BeforeEntityUpdatedEvent::class => ['updateAffaire'],
// AfterEntityBuiltEvent::class => ['setPropositions'],
// AfterEntityBuiltEvent::class => ['processAffaire'],
];
}
public function processAffaire(AfterEntityBuiltEvent $event)
{
// $entity = $event->getEntity();
// $entity->setProposition1("Prop " . "blabla");
}
public function updateAffaire(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Affaire)) {
return;
}
if ($entity->isCopyClientSite()){
$this->processClientSite($entity);
}
$this->processPropositions($entity);
}
public function addAffaire(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Affaire)) {
return;
}
$this->setNumeroAffaire($entity);
$this->processPropositions($entity);
}
public function setNumeroAffaire(Affaire $entity): void
{
$newNumAffaire = $this->affaireRepository->getNewNumAffaire(date('Y'));
$entity->setNumeroAffaire($newNumAffaire);
$entity->setCreatedAt(new \DateTime('now'));
}
// public function setPropositions(AfterEntityBuiltEvent $event)
// {
// $entity = $event->getEntity()->getInstance();
// $entity->setProposition1("Ceci est la prop 1");
// }
public function edit(AdminContext $context)
{
if ($context->getRequest()->query->has('duplicate')) {
$entity = $context->getEntity()->getInstance();
/** @var Affaire $clonedAffaire */
$clonedAffaire = clone $entity;
$clonedAffaire->setCreatedAt(new \DateTime('now'));
$clonedAffaire->setDuplicate(true);
$propositions = $entity->getPropositions();
if($propositions && count($propositions) > 0){
$newProp = new Proposition();
$p1 = $propositions[0];
// $newProp = clone $p1;
// $newProp = clone $p1;
$newProp->setObjet($p1->getObjet());
$newProp->setCategorie($p1->getCategorie());
$newProp->setMontantHT($p1->getMontantHT());
}
foreach ($propositions as $prop) {
// /** @var Proposition $clonedProp */
// $clonedProp = clone $prop;
$clonedAffaire->removeProposition($prop);
// //TODO remove factures et sous traitance ?
//// foreach ()
// $clonedAffaire->addProposition($clonedProp);
}
if ($newProp)
$clonedAffaire->addProposition($newProp);
$this->setNumeroAffaire($clonedAffaire);
$context->getRequest()->query->remove('duplicate');
// $context->getRequest()->query->set('crudAction', 'new');
$context->getEntity()->setInstance($clonedAffaire);
}
return parent::edit($context);
}
public function configureActions(Actions $actions): Actions
{
$duplicate = Action::new('duplicate', 'Dupliquer')
->setIcon('fa fa-copy')
->linkToUrl(
function (Affaire $entity) {
return $this->adminUrlGenerator
->setAction(Action::EDIT)
->setEntityId($entity->getId())
->set('duplicate', '1')
->generateUrl();
}
);
$actions
->add(Crud::PAGE_INDEX, $duplicate)
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action) {
return $action->setIcon('fa fa-file-alt');
})
->update(Crud::PAGE_EDIT, Action::SAVE_AND_CONTINUE, function (Action $action) {
$action->displayIf(static function ($entity) {
// dump($entity);
return !$entity->isDuplicate();
// return $entity->getSite() == "Ecole d'Ussacccc";
});
return $action->setIcon('fa fa-file-alt');
});;
$actions
->remove(Crud::PAGE_INDEX, Action::DELETE);
return parent::configureActions($actions);
}
/**
* @param Affaire $entity
* @return void
*/
private function processPropositions(Affaire $entity): void
{
foreach ($entity->getPropositions() as $proposition) {
foreach ($proposition->getCommandes() as $commande) {
$commande->setProposition($proposition);
}
// if($proposition->getFactures()->count() > 0) {
// $toutesFacturesSoldees = true;
// foreach ($proposition->getFactures() as $facture) {
// $facture->setProposition($proposition);
// if(!$facture->isSoldee()) {
// $toutesFacturesSoldees = false;
// }
// }
// } else {
// $toutesFacturesSoldees = false;
// }
if ($proposition->isValide()) {
$proposition->setAvancement("Commande soldée");
// } elseif ($proposition->isValide()) {
// $proposition->setAvancement("Commande validée");
} else if ($proposition->getDateValidite() !== null) {
$proposition->setAvancement("Commande validée");
} elseif ($proposition->getDateEnvoi() !== null) {
$proposition->setAvancement("Devis envoyé");
} else {
$proposition->setAvancement("Préparation devis");
}
$entity->setProposition1("Prop " . $proposition->getAvancement());
}
}
private function processClientSite(Affaire $entity)
{
if($entity->getClient() != null){
$entity->setSiteContactMail($entity->getClient()->getEmail());
$entity->setSiteContactTel($entity->getClient()->getTelephone());
$entity->setSiteAdresse($entity->getClient()->getAdresse());
$entity->setSiteCodePostal($entity->getClient()->getCodePostal());
$entity->setSiteVille($entity->getClient()->getVille());
}
}
}