src/EventSubscriber/CustomerAutoCodeSubscriber.php line 153

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Addressing\City;
  4. use App\Entity\Customer\Customer;
  5. use App\Entity\Customer\CustomerGroup;
  6. use App\Entity\Customer\CustomerActivity;
  7. use App\Entity\Product\Depot;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. final class CustomerAutoCodeSubscriber implements EventSubscriberInterface
  12. {
  13.     /** @var EntityManagerInterface */
  14.     private $em;
  15.     public function __construct(EntityManagerInterface $em)
  16.     {
  17.         $this->em $em;
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             // Génération à la création uniquement
  23.             'sylius.customer.pre_create' => 'onPreCreate',
  24.             // Préservation/Restoration à la mise à jour
  25.             'sylius.customer.pre_update' => 'onPreUpdate',
  26.         ];
  27.     }
  28.     /**
  29.      * Création : si aucun code fourni, on génère à partir du groupe.
  30.      */
  31.     public function onPreCreate(ResourceControllerEvent $event): void
  32.     {
  33.         $customer $event->getSubject();
  34.         if (!$customer instanceof Customer) {
  35.             return;
  36.         }
  37.         // Si un code est déjà renseigné (import ou saisie manuelle), on ne touche pas.
  38.         $currentCode trim((string) $customer->getCode());
  39.         if ($currentCode !== '') {
  40.             return;
  41.         }
  42.         $group $customer->getGroup();
  43.         $category=$group->getCategory();
  44.         if (!$group instanceof CustomerGroup) {
  45.             // Sans groupe, on ne peut pas générer : on laisse tel quel.
  46.             return;
  47.         }
  48.         // Incrément atomique du compteur du groupe
  49. if($category == "STANDARD" or $category == "DIFFUSEUR" ){
  50. $cats = ['STANDARD''DIFFUSEUR'];
  51.          $this->em->createQuery(
  52.             'UPDATE ' CustomerGroup::class . ' g SET g.counter = g.counter + 1 WHERE g.category IN (:cats)'
  53.         )
  54.         ->setParameter('cats'$cats)
  55.         ->execute();
  56. }else{
  57. $cats = ['STANDARD''DIFFUSEUR'];
  58.          $this->em->createQuery(
  59.             'UPDATE ' CustomerGroup::class . ' g SET g.counter = g.counter + 1 WHERE g.category IN (:cats) and g.id <> 91'
  60.         )
  61.         ->setParameter('cats'$cats)
  62.         ->execute();
  63.  $this->em->createQuery(
  64.             'UPDATE ' CustomerGroup::class . ' g SET g.counter = g.counter + 1 WHERE g.id = :id'
  65.         )
  66.         ->setParameter('id'$group->getId())
  67.         ->execute();
  68. }
  69.        
  70.         // Rafraîchir pour relire le counter et le prefix à jour
  71.         $this->em->refresh($group);
  72.         $next   = (int) $group->getCounter();
  73.         $prefix = (string) $group->getCounterPrefix();
  74.         // Padding : utilise getCounterPadLength() si dispo, sinon 5
  75.         $padLength 5;
  76.         if (method_exists($group'getCounterPadLength')) {
  77.             $tryPad = (int) $group->getCounterPadLength();
  78.             if ($tryPad 0) {
  79.                 $padLength $tryPad;
  80.             }
  81.         }
  82. $ville=trim((string) $customer->getDefaultAddress()->getCity());
  83.  $city $this->em->getRepository(City::class)
  84.                 ->createQueryBuilder('c')
  85.                 ->where('LOWER(c.name) = LOWER(:cityName)')
  86.                 ->setParameter('cityName'$ville)
  87.                 ->setMaxResults(1)
  88.                 ->getQuery()
  89.                 ->getOneOrNullResult();
  90.             if($city) {
  91.               
  92.                 $v=$customer->getDefaultAddress();
  93.                 $v->setCityId($city);
  94.                 $v->setAddress1($customer->getDefaultAddress()->getStreet());
  95.             }
  96.     $activity $this->em->getRepository(CustomerActivity::class)
  97.            ->createQueryBuilder('c')
  98.                 ->where('c.id = :acti')
  99.                 ->setParameter('acti'$group)
  100.                 ->setMaxResults(1)
  101.                 ->getQuery()
  102.                 ->getOneOrNullResult();
  103.             if($activity) {
  104.             $customer->setActivity($activity);
  105.             }
  106.         $depot $this->em->getRepository(Depot::class)
  107.            ->createQueryBuilder('c')
  108.                 ->where('c.id = 1')
  109.                 ->setMaxResults(1)
  110.                 ->getQuery()
  111.                 ->getOneOrNullResult();
  112.             if($depot) {
  113.             $customer->setDepot($depot);
  114.             }       
  115.   
  116.         // Concat préfixe + numéro paddé
  117.         $code sprintf('%s%d'$prefix$next);
  118.       
  119.         $repo $this->em->getRepository(Customer::class);
  120.         $attempts 0;
  121.         while ($repo->findOneBy(['code' => $code]) && $attempts 3) {
  122.             $this->em->createQuery(
  123.                 'UPDATE ' CustomerGroup::class . ' g SET g.counter = g.counter + 1 WHERE g.id = :id'
  124.             )
  125.             ->setParameter('id'$group->getId())
  126.             ->execute();
  127.             $this->em->refresh($group);
  128.             $next = (int) $group->getCounter();
  129.             $code sprintf('%s%d'$prefix$next);
  130.             $attempts++;
  131.         }
  132.         $customer->setCode($code);
  133.     }
  134.     /**
  135.      * Mise à jour : on ne régénère pas, on préserve.
  136.      * Si le code arrive vide (formulaire), on restaure la valeur stockée en base.
  137.      */
  138.     public function onPreUpdate(ResourceControllerEvent $event): void
  139.     {
  140.      
  141.         $customer $event->getSubject();
  142.    
  143.         if (!$customer instanceof Customer) {
  144.             return;
  145.         }
  146.         if($customer->getFirstName() == NULL){
  147.             $customer->setFirstName($customer->getCompanyName());
  148.         }
  149.    if($customer->getLastName() == NULL){
  150.             $customer->setLastName($customer->getCompanyName());
  151.         }
  152.             if ( $customer ->getAccountant() == NULL){
  153.                 $customer->setAccountant($customer);
  154.             }
  155.                   if ( $customer ->getShippingContact() == NULL){
  156.                 $customer->setShippingContact($customer);
  157.             }
  158.                   if ( $customer ->getInvoicingContact() == NULL){
  159.                 $customer->setInvoicingContact($customer);
  160.             }
  161.                   if ( $customer ->getFiche1() == NULL){
  162.                 $customer->setFiche1($customer);
  163.             }
  164.                   if ( $customer ->getFiche2() == NULL){
  165.                 $customer->setFiche2($customer);
  166.             }
  167.       
  168.          
  169.          
  170.         // Cas update uniquement (id déjà présent)
  171.         if (null === $customer->getId()) {
  172.             return;
  173.         }
  174.         $submittedCode trim((string) $customer->getCode());
  175.         
  176.         if ($submittedCode !== '') {
  177.           
  178.             return;
  179.         }
  180.         // Si le champ a été envoyé vide (ou non soumis et mis à null), on restaure la valeur d'origine
  181.         $original $this->em->getRepository(Customer::class)->find($customer->getId());
  182.         if ($original instanceof Customer) {
  183.             $originalCode trim((string) $original->getCode());
  184.             if ($originalCode !== '') {
  185.                 $customer->setCode($originalCode);
  186.             }
  187.         }
  188.         
  189.     }
  190. }