src/Controller/WooCommerceController.php line 165

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Nouvelleorder;
  4. use App\Entity\User;
  5. use App\Repository\BonusRepository;
  6. use App\Repository\MonthlyCommissionTotalRepository;
  7. use App\Repository\PaiementRepository;
  8. use App\Service\WooCommerceApiService;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\JsonResponse;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use App\Entity\Orders;
  16. use App\Repository\UserRepository;
  17. use Psr\Log\LoggerInterface;
  18. use Symfony\Contracts\HttpClient\HttpClientInterface;
  19. use App\Service\CommissionService;
  20. use App\Service\GiftService;
  21. /**
  22.  * @Route("/newapimlmfinal")
  23.  */
  24. class WooCommerceController extends AbstractController
  25. {
  26.     private $logger;
  27.     private $wooCommerceApiService;
  28.     private $client;
  29.     private $consumerKey;
  30.     private $consumerSecret;
  31.     private $commissionService;
  32.     private $giftService;
  33.     private  $entityManager ;
  34.     public function __construct(GiftService $giftServiceCommissionService $commissionServicestring $consumerKeystring $consumerSecretHttpClientInterface $client,EntityManagerInterface $entityManagerWooCommerceApiService $wooCommerceApiService LoggerInterface $logger)
  35.     {
  36.         $this->wooCommerceApiService $wooCommerceApiService;
  37.         $this->logger $logger;
  38.         $this->entityManager $entityManager;
  39.         $this->client $client;
  40.         $this->consumerKey $consumerKey;
  41.         $this->consumerSecret $consumerSecret;
  42.         $this->commissionService $commissionService;
  43.         $this->giftService $giftService;
  44.     }
  45.     public function getCustomerDisplayNamebyuser($customerId)
  46.     {
  47.         try {
  48.             $response $this->client->request('GET'"https://biocasemlm-shop.com/wp-json/wc/v3/customers/{$customerId}", [
  49.                 'auth_basic' => [$this->consumerKey$this->consumerSecret],
  50.             ]);
  51.             $customerData $response->toArray();
  52.             return $customerData['last_name']; // Ou tout autre champ
  53.         } catch (\Exception $e) {
  54.             // Log l'erreur et/ou renvoyer une valeur par défaut ou null
  55.         }
  56.     }
  57.     /**
  58.      * @Route("/orders/webhook", name="order_webhook", methods={"POST"})
  59.      */
  60.     public function handleOrderWebhook(BonusRepository $bonusRepository,MonthlyCommissionTotalRepository $commissionTotalRepository,Request $requestLoggerInterface $loggerEntityManagerInterface $entityManager): Response
  61.     {
  62.         $data json_decode($request->getContent(), true);
  63.         if ($data['status'] === 'processing') {
  64.             $cin $this->getCustomerDisplayNamebyuser($data['customer_id']);
  65.             $user $this->entityManager->getRepository(User::class)->findOneBy(['Cin' => $cin]);
  66.             $totalOrder $data['total'];
  67. // Accès au total de l'expédition
  68. // Comme shipping_lines est un tableau, vous devez accéder au premier élément (ou à un élément spécifique) avant de récupérer le total
  69.             $totalShipping $data['shipping_lines'][0]['total'];
  70.             $modedepaiement $data['payment_method'];
  71. // Calcul du total ajusté en soustrayant le total de l'expédition du total de la commande
  72.             $totalAdjusted $totalOrder $totalShipping;
  73.             $existingOrder $entityManager->getRepository(Orders::class)->findOneBy(['numerocommande' => $data['id']]);
  74.             if ($existingOrder) {
  75.                 $logger->info('Order already exists with number: ' $data['id']);
  76.                 return new Response('Order already exists'Response::HTTP_OK); // Ou considérez un autre code de statut si cela doit être traité comme une erreur
  77.             }
  78.             $order = new Orders();
  79.             $order->setStatus($data['status']);
  80.             $order->setNumerocommande($data['id']);
  81.             $order->setTotal($totalAdjusted);
  82.             $order->setDate(new \DateTime());
  83.             $order->setUser($user);
  84.             try {
  85.                 if ($modedepaiement  =='commission_payment'){
  86.                     $bonusTotal $bonusRepository->getTotalUnpaidForUser($user);
  87.                     $commissionTotal $commissionTotalRepository->getTotalUnpaidForUser($user);
  88.                     $totalToPay $bonusTotal $commissionTotal;
  89.                     if($totalToPay $totalOrder)
  90.                     {
  91.                         $totalbbalance =  $user->getBalance() + $totalOrder ;
  92.                         $user->setBalance($totalbbalance);
  93.                     }else{
  94.                         $user->setBalance($totalToPay);
  95.                     }
  96.                 }
  97.                 $entityManager->persist($order);
  98.                 $entityManager->flush();
  99.                 $this->commissionService->calculateAndRecordCommissions($order);
  100.                 $this->giftService->checkAndCreateGiftForUser($order->getUser());
  101.             } catch (\Exception $e) {
  102.                 $response = new Response();
  103.                 $response->setContent('Un problème est survenu lors du traitement de la commande.');
  104.                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
  105.                 // Vous pouvez aussi ajouter des en-têtes si nécessaire, par exemple:
  106.                 // $response->headers->set('Content-Type', 'text/plain');
  107.                 return $response;
  108.             }
  109.             return new Response('Order processed'Response::HTTP_OK);
  110.         }
  111.         return new Response('Webhook received, but no action required'Response::HTTP_OK);
  112.     }
  113.     /**
  114.      * @Route("/commission/balance/{cin}", name="api_commission_balance", methods={"GET"})
  115.      */
  116.     public function getCommissionBalance(PaiementRepository $PaiementRepository $cinUserRepository $userRepositoryBonusRepository $bonusRepositoryMonthlyCommissionTotalRepository $monthlyCommissionRepository): JsonResponse
  117.     {
  118.         $user $userRepository->findOneBy(['Cin' => $cin]);
  119.         if (!$user) {
  120.             return new JsonResponse(['error' => 'Utilisateur non trouvé'], Response::HTTP_NOT_FOUND);
  121.         }
  122.         $bonusTotal $bonusRepository->findTotalUnpaidByUser($user);
  123.         $commissionTotal $monthlyCommissionRepository->findTotalUnpaidByUser($user);
  124.         $totalPayments $PaiementRepository->findTotalPaymentsForUserfinal($user);
  125.         $balanceuser $user->getBalance();
  126.         $balance = ($bonusTotal $commissionTotal) - $balanceuser $totalPayments;
  127.         $balance number_format($balance2'.''');
  128.         if ($commissionTotal == 0) {
  129.             if ($bonusTotal == 0) {
  130.                 return new JsonResponse(['balance' => 0]);
  131.             }
  132.         } else {
  133.             return new JsonResponse(['balance' => $balance]);
  134.         }
  135.     }
  136.     /**
  137.      * @Route("/orders/webhook/new", name="order_webhook_NEW", methods={"POST"})
  138.      */
  139.     public function handleOrderWebhooknouvellecommandNEWe(Request $requestLoggerInterface $loggerEntityManagerInterface $entityManager): Response
  140.     {
  141.         $data json_decode($request->getContent(), true);
  142.         if (!$data) {
  143.             $logger->error('Invalid JSON received.');
  144.             return new Response('Invalid JSON');
  145.         }
  146.         $logger->info('Webhook received: ');
  147.         if (!isset($data['status'])) {
  148.             $logger->error('Missing status in data.');
  149.             return new Response('Invalid data: Missing status'Response::HTTP_BAD_REQUEST);
  150.         }
  151.         if ($data['status'] === 'new') {
  152.             $logger->info('Order with status: ' $data['status']);
  153.             $cin $this->getCustomerDisplayNamebyuser($data['customer_id']);
  154.             $user $this->entityManager->getRepository(User::class)->findOneBy(['Cin' => $cin]);
  155.             $totalOrder $data['total'];
  156. // Accès au total de l'expédition
  157. // Comme shipping_lines est un tableau, vous devez accéder au premier élément (ou à un élément spécifique) avant de récupérer le total
  158.             $totalShipping $data['shipping_lines'][0]['total'];
  159.             $modedepaiement $data['payment_method'];
  160. // Calcul du total ajusté en soustrayant le total de l'expédition du total de la commande
  161.             $totalAdjusted $totalOrder $totalShipping;
  162.             $existingOrder $entityManager->getRepository(Nouvelleorder::class)->findOneBy(['numerocommande' => $data['id']]);
  163.             if ($existingOrder) {
  164.                 $logger->info('Order already exists with number: ' $data['id']);
  165.                 return new Response('Order already exists'Response::HTTP_OK); // Ou considérez un autre code de statut si cela doit être traité comme une erreur
  166.             }
  167.             $nouvelleorder = new Nouvelleorder();
  168.             $nouvelleorder->setStatus($data['status']);
  169.             $nouvelleorder->setNumerocommande($data['id']);
  170.             $nouvelleorder->setTotal($totalAdjusted);
  171.             $nouvelleorder->setDate(new \DateTime());
  172.             $nouvelleorder->setUser($user);
  173.             try {
  174.                 $entityManager->persist($nouvelleorder);
  175.                 $entityManager->flush();
  176.                 $this->commissionService->calculateAndRecordCommissionsNeworders($nouvelleorder);
  177.             } catch (\Exception $e) {
  178.                 $response = new Response();
  179.                 $response->setContent('Un problème est survenu lors du traitement de la commande.');
  180.                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
  181.                 // Vous pouvez aussi ajouter des en-têtes si nécessaire, par exemple:
  182.                 // $response->headers->set('Content-Type', 'text/plain');
  183.                 return $response;
  184.             }
  185.             return new Response('Order processed'Response::HTTP_OK);
  186.         }
  187.         return new Response('Webhook received, but no action required'Response::HTTP_OK);
  188.     }
  189. }