src/Service/MarketPlace/EbayService.php line 323

Open in your IDE?
  1. <?php
  2. namespace App\Service\MarketPlace;
  3. use App\Entity\Articles\ArticleComposant;
  4. use App\Entity\Articles\Categorie;
  5. use App\Entity\GestionComerciale\ArticleCommande;
  6. use App\Entity\GestionComerciale\ModeExpedition;
  7. use App\Entity\GestionComerciale\ModeExpeditionPoidsTransporteur;
  8. use App\Entity\GestionComerciale\ModeReglement;
  9. use App\Model\GestionCommerciale\TypeDocumentCommercial;
  10. use App\Entity\Taxes\Taxe;
  11. use App\Service\Articles\DeviseService;
  12. use App\Service\Clients\ClientService;
  13. use App\Service\GestionComerciale\AcompteService;
  14. use App\Service\GestionComerciale\CommandeService;
  15. use App\Service\GestionComerciale\EmailService;
  16. use App\Service\GestionComerciale\ModeExpeditionService;
  17. use App\Service\GestionComerciale\NumerotationDocumentService;
  18. use App\Service\Taxes\TaxeService;
  19. use Doctrine\ORM\EntityManager;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Symfony\Component\DependencyInjection\Container;
  22. use App\Entity\FO\Societe;
  23. use App\Entity\Traductions\Traduction;
  24. use App\Entity\MarketPlace\CompteMarketPlace;
  25. use App\Entity\MarketPlace\ArticleMarketPlace;
  26. use App\Entity\MarketPlace\ArticleMarketPlaceImage;
  27. use App\Entity\Articles\Article;
  28. use App\Entity\MarketPlace\HistoriqueArticleMarketPlace;
  29. use App\Entity\GestionComerciale\Commande;
  30. use App\Entity\MarketPlace\ErreurPublicationArticleMarketPlace;
  31. use App\Entity\GestionComerciale\Acompte;
  32. //require __DIR__.'/../../../../web/ebay-api/vendor/autoload.php';
  33. //require __DIR__."/../../../../web/ebay-api/order/XML_Serializer-0.21.0/XML/Serializer.php";
  34. /**
  35.  * The namespaces provided by the SDK.
  36.  */
  37. use \DTS\eBaySDK\Constants;
  38. use \DTS\eBaySDK\Trading\Services;
  39. use \DTS\eBaySDK\Trading\Types;
  40. use \DTS\eBaySDK\Trading\Enums;
  41. use \DTS\eBaySDK\Product\Services as ProductService;
  42. use \DTS\eBaySDK\Product\Types as ProductTypes;
  43. use \DTS\eBaySDK\Product\Enums as ProductEnums;
  44. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  45. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  46. use Symfony\Component\Serializer\Serializer;
  47. class EbayService
  48. {
  49.     private $em;
  50.     private $filters;
  51.     private $config;
  52.     private $siteId;
  53.     //private $service;
  54.     //private $compteMarketPlace;
  55.     private NumerotationDocumentService $numerotationDocumentService;
  56.     private ArticleMarketPlaceService $articleMarketPlaceService;
  57.     private ClientService $clientService;
  58.     private CommandeService $commandeService;
  59.     private AcompteService $acompteService;
  60.     private TaxeService $taxeService;
  61.     private EmailService $emailService;
  62.     private MarketPlaceService $marketPlaceService;
  63.     private ModeExpeditionService $modeExpeditionService;
  64.     private DeviseService $deviseService;
  65.     public function __construct(EntityManagerInterface $emNumerotationDocumentService $numerotationDocumentServiceArticleMarketPlaceService $articleMarketPlaceService,
  66.                                 ClientService          $clientServiceCommandeService $commandeServiceAcompteService $acompteServiceTaxeService $taxeService,
  67.                                 EmailService           $emailServiceMarketPlaceService $marketPlaceServiceModeExpeditionService $modeExpeditionServiceDeviseService $deviseService
  68.     ) {
  69.         $this->em     $em;
  70.         $this->siteId Constants\SiteIds::FR;
  71.         /*
  72.         $this->compteMarketPlace = $em->getRepository(CompteMarketPlace::class)->find(11);
  73.         /*
  74.         ebay_client_id: CazinSAR-Test-PRD-572546526-9ea7c340
  75.         ebay_client_id_dev: ID4a96ec78-dfae-45f5-b190-f410f01a8607
  76.         ebay_client_secret: PRD-72546526c41c-714f-4efc-b412-1881
  77.         //$this->config = require __DIR__.'/../../../../web/ebay-api/configuration.php';
  78.         if(is_object($this->compteMarketPlace)){
  79.             $this->service = new Services\TradingService([
  80.                 //'authorization' => $this->getAuthToken(),
  81.                 'credentials' => array(
  82.                     'devId' => $this->compteMarketPlace->getDevID(),
  83.                     'appId' => $this->compteMarketPlace->getIdentifiant(),
  84.                     'certId' => $this->compteMarketPlace->getSecret(),
  85.                 ),
  86.                 'sandbox'     => false,
  87.                 'siteId'      => $this->siteId
  88.             ]);
  89.         }
  90.         */
  91.         //$this->authToken = $this->config['production']['authToken'];
  92.         $this->numerotationDocumentService $numerotationDocumentService;
  93.         $this->articleMarketPlaceService   $articleMarketPlaceService;
  94.         $this->clientService               $clientService;
  95.         $this->commandeService             $commandeService;
  96.         $this->acompteService              $acompteService;
  97.         $this->taxeService                 $taxeService;
  98.         $this->emailService                $emailService;
  99.         $this->marketPlaceService          $marketPlaceService;
  100.         $this->modeExpeditionService       $modeExpeditionService;
  101.         $this->deviseService               $deviseService;
  102.     }
  103.     public function getTradingService($compteMarketPlace$output '')
  104.     {
  105.         $service '';
  106.         if (is_object($compteMarketPlace)) {
  107.             $service = new Services\TradingService([
  108.                                                        'credentials' => [
  109.                                                            'devId'  => $compteMarketPlace->getDevID(),
  110.                                                            'appId'  => $compteMarketPlace->getIdentifiant(),
  111.                                                            'certId' => $compteMarketPlace->getSecret(),
  112.                                                        ],
  113.                                                        'sandbox' => false,
  114.                                                        'siteId'  => $this->siteId,
  115.                                                    ]);
  116.         }
  117.         return $service;
  118.     }
  119.     public function getProductService($compteMarketPlace)
  120.     {
  121.         $service '';
  122.         if (is_object($compteMarketPlace)) {
  123.             $service = new ProductService\ProductService([
  124.                                                              'credentials' => [
  125.                                                                  'devId'  => $compteMarketPlace->getDevID(),
  126.                                                                  'appId'  => $compteMarketPlace->getIdentifiant(),
  127.                                                                  'certId' => $compteMarketPlace->getSecret(),
  128.                                                              ],
  129.                                                              'globalId'    => Constants\GlobalIds::MOTORS,
  130.                                                              //'globalId'    => Constants\GlobalIds::FR
  131.                                                              'sandbox'     => false,
  132.                                                              'siteId'      => $this->siteId,
  133.                                                          ]);
  134.         }
  135.         return $service;
  136.     }
  137.     public function getAuthToken($compteMarketPlace$output '')
  138.     {
  139.         if (is_object($compteMarketPlace)) {
  140.             $this->em->refresh($compteMarketPlace);
  141.             $dateValiditeAuthToken $compteMarketPlace->getDateValiditeAuthToken();
  142.             $dateValiditeAuthToken->modify('- 5 minutes');
  143.             $authToken $compteMarketPlace->getAuthToken();
  144.             if ($dateValiditeAuthToken > (new \Datetime)) {
  145.                 if (is_object($output)) {
  146.                     $output->writeln('Auth token en cours de validité');
  147.                 }
  148.                 return $authToken;
  149.             }
  150.             //verifier la validite
  151.             //$authToken = 'frrrrr';
  152.             /*
  153.             $url = 'https://api.ebay.com/buy/browse/v1/item/get_item_by_legacy_id?';
  154.                 $url .= 'legacy_item_id=000000';
  155.                 //$url = 'https://api.ebay.com/buy/browse/v1/item/V1|'.$itemId.'|0?';
  156.                 //$url .= 'legacy_item_id=string&';
  157.                 //$url .= 'legacy_variation_id=string&';
  158.                 //$url .= 'legacy_variation_sku=string&';
  159.                 $url .= 'fieldgroups=PRODUCT';
  160.                 $ch = curl_init();
  161.                 curl_setopt($ch, CURLOPT_URL, $url);
  162.                 //curl_setopt($ch, CURLOPT_POST, 1);
  163.                 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  164.                     //'Content-Type: application/json',
  165.                     'Accept: application/json',
  166.                     'Authorization: Bearer '.$authToken,
  167.                     'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  168.                     //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  169.                 ));
  170.                     //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  171.                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  172.                 $retour = curl_exec($ch);
  173.                 //print_r($retour);
  174.                 $retour = json_decode($retour);
  175.                 if(is_object($output)) print_r($retour);
  176.                 if(is_object($retour) && !empty($retour->errors) && $retour->errors[0]->errorId == '1001'){
  177.                     //pb Invalid access token
  178.                     if(is_object($output)) $output->writeln('Invalid access token');
  179.                 } else {
  180.                     return $authToken;
  181.                 }
  182.                 */
  183.             //return '';
  184.             /*
  185.             if(!empty($authToken) && is_object($dateValiditeAuthToken) && $dateValiditeAuthToken > (new \Datetime)){
  186.                 return $authToken;
  187.             }
  188.             */
  189.             /*
  190.             if($this->container->getParameter('ebay_prod')){
  191.                 $url = 'https://api.ebay.com/identity/v1/oauth2/token';
  192.                 $ebay_client_id = $this->container->getParameter('ebay_client_id');
  193.                 $ebay_client_secret = $this->container->getParameter('ebay_client_secret');
  194.             } else {
  195.                 $url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token';
  196.                 $ebay_client_id = $this->container->getParameter('ebay_client_id_dev');
  197.                 $ebay_client_secret = $this->container->getParameter('ebay_client_secret');
  198.             }
  199.             */
  200.             if (is_object($output)) {
  201.                 $output->writeln('Début renouvellement Auth');
  202.             }
  203.             $url                'https://api.ebay.com/identity/v1/oauth2/token';
  204.             $ebay_client_id     $compteMarketPlace->getIdentifiant();
  205.             $ebay_client_secret $compteMarketPlace->getSecret();
  206.             //var_dump($url);
  207.             //var_dump($ebay_client_id);
  208.             //var_dump($ebay_client_secret);
  209.             $authorization base64_encode($ebay_client_id.':'.$ebay_client_secret);
  210.             $scopes = [
  211.                 'https://api.ebay.com/oauth/api_scope',//   View public data from eBay
  212.                 //'https://api.ebay.com/oauth/api_scope/sell.marketing',//  View and manage your eBay marketing activities, such as ad campaigns and listing promotions
  213.                 //'https://api.ebay.com/oauth/api_scope/sell.inventory',//  View and manage your inventory and offers
  214.                 //'https://api.ebay.com/oauth/api_scope/sell.account',//    View and manage your account settings
  215.                 //'https://api.ebay.com/oauth/api_scope/sell.onboarding',// Share your merchant profile data with eBay
  216.                 //'https://api.ebay.com/oauth/api_scope/sell.fulfillment',//
  217.             ];
  218.             $scopes = [
  219.                 'https://api.ebay.com/oauth/api_scope',
  220.                 'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
  221.                 'https://api.ebay.com/oauth/api_scope/sell.marketing',
  222.                 'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
  223.                 'https://api.ebay.com/oauth/api_scope/sell.inventory',
  224.                 'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
  225.                 'https://api.ebay.com/oauth/api_scope/sell.account',
  226.                 'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
  227.                 'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
  228.                 'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
  229.                 'https://api.ebay.com/oauth/api_scope/sell.finances',
  230.                 'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
  231.                 'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
  232.             ];
  233.             $scope  urlencode(implode(' '$scopes));
  234.             $scope  implode(' '$scopes);
  235.             /*
  236.             $post_data = array(
  237.                 'grant_type' => 'client_credentials',
  238.                 'scope' => $scope
  239.             );
  240.             var_dump($scope);
  241.             */
  242.             $post_data = [
  243.                 'grant_type'    => 'refresh_token',
  244.                 'refresh_token' => $compteMarketPlace->getRefreshToken(),
  245.                 'scope'         => $scope,
  246.             ];
  247.             //var_dump(http_build_query($post_data));
  248.             $ch curl_init();
  249.             curl_setopt($chCURLOPT_URL$url);
  250.             curl_setopt($chCURLOPT_POST1);
  251.             curl_setopt($chCURLOPT_HTTPHEADER, [
  252.                 'Content-Type: application/x-www-form-urlencoded',
  253.                 'Authorization: Basic '.$authorization,
  254.             ]);
  255.             curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($post_data));
  256.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  257.             $retour curl_exec($ch);
  258.             //var_dump($retour);
  259.             $retour json_decode($retourtrue);
  260.             $err    curl_error($ch);
  261.             curl_close($ch);
  262.             //var_dump($err);
  263.             //if(is_object($output)) print_r($retour);
  264.             if (is_object($output)) {
  265.                 $output->writeln('Fin renouvellement Auth');
  266.             }
  267.             if ( ! empty($retour['access_token'])) {
  268.                 //echo $retour['access_token'];
  269.                 $date = new \Datetime();
  270.                 $date->modify('+ '.floatval($retour['expires_in']).'seconds');
  271.                 $compteMarketPlace->setDateValiditeAuthToken($date);
  272.                 $compteMarketPlace->setAuthToken($retour['access_token']);
  273.                 $this->em->persist($compteMarketPlace);
  274.                 $this->em->flush();
  275.                 return $retour['access_token'];
  276.             }
  277.         }
  278.         return '';
  279.     }
  280.     public function getOrders2($compteMarketPlace$hours 15$output ''$donnee$count 0)
  281.     {
  282.         $repo_compte_market_place $this->em->getRepository(CompteMarketPlace::class);
  283.         $compteMarketPlaceId      $compteMarketPlace->getId();
  284.         //https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/methods/getOrders
  285.         /*
  286.         GET https://api.ebay.com/sell/fulfillment/v1/order?
  287.         orderIds=string&
  288.         filter=FilterField&
  289.         limit=string&
  290.         offset=string&
  291.         fieldGroups=string
  292.         */
  293.         //'224358007693-2533745807012';//RU
  294.         //'124232724894-2390972902002';//FR
  295.         $date_debut = new \DateTime('UTC');
  296.         //22-07096-37205
  297.         date_modify($date_debut'- '.$hours.' hours');
  298.         $compteur_boucle_pagination  0;
  299.         $continuer_boucle_pagination true;
  300.         $parameters ''
  301.                       //.'orderIds=27-07599-22085'
  302.                       //.'orderIds=07-07812-51390'
  303.                       .'&filter='.rawurlencode('lastmodifieddate:['.$date_debut->format('Y-m-d\TH:i:s\.000\Z').'..]')
  304.                       //.'&limit=500'
  305.                       .'&limit=20'
  306.             //.'&offset=string'
  307.             //.'&fieldGroups=TAX_BREAKDOWN'
  308.         ;
  309.         //$parameters = 'orderIds=21-07691-36968';
  310.         //$parameters = 'orderIds=23-07692-87805';
  311.         $url 'https://api.ebay.com/sell/fulfillment/v1/order?'.$parameters;
  312.         while ($continuer_boucle_pagination) {
  313.             //$continuer_boucle_pagination = false;
  314.             $compteur_boucle_pagination++;
  315.             if (is_object($output)) {
  316.                 $output->writeln('url : '.$url);
  317.             }
  318.             //return;
  319.             $authToken $this->getAuthToken($compteMarketPlace);
  320.             if (empty($authToken)) {
  321.                 return $authToken;
  322.             }
  323.             $ch curl_init();
  324.             curl_setopt($chCURLOPT_URL$url);
  325.             //curl_setopt($ch, CURLOPT_POST, 1);
  326.             curl_setopt($chCURLOPT_HTTPHEADER, [
  327.                 'Content-Type: application/json',
  328.                 'Authorization: Bearer '.$authToken,
  329.                 'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  330.             ]);
  331.             //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  332.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  333.             $retour curl_exec($ch);
  334. //          $directory = __DIR__."/../../../../web/ebay-api/ORDERS/EXPORT/".date("Y/m/d");
  335.             $file    $directory."/export_orders_ebay_".$compteMarketPlace->getId()."_".date("dmY")."-".$compteur_boucle_pagination.".json";
  336.             $dirname dirname($file);
  337.             if ( ! is_dir($dirname)) {
  338.                 mkdir($dirname0755true);
  339.             }
  340.             $fp fopen($file'w') or die("Erreur d'écriture du fichier");
  341.             fwrite($fp$retour);
  342.             fclose($fp);
  343.             //var_dump($retour);
  344.             $retour json_decode($retourtrue);
  345.             //var_dump($retour);
  346.             $err curl_error($ch);
  347.             curl_close($ch);
  348.             //$file = "/data/www/tl/cazin.local.tl/www/src/DTC/MarketPlaceBundle/Services/../../../../web/ebay-api/ORDERS/EXPORT/2021/04/19/export_orders_ebay_11_19042021.json";
  349.             $json   file_get_contents($file);
  350.             $retour json_decode($jsontrue);
  351.             if (is_object($output)) {
  352.                 $output->writeln("TEST ".$file);
  353.             }
  354.             //exit;
  355.             /*
  356.             if(empty($retour['total']) && $compteur_boucle_pagination == 1){
  357.               //il faut remonter à la dernière commande
  358.               $hours = 24;
  359.               $count++;
  360.               if($count < 2) $this->getOrders2($compteMarketPlace, $hours, $output, $donnee, $count);
  361.             }
  362.             */
  363.             if ( ! empty($retour['total']) && ! empty($retour['orders'])) {
  364.                 if (is_object($output)) {
  365.                     $output->writeln('Nb de commandes : '.count($retour['orders']));
  366.                 }
  367.                 $compteur_boucle 1;
  368.                 foreach ($retour['orders'] as $order) {
  369.                     if (is_object($output)) {
  370.                         $output->writeln('Commande '.$compteur_boucle.'/'.count($retour['orders']));
  371.                     }
  372.                     //if($compteur_boucle == 1) print_r($order);
  373.                     $compteur_boucle++;
  374.                     try {
  375.                         //$this->traiterCommande2($compteMarketPlace, $order, $output, $donnee);
  376.                         //if($order["orderId"] == "10-07210-53488" or 1==1) {
  377.                         $output->writeln($order["orderId"]);
  378.                         //if($compteur_boucle == 2) print_r($order);
  379.                         //rechercher si la commande a été saisie manuellement
  380.                         $commande $this->em->getRepository(Commande::class)->findOneBy(['referenceClient' => $order["orderId"]]);
  381.                         if (is_object($commande)) {
  382.                         } elseif ($order["orderId"] == "06-07343-90360" or == 1) {//
  383.                             //print_r($order);
  384.                             $this->traiterCommande2($compteMarketPlace$order$output$donnee);
  385.                             if ($compteur_boucle 10 == 0) {
  386.                                 $this->em->clear();
  387.                                 $compteMarketPlace $repo_compte_market_place->find($compteMarketPlaceId);
  388.                             }
  389.                             //echo "fintest";
  390.                             //exit;
  391.                         }
  392.                     } catch (\Exception $e) {
  393.                         //var_dump($order);
  394.                         $output->writeln('Exception');
  395.                         $output->writeln($e->getMessage());
  396.                         //envoyer un email
  397.                         $this->emailService->envoyerEmailErrorCron("Erreur dans le traitement de la commande ebay ".$order["orderId"].' '.$e->getMessage());
  398.                     }
  399.                     //break;
  400.                     if ($order["orderId"] == "18-07178-25982") {
  401.                         //echo "STOPSTOP";
  402.                         //exit;
  403.                     }
  404.                 }
  405.                 if ( ! empty($retour['next'])) {
  406.                     $url $retour['next'];
  407.                 } else {
  408.                     $continuer_boucle_pagination false;
  409.                 }
  410.             } else {
  411.                 if (is_object($output)) {
  412.                     $output->writeln('Aucune commande!');
  413.                 }
  414.                 $continuer_boucle_pagination false;
  415.                 //erreurs?
  416.             }
  417.         }
  418.     }
  419.     public function getApiAccessRules($compteMarketPlace$output '')
  420.     {
  421.         //$authToken = $this->getAuthToken();
  422.         $authToken $this->getAuthToken($compteMarketPlace$output);
  423.         if (empty($authToken)) {
  424.             return $authToken;
  425.         }
  426.         $request                                      = new Types\GetApiAccessRulesRequestType();
  427.         $request->RequesterCredentials                = new Types\CustomSecurityHeaderType();
  428.         $request->RequesterCredentials->eBayAuthToken $authToken;
  429.         $response                                     = @$this->getTradingService($compteMarketPlace)->getApiAccessRules($request);
  430.         /*
  431.         $request = new Types\GeteBayOfficialTimeRequestType();
  432.         $request->RequesterCredentials = new Types\CustomSecurityHeaderType();
  433.         $request->RequesterCredentials->eBayAuthToken = $authToken;
  434.         $request->RequesterCredentials->authorization = $authToken;
  435.         $response = $this->service->geteBayOfficialTime($request);
  436.         */
  437.         return $response;
  438.     }
  439.     public function getMyeBaySellingRequestType($compteMarketPlace$output '')
  440.     {
  441.         if (is_object($output)) {
  442.             $output->writeln('getMyeBaySellingRequestType');
  443.         }
  444.         $authToken $this->getAuthToken($compteMarketPlace);
  445.         if (empty($authToken)) {
  446.             return $authToken;
  447.         }
  448.         $request = new Types\GetMyeBaySellingRequestType();
  449.         /**
  450.          * An user token is required when using the Trading service.
  451.          */
  452.         $request->RequesterCredentials                = new Types\CustomSecurityHeaderType();
  453.         $request->RequesterCredentials->eBayAuthToken $authToken;
  454.         /**
  455.          * Request that eBay returns the list of actively selling items.
  456.          * We want 10 items per page and they should be sorted in descending order by the current price.
  457.          */
  458.         $request->ActiveList                             = new Types\ItemListCustomizationType();
  459.         $request->ActiveList->Include                    true;
  460.         $request->ActiveList->Pagination                 = new Types\PaginationType();
  461.         $request->ActiveList->Pagination->EntriesPerPage 10;
  462.         //$request->ActiveList->DurationInDays = 1;
  463.         //$request->ActiveList->Sort = Enums\ItemSortTypeCodeType::C_CURRENT_PRICE_DESCENDING;
  464.         $request->ActiveList->Sort Enums\ItemSortTypeCodeType::C_START_TIME_DESCENDING;
  465.         $pageNum 1;
  466.         $s          "ItemID;Title;currencyID;CurrentPriceId;CurrentPriceValue;PictureDetails";
  467.         $s          "ItemID;Title;CurrentPriceId;CurrentPriceValue;Quantity;PictureDetails;SKU;StartTime;EAN;NbVendus";
  468.         $string_csv $s;
  469.         $string_csv .= "\n";
  470.         //$string_csv .= chr(13);
  471.         //echo $s;
  472.         $directory "";
  473. //    $file = __DIR__."/../../../../web/ebay-api/PRODUCTS/".date("Y")."/".date("m")."/".date("d")."/export_ebay_".$compteMarketPlace->getId()."_".date("dmY").".csv";
  474.         $dirname dirname($file);
  475.         if ( ! is_dir($dirname)) {
  476.             mkdir($dirname0755true);
  477.         }
  478.         do {
  479.             $request->ActiveList->Pagination->PageNumber $pageNum;
  480.             $response                                    = @$this->getTradingService($compteMarketPlace)->getMyeBaySelling($request);
  481.             if (isset($response->Errors)) {
  482.                 foreach ($response->Errors as $error) {
  483.                     /*
  484.                     printf(
  485.                         "%s: %s\n%s\n\n",
  486.                         $error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning',
  487.                         $error->ShortMessage,
  488.                         $error->LongMessage
  489.                     );
  490.                     */
  491.                 }
  492.             }
  493.             $cpt 0;
  494.             //print_r($response);
  495.             //break;
  496.             //echo "<div>atp ".$response->ActiveList->PaginationResult->TotalNumberOfPages."</div>";
  497.             //echo "<div>pageNum ".$pageNum."</div>";
  498.             if ($response->Ack !== 'Failure' && isset($response->ActiveList)) {
  499.                 foreach ($response->ActiveList->ItemArray->Item as $item) {
  500.                     /*printf(
  501.                         "(%s) %s: %s %.2f\n",
  502.                         $item->ItemID,
  503.                         $item->Title,
  504.                         $item->SellingStatus->CurrentPrice->currencyID,
  505.                         $item->SellingStatus->CurrentPrice->value
  506.                     );
  507.                     */
  508.                     if ($cpt == 0) {
  509.                         /*foreach($item as $k=>$v) {
  510.                             print_r($k);
  511.                             print_r($v);
  512.                         }
  513.                         */
  514.                         //echo "<div>------------------------------------------------</div>";
  515.                         //print_r($item->PictureDetails);
  516.                         //exit;
  517.                     }
  518.                     $cpt++;
  519.                     //print_r($item);
  520.                     //exit;
  521.                     $s trim($item->ItemID).";"
  522.                          .trim($item->Title).";"
  523.                          .trim($item->SellingStatus->CurrentPrice->currencyID).";"
  524.                          .trim($item->SellingStatus->CurrentPrice->value).";"
  525.                          //.$item->Seller->UserID.";"
  526.                          .trim($item->Quantity).";"
  527.                          .trim(stripslashes($item->PictureDetails->GalleryURL)).";"
  528.                          .trim($item->SKU).";"
  529.                          .trim($item->ListingDetails->StartTime->format("dmY")).";";
  530.                     if ( ! empty($item->ProductListingDetails) && is_object($item->ProductListingDetails)) {
  531.                         $s .= trim($item->ProductListingDetails->EAN).";";
  532.                     } else {
  533.                         $s .= ";";
  534.                     }
  535.                     $s .= trim($item->SellingStatus->QuantitySold).";";
  536.                     //if(is_object($output)) $output->writeln('getMyeBaySellingRequestType t4');
  537.                     if (is_object($output)) {
  538.                         $output->writeln($s);
  539.                     }
  540.                     $string_csv .= utf8_decode($s);
  541.                     $string_csv .= "\n";
  542.                     //$string_csv .= chr(13);
  543.                     //  echo "<div>".utf8_decode($s)."</div>";
  544.                     //exit;
  545.                 }
  546.             }
  547.             $pageNum += 1;
  548.         } while (isset($response->ActiveList));//&& $pageNum <= 1
  549.         $fp fopen($file'w') or die("Erreur d'écriture du fichier");
  550.         fwrite($fp$string_csv);
  551.         fclose($fp);
  552.     }
  553.     public function getItem($articleMarketPlace$detailLevel 'ReturnAll'$authToken ''$count 0)
  554.     {
  555.         $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  556.         if (empty($authToken)) {
  557.             $authToken $this->getAuthToken($compteMarketPlace);
  558.         }
  559.         //$authToken = $this->getAuthToken($compteMarketPlace);
  560.         if (empty($authToken)) {
  561.             return $authToken;
  562.         }
  563.         $request                                      = new Types\GetItemRequestType();
  564.         $request->RequesterCredentials                = new Types\CustomSecurityHeaderType();
  565.         $request->RequesterCredentials->eBayAuthToken $authToken;
  566.         $request->ItemID                              $articleMarketPlace->getIdImport();//$item->ItemID;
  567.         $request->DetailLevel[]                       = $detailLevel;
  568.         $request->IncludeItemCompatibilityList        true;
  569.         try {
  570.             $response = @$this->getTradingService($compteMarketPlace)->getItem($request);
  571.         } catch (\Exception $e) {
  572.             $count++;
  573.             sleep(1);
  574.             $response $this->getItem($articleMarketPlace$detailLevel''$count);
  575.         }
  576.         if (isset($response->Errors)) {
  577.             foreach ($response->Errors as $error) {
  578.                 if (in_array($error->ErrorCode, [518'518'])) {
  579.                     return $response;
  580.                 }
  581.             }
  582.         }
  583.         if (isset($response->Errors) && $count 3) {
  584.             $count++;
  585.             sleep(1);
  586.             $response $this->getItem($articleMarketPlace$detailLevel''$count);
  587.         }
  588.         if (isset($response->Errors)) {
  589.             $date                 = new \Datetime();
  590.             $dateNonRenouvellable = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"))->modify('- 90 days');
  591.             $endTime              $articleMarketPlace->getEndTime();
  592.             foreach ($response->Errors as $error) {
  593.                 if (in_array($error->ErrorCode, [17'17']) && is_object($endTime) && $endTime $dateNonRenouvellable) {
  594.                     //$output->writeln('Annonce non renouvelable');
  595.                     $conn $this->em->getConnection();
  596.                     $conn->getConfiguration()->setSQLLogger(null);
  597.                     $tableau_donnee["statut_article_market_place_id"] = 2;//publié
  598.                     $tableau_donnee["statut"]                         = 0;
  599.                     $tableau_donnee["visible"]                        = 0;
  600.                     $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlace->getId()]);
  601.                     $this->supprimerErreur($articleMarketPlace->getIdImport());
  602.                     return $response;
  603.                 }
  604.             }
  605.             $this->creerErreur($response$articleMarketPlace->getIdImport(), '''MarketPlaceEnvoiArticle getItem');
  606.         } else {
  607.             $this->supprimerErreur($articleMarketPlace->getIdImport());
  608.         }
  609.         return $response;
  610.     }
  611.     public function getItem2($compteMarketPlace$itemId$output '')
  612.     {
  613.         $authToken $this->getAuthToken($compteMarketPlace);
  614.         if (empty($authToken)) {
  615.             return $authToken;
  616.         }
  617.         $url 'https://api.ebay.com/buy/browse/v1/item/V1|'.$itemId.'|0?';
  618.         //$url .= '&fieldgroups=PRODUCT';
  619.         if (is_object($output)) {
  620.             $output->writeln($url);
  621.         }
  622.         $ch curl_init();
  623.         curl_setopt($chCURLOPT_URL$url);
  624.         //curl_setopt($ch, CURLOPT_POST, 1);
  625.         curl_setopt($chCURLOPT_HTTPHEADER, [
  626.             'Content-Type: application/json',
  627.             'Authorization: Bearer '.$authToken,
  628.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  629.         ]);
  630.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  631.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  632.         $retour curl_exec($ch);
  633.         return json_decode($retour);
  634.     }
  635.     public function getItemByLegacyId($compteMarketPlace$itemId$output '')
  636.     {
  637.         $authToken $this->getAuthToken($compteMarketPlace);
  638.         if (empty($authToken)) {
  639.             return $authToken;
  640.         }
  641.         #https://developer.ebay.com/api-docs/buy/browse/resources/item/methods/getItemByLegacyId
  642.         $url 'https://api.ebay.com/buy/browse/v1/item/get_item_by_legacy_id?';
  643.         $url .= 'legacy_item_id='.$itemId;
  644.         //$url = 'https://api.ebay.com/buy/browse/v1/item/V1|'.$itemId.'|0?';
  645.         //$url .= 'legacy_item_id=string&';
  646.         //$url .= 'legacy_variation_id=string&';
  647.         //$url .= '&legacy_variation_sku=KC01104';
  648.         $url .= '&fieldgroups=PRODUCT';
  649.         if (is_object($output)) {
  650.             $output->writeln($url);
  651.         }
  652.         $ch curl_init();
  653.         curl_setopt($chCURLOPT_URL$url);
  654.         //curl_setopt($ch, CURLOPT_POST, 1);
  655.         curl_setopt($chCURLOPT_HTTPHEADER, [
  656.             //'Content-Type: application/json',
  657.             'Accept: application/json',
  658.             'Authorization: Bearer '.$authToken,
  659.             'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  660.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  661.         ]);
  662.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  663.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  664.         $retour curl_exec($ch);
  665.         return json_decode($retour);
  666.     }
  667.     public function getProductCompatibilities2($compteMarketPlace$sku$output '')
  668.     {
  669.         //https://developer.ebay.com/devzone/xml/docs/reference/ebay/types/ItemCompatibilityListType.html
  670.         //https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/product_compatibility/methods/getProductCompatibility
  671.         $authToken $this->getAuthToken($compteMarketPlace);
  672.         if (empty($authToken)) {
  673.             return $authToken;
  674.         }
  675.         #https://developer.ebay.com/api-docs/buy/browse/resources/item/methods/getItemByLegacyId
  676.         $url    'https://api.ebay.com/sell/inventory/v1/inventory_item/A'.$sku.'0/product_compatibility';
  677.         $itemId '274265966060';
  678.         $itemId $sku;
  679.         $url    'https://api.ebay.com/buy/browse/v1/item/'.$itemId.'/check_compatibility';
  680.         if (is_object($output)) {
  681.             $output->writeln($url);
  682.         }
  683.         $ch curl_init();
  684.         curl_setopt($chCURLOPT_URL$url);
  685.         //curl_setopt($ch, CURLOPT_POST, 1);
  686.         curl_setopt($chCURLOPT_HTTPHEADER, [
  687.             //'Content-Type: application/json',
  688.             //'Accept: application/json',
  689.             'Authorization: Bearer '.$authToken,
  690.             'Content-Language: fr-FR',
  691.             //'Accept-Language: fr-FR',
  692.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  693.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  694.         ]);
  695.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  696.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  697.         $retour curl_exec($ch);
  698.         return json_decode($retour);
  699.     }
  700.     public function getProductCompatibilities($compteMarketPlace$ePID$output '')
  701.     {
  702.         $authToken $this->getAuthToken($compteMarketPlace);
  703.         //if(empty($authToken)) return $authToken;
  704.         $request = new ProductTypes\GetProductCompatibilitiesRequest();
  705.         //$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
  706.         //$request->RequesterCredentials->eBayAuthToken = $authToken;
  707.         //$request->ItemID = $itemId;//$item->ItemID;
  708.         $request->dataset = ['DisplayableProductDetails'];
  709.         /**
  710.          * Assign the ePID.
  711.          */
  712.         $request->productIdentifier = new ProductTypes\ProductIdentifier();
  713.         //$request->productIdentifier->ePID = '193042315';
  714.         $request->productIdentifier->ePID $ePID;
  715.         //$request->productIdentifier->ePID = '228436781';
  716.         //$request->productIdentifier->EAN = $ean;
  717.         //$request->productIdentifier->EAN = '3306430033692';
  718.         //$request->productIdentifier->SKU = 'SC22141';
  719.         //$request->productIdentifier->productId = '4C67E8DA7C7042FBBA03C1313F47A5A4';
  720.         //$request->productIdentifier->UPC = '4C67E8DA7C7042FBBA03C1313F47A5A4';
  721.         /**
  722.          * Limit the results to 10 items per page.
  723.          */
  724.         $request->paginationInput                 = new ProductTypes\PaginationInput();
  725.         $request->paginationInput->entriesPerPage 10;
  726.         $pageNum 1;
  727.         $retour  = [];
  728.         do {
  729.             $request->paginationInput->pageNumber $pageNum;
  730.             /**
  731.              * Send the request.
  732.              */
  733.             $response $this->getProductService($compteMarketPlace)->getProductCompatibilities($request);
  734.             print_r($response);
  735.             /**
  736.              * Output the result of calling the service operation.
  737.              */
  738.             if (is_object($output)) {
  739.                 $output->writeln("==================Results for page ".$pageNum."==================");
  740.             }
  741.             if (isset($response->errorMessage)) {
  742.                 foreach ($response->errorMessage->error as $error) {
  743.                     printf(
  744.                         "%s: %s\n\n",
  745.                         $error->severity === ProductEnums\ErrorSeverity::C_ERROR 'Error' 'Warning',
  746.                         $error->message
  747.                     );
  748.                 }
  749.             }
  750.             $countTmp 0;
  751.             if ($response->ack !== 'Failure') {
  752.                 if ( ! empty($response->compatibilityDetails)) {
  753.                     foreach ($response->compatibilityDetails as $details) {
  754.                         if ($countTmp == 0) {
  755.                             print_r($details);
  756.                         }
  757.                         $countTmp++;
  758.                         //if(is_object($output)) $output->writeln('==================Compatibility==================');
  759.                         $tmp = [];
  760.                         foreach ($details->productDetails as $detail) {
  761.                             //printf("\n%s :", $detail->propertyName);
  762.                             //print_r($detail);
  763.                             foreach ($detail->value as $value) {
  764.                                 //print_r($detail->propertyName);
  765.                                 $tmp[$detail->propertyName] = isset($value->number) ? $value->number->value '';
  766.                                 $tmp[$detail->propertyName] .= isset($value->text) ? ' '.$value->text->value '';
  767.                                 $tmp[$detail->propertyName] .= isset($value->URL) ? ' '.$value->URL->value '';
  768.                                 $tmp[$detail->propertyName] = trim($tmp[$detail->propertyName]);
  769.                                 /*
  770.                                 printf(
  771.                                     "%s %s %s ",
  772.                                     isset($value->number) ? $value->number->value : '',
  773.                                     isset($value->text) ? $value->text->value : '',
  774.                                     isset($value->URL) ? $value->URL->value : ''
  775.                                 );
  776.                                 */
  777.                             }
  778.                         }
  779.                         $retour[] = $tmp;
  780.                     }
  781.                 }
  782.             }
  783.             $pageNum += 1;
  784.         } while (isset($response->compatibilityDetails) && $pageNum <= $response->paginationOutput->totalPages);
  785.         return $retour;
  786.     }
  787.     public function getOrders($compteMarketPlace$hours 15$output ''$donnee)
  788.     {
  789.         $authToken $this->getAuthToken($compteMarketPlace);
  790.         //if(is_object($output)) $output->writeln($authToken);
  791.         if (empty($authToken)) {
  792.             return $authToken;
  793.         }
  794.         $request = new Types\GetMyeBaySellingRequestType();
  795.         $date_debut = new \DateTime();
  796.         date_modify($date_debut'- '.$hours.' hours');
  797.         $date_fin = new \DateTime();
  798.         $args = [
  799.             //"OrderStatus"   => "Completed",
  800.             "OrderStatus" => "All",
  801.             //"SortingOrder"  => "Descending",
  802.             //"OrderRole"     => "Seller",
  803.             "ModTimeFrom" => $date_debut,
  804.             "ModTimeTo"   => $date_fin,
  805.             //"siteId" => $this->siteId,
  806.             //"CreateTimeFrom"   => $date_debut,
  807.             //"CreateTimeTo"   => $date_fin,
  808.         ];
  809.         //$jSON = "";
  810.         //$args = array('OrderIDArray'=>array(224358007693));
  811.         $orders = [];
  812.         $getOrders                                      = new Types\GetOrdersRequestType($args);
  813.         $getOrders->RequesterCredentials                = new Types\CustomSecurityHeaderType();
  814.         $getOrders->RequesterCredentials->eBayAuthToken $authToken;
  815.         $getOrders->IncludeFinalValueFee                true;
  816.         $getOrders->Pagination                          = new Types\PaginationType();
  817.         $getOrders->Pagination->EntriesPerPage          10;
  818.         $getOrders->DetailLevel[]                       = 'ReturnAll';
  819.         $getOrders->OrderIDArray            = new Types\OrderIDArrayType();
  820.         $getOrders->OrderIDArray->OrderID[] = '224358007693-2533745807012';//RU
  821.         $getOrders->OrderIDArray->OrderID[] = '124232724894-2390972902002';//FR
  822.         $pageNum                           1;
  823.         $getOrders->Pagination->PageNumber $pageNum;
  824. //        $directory = __DIR__."/../../../../web/ebay-api/ORDERS/EXPORT/".date("Y/m/d");
  825.         $file    $directory."/export_orders_ebay_".$compteMarketPlace->getId()."_".date("dmY").".xml";
  826.         $dirname dirname($file);
  827.         if ( ! is_dir($dirname)) {
  828.             mkdir($dirname0755true);
  829.         }
  830.         $fp fopen($file'w') or die("Erreur d'écriture du fichier");
  831.         fwrite($fp'<?xml version="1.0" encoding="UTF-8"?>');
  832.         fwrite($fp'<Orders>');
  833.         $nbLignes 0;
  834.         do {
  835.             $getOrders->Pagination->PageNumber $pageNum;
  836.             //var_dump($getOrders);
  837.             $response = @$this->getTradingService($compteMarketPlace$output)->getOrders($getOrders);
  838.             foreach ($response->OrderArray->Order as $order) {
  839.                 $orders[] = $order;
  840.                 //$this->traiterCommande($compteMarketPlace, $order, $output);
  841.                 //if(is_object($output) && $pageNum == 1) print_r($order);
  842.                 $nbLignes++;
  843.                 $output->writeln('Enregistrement line '.$nbLignes);
  844.                 fwrite($fp$this->json_to_xml($order));
  845.             }
  846.             //printf($response->OrderArray);break;
  847.             $pageNum += 1;
  848.         } while (isset($response->HasMoreOrders) && $response->HasMoreOrders == true && $pageNum <= 2);
  849.         fwrite($fp'</Orders>');
  850.         fclose($fp);
  851.         $nbLignes 0;
  852.         if (count($orders)) {
  853.             $compteur_boucle 0;
  854.             foreach ($orders as $order) {
  855.                 $nbLignes++;
  856.                 $output->writeln('Traitement line '.$nbLignes);
  857.                 print_r($order);
  858.                 $this->traiterCommande($compteMarketPlace$order$output$donnee);
  859.             }
  860.         }
  861.         $this->em->clear();
  862.         //return $orders;
  863.         //return $response;
  864.     }
  865.     // TODO TEST
  866.     private function json_to_xml($json)
  867.     {
  868.         $normalizers = [new ObjectNormalizer()];
  869.         $encoders    = [new XmlEncoder()];
  870.         $serializer  = new Serializer($normalizers$encoders);
  871.         $obj         json_decode($json);
  872.         $xml         $serializer->serialize($obj'xml');
  873.         if ( ! empty($xml)) {
  874.             $xml str_replace("<stdClass>""<Order>"$xml);
  875.             $xml str_replace("</stdClass>""</Order>"$xml);
  876.             return $xml;
  877.         } else {
  878.             return null;
  879.         }
  880.     }
  881.     private function traiterCommande($compte$order$output$donnee)
  882.     {
  883.         $conn $this->em->getConnection();
  884.         $conn->getConfiguration()->setSQLLogger(null);
  885.         $repo_commande                 $this->em->getRepository(Commande::class);
  886.         $repo_article_commande         $this->em->getRepository(ArticleCommande::class);
  887.         $repo_type_document_commercial $this->em->getRepository(TypeDocumentCommercial::class);
  888.         $repo_article_market_place     $this->em->getRepository(ArticleMarketPlace::class);
  889.         $output->writeln('ORDER ID '.$order->OrderID);
  890.         $SellingManagerSalesRecordNumber trim($order->ShippingDetails->SellingManagerSalesRecordNumber);
  891.         $OrderID     trim($order->OrderID);
  892.         $OrderStatus trim($order->OrderStatus);
  893.         $AdjustmentAmount_value      trim($order->AdjustmentAmount->value);
  894.         $AdjustmentAmount_currencyID trim($order->AdjustmentAmount->currencyID);
  895.         $AmountPaid_value      trim($order->AmountPaid->value);
  896.         $AmountPaid_currencyID trim($order->AmountPaid->currencyID);
  897.         $AmountSaved_value      trim($order->AmountSaved->value);
  898.         $AmountSaved_currencyID trim($order->AmountSaved->currencyID);
  899.         $eBayPaymentStatus                   trim($order->CheckoutStatus->eBayPaymentStatus);
  900.         $LastModifiedTime                    $order->CheckoutStatus->LastModifiedTime;
  901.         $PaymentMethod                       trim($order->CheckoutStatus->PaymentMethod);
  902.         $Status                              trim($order->CheckoutStatus->Status);
  903.         $IntegratedMerchantCreditCardEnabled trim($order->CheckoutStatus->IntegratedMerchantCreditCardEnabled);
  904.         $PaymentInstrument                   trim($order->CheckoutStatus->PaymentInstrument);
  905.         $SalesTaxPercent       trim($order->ShippingDetails->SalesTax->SalesTaxPercent);
  906.         $SalesTaxState         trim($order->ShippingDetails->SalesTax->SalesTaxState);
  907.         $ShippingIncludedInTax trim($order->ShippingDetails->SalesTax->ShippingIncludedInTax);
  908.         //print_r($order->TransactionArray->Transaction);
  909.         /*
  910.         $ShippingService = trim($order->ShippingDetails->ShippingServiceOptions->ShippingService);
  911.         $ShippingServiceCost_value = trim($order->ShippingDetails->ShippingServiceOptions->ShippingServiceCost->value);
  912.         $ShippingServiceCost_currencyID = trim($order->ShippingDetails->ShippingServiceOptions->ShippingServiceCost->currencyID);
  913.         $ShippingServicePriority = trim($order->ShippingDetails->ShippingServiceOptions->ShippingServicePriority);
  914.         $ExpeditedService = trim($order->ShippingDetails->ShippingServiceOptions->ExpeditedService);
  915.         $ShippingTimeMin = trim($order->ShippingDetails->ShippingServiceOptions->ShippingTimeMin);
  916.         $ShippingTimeMax = trim($order->ShippingDetails->ShippingServiceOptions->ShippingTimeMax);
  917.         */
  918.         $CreatingUserRole trim($order->CreatingUserRole);
  919.         $CreatedTime      $order->CreatedTime;
  920.         /*
  921.         $PaymentMethods ="";
  922.         if(isset($order->PaymentMethods)) $PaymentMethods = trim($order->PaymentMethods);
  923.         */
  924.         $SellerEmail trim($order->SellerEmail);
  925.         /*
  926.         $ShippingAddress_Name = trim($order->ShippingAddress->Name);
  927.         $ShippingAddress_Street1 = trim($order->ShippingAddress->Street1);
  928.         $ShippingAddress_Street2 = trim($order->ShippingAddress->Street2);
  929.         $ShippingAddress_CityName = trim($order->ShippingAddress->CityName);
  930.         $ShippingAddress_StateOrProvince = trim($order->ShippingAddress->StateOrProvince);
  931.         $ShippingAddress_Country = trim($order->ShippingAddress->Country);
  932.         $ShippingAddress_CountryName = trim($order->ShippingAddress->CountryName);
  933.         $ShippingAddress_Phone = trim($order->ShippingAddress->Phone);
  934.         $ShippingAddress_PostalCode = trim($order->ShippingAddress->PostalCode);
  935.         $ShippingAddress_AddressID = trim($order->ShippingAddress->AddressID);
  936.         $ShippingAddress_AddressOwner = trim($order->ShippingAddress->AddressOwner);
  937.         $ShippingAddress_ExternalAddressID = trim($order->ShippingAddress->ExternalAddressID);
  938.         */
  939.         $ShippingServiceSelected        trim($order->ShippingServiceSelected->ShippingService);
  940.         $ShippingServiceCost_value      trim($order->ShippingServiceSelected->ShippingServiceCost->value);
  941.         $ShippingServiceCost_currencyID trim($order->ShippingServiceSelected->ShippingServiceCost->currencyID);
  942.         $Subtotal_value      trim($order->Subtotal->value);
  943.         $Subtotal_currencyID trim($order->Subtotal->currencyID);
  944.         $Total_value      trim($order->Total->value);
  945.         $Total_currencyID trim($order->Total->currencyID);
  946.         //$Buyer_Email = trim($order->Total->currencyID);
  947.         $BuyerCheckoutMessage trim($order->BuyerCheckoutMessage);
  948.         //$output->writeln('ETAPE 2 '.$order->OrderID);
  949.         $Buyer_Email         '';
  950.         $Buyer_UserFirstName '';
  951.         $Buyer_UserLastName  '';
  952.         if (isset($order->TransactionArray->Transaction) && count($order->TransactionArray->Transaction)) {
  953.             foreach ($order->TransactionArray->Transaction as $transaction) {
  954.                 $Buyer_Email         $transaction->Buyer->Email;
  955.                 $Buyer_UserFirstName $transaction->Buyer->UserFirstName;
  956.                 $Buyer_UserLastName  $transaction->Buyer->UserLastName;
  957.             }
  958.         }
  959.         //$BuyerUserID = trim($order->BuyerUserID);
  960.         $PaidTime                            $order->PaidTime;
  961.         $ShippedTime                         $order->ShippedTime;
  962.         $IntegratedMerchantCreditCardEnabled trim($order->IntegratedMerchantCreditCardEnabled);
  963.         $PaymentHoldStatus                   trim($order->PaymentHoldStatus);
  964.         $ExtendedOrderID                     trim($order->ExtendedOrderID);
  965.         $tab_client = [
  966.             'idImport'          => 'cpt'.$compte->getId().'_'.trim($order->BuyerUserID),
  967.             'email'             => trim($order->BuyerUserID),
  968.             'nom'               => $Buyer_UserLastName,
  969.             'prenom'            => $Buyer_UserFirstName,
  970.             'pays'              => trim($order->ShippingAddress->CountryName),
  971.             'pays_code_iso'     => trim($order->ShippingAddress->Country),
  972.             'compteMarketPlace' => $compte,
  973.         ];
  974.         $client     $this->clientService->getClient($tab_client);
  975.         //getClientMarketPlace
  976.         //pays
  977.         //compteMarketPlace
  978.         //si non trouve verifier si pays ue ou reste du monde et chercher à nouveau
  979.         $tab_shipping_address = [
  980.             'livraisonDefaut' => true,
  981.             'societe'         => trim($order->ShippingAddress->Name),
  982.             'rue'             => trim($order->ShippingAddress->Street1),
  983.             'complement'      => trim($order->ShippingAddress->Street2),
  984.             'ville'           => trim($order->ShippingAddress->CityName),
  985.             'pays'            => trim($order->ShippingAddress->CountryName),
  986.             'pays_code_iso'   => trim($order->ShippingAddress->Country),
  987.             'idImport'        => 'cpt'.$compte->getId().'_'.trim($order->ShippingAddress->AddressID),
  988.             'telephone'       => trim($order->ShippingAddress->Phone),
  989.             'codePostal'      => trim($order->ShippingAddress->PostalCode),
  990.         ];
  991.         if (is_object($client)) {
  992.             $tab_shipping_address['client'] = $client;
  993.         }
  994.         //$shipping_address = $service_adresse->getAdresse($tab_shipping_address, $output);
  995.         //lien commande / marketplace
  996.         $query $repo_commande->createQueryBuilder('p')
  997.                                ->select(
  998.                                    'p.id,p.reference,sc.id as statut_commande_id, sc.libelle as statut_commande_libelle, scm.libelle as statut_commande_market_place_libelle,scm.reference as statut_commande_market_place_reference'
  999.                                )//p.commentaireExpedition as commentaire_expedition,p.sifam
  1000.                                ->where(
  1001.                 '(p.archive is null or p.archive = :archive) and p.compteMarketPlace = :compteMarketPlace AND p.idImport = :idImport AND tp.id = :typeDocumentCommercial'
  1002.             )
  1003.                                ->setParameters(['archive' => '0''compteMarketPlace' => $compte->getId(), "idImport" => $OrderID'typeDocumentCommercial' => TypeDocumentCommercial::COMMANDE])
  1004.                                ->setMaxResults(1)
  1005.                                //->join('p.typeDocumentCommercial', 'tp')
  1006.                                ->join('p.statutCommande''sc')
  1007.                                ->leftJoin('p.statutCommandeMarketPlace''scm')
  1008.                                ->orderBy('p.id''ASC');
  1009.         $commande_bdd   $query->getQuery()->getOneOrNullResult();
  1010.         $tableau_donnee = [];
  1011.         //$dateCommande = new \Datetime($CreatedTime);
  1012.         //$tableau_donnee["reference"]=$purchaseid;
  1013.         $tableau_donnee["reference_market_place"] = $SellingManagerSalesRecordNumber;
  1014.         if (is_object($client)) {
  1015.             $tableau_donnee["client_id"] = $client->getId();
  1016.         } else {
  1017.             $tableau_donnee["client_id"] = null;
  1018.         }
  1019.         $tableau_donnee["id_import"]              = $OrderID;
  1020.         $tableau_donnee["compte_market_place_id"] = $compte->getId();
  1021.         $tableau_donnee["dateMaj"]                = (new \Datetime)->format("Y-m-d H:i:s");
  1022.         //$tableau_donnee["date"] = $dateCommande->format('Y-m-d H:i:s');
  1023.         $tableau_donnee["date"]                        = $CreatedTime->format('Y-m-d H:i:s');
  1024.         $tableau_donnee["type_document_commercial_id"] = TypeDocumentCommercial::COMMANDE;
  1025.         $tableau_donnee["archive"]                     = 0;
  1026.         $tableau_donnee["avecTaxe"]                    = 1;
  1027.         $tableau_donnee["statut_paiement_id"]          = 1;
  1028.         $tableau_donnee["etat_commande_id"]            = 1;
  1029.         $tableau_donnee["bascule_comptabilite"]        = 0;
  1030.         $tableau_donnee["visible"]                     = "1";
  1031.         $tableau_donnee["modifiable"]                  = "0";
  1032.         $tableau_donnee["temps_passe"]                 = "0";
  1033.         $tableau_donnee["temps_facture"]               = "0";
  1034.         $tableau_donnee["attente_facturation"]         = "0";
  1035.         $tableau_donnee["origine_saisie"]              = "commande";
  1036.         $tableau_donnee["statut_commande_id"]          = "1";
  1037.         $tableau_donnee["total_frais_port"]     = $ShippingServiceCost_value;
  1038.         $tableau_donnee["total_frais_port_ttc"] = $ShippingServiceCost_value;
  1039.         $tableau_donnee["total_tva_frais_port"] = 0;
  1040.         //Subtotal_value
  1041.         $tableau_donnee["total_ttc"] = $Total_value;
  1042.         //$tableau_donnee["total"] = $Total_value*(100/(100+floatval($SalesTaxPercent)));
  1043.         $tableau_donnee["total"] = $Subtotal_value;
  1044.         //$Total_currencyID = trim($order->Total->currencyID);
  1045.         $tableau_donnee["devise_id"] = $this->deviseService->getDevise($Total_currencyID$output)->getId();
  1046.         /*
  1047.                                 $tableau_donnee['destinataire_livraison_texte']=$ShippingAddress_Name;
  1048.                                 $tableau_donnee['destinataire_facturation_texte']=$ShippingAddress_Name;
  1049.                                 $tableau_donnee['pays_livraison_texte']=$this->trouverPays($tab_adresse['pays']);;
  1050.                                 $tableau_donnee['ville_livraison_texte']=$tab_adresse["ville"];
  1051.                                 $tableau_donnee['code_postal_livraison_texte']=$tab_adresse["codePostal"];
  1052.                                 $tableau_donnee['pays_facturation_texte']=$this->trouverPays($tab_adresse['pays']);;
  1053.                                 $tableau_donnee['ville_facturation_texte']=$tab_adresse["ville"];
  1054.                                 $tableau_donnee['code_postal_facturation_texte']=$tab_adresse["codePostal"];
  1055.                                 */
  1056.         $tableau_donnee['commentaire'] = $BuyerCheckoutMessage;
  1057.         //livraison
  1058.         /*
  1059.         if(is_object($shipping_address)) $tableau_donnee['adresse_livraison_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_livraison_id'] = NULL;
  1060.         if(is_object($shipping_address) && is_object($shipping_address->getPays())) $tableau_donnee['pays_livraison_id'] = $shipping_address->getPays()->getId(); else $tableau_donnee['pays_livraison_id'] = NULL;
  1061.         if(is_object($shipping_address) && is_object($shipping_address->getVille())) $tableau_donnee['ville_livraison_id'] = $shipping_address->getVille()->getId(); else $tableau_donnee['ville_livraison_id'] = NULL;
  1062.         if(is_object($shipping_address) && is_object($shipping_address->getCodePostal())) $tableau_donnee['code_postal_livraison_id'] = $shipping_address->getCodePostal()->getId(); else $tableau_donnee['code_postal_livraison_id'] = NULL;
  1063.         */
  1064.         $tableau_donnee['adresse_livraison_id']      = null;
  1065.         $tableau_donnee['ville_livraison_txt']       = trim($order->ShippingAddress->CityName);
  1066.         $tableau_donnee['pays_livraison_txt']        = trim($order->ShippingAddress->CountryName);
  1067.         $tableau_donnee['code_postal_livraison_txt'] = trim($order->ShippingAddress->PostalCode);
  1068.         $tableau_donnee['libelle_livraison']         = trim($order->ShippingAddress->Name);
  1069.         //$tableau_donnee['numero_livraison'] = '';
  1070.         $tableau_donnee['rue_livraison']               = trim($order->ShippingAddress->Street1);
  1071.         $tableau_donnee['complement_livraison']        = trim($order->ShippingAddress->Street2);
  1072.         $tableau_donnee['code_iso_livraison']          = trim($order->ShippingAddress->Country);
  1073.         $tableau_donnee['state_or_province_livraison'] = trim($order->ShippingAddress->StateOrProvince);
  1074.         //$tableau_donnee['complement_livraison_2'] = ;
  1075.         //facturation
  1076.         /*
  1077.         if(is_object($shipping_address)) $tableau_donnee['adresse_facturation_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_facturation_id'] = NULL;
  1078.         if(is_object($shipping_address) && is_object($shipping_address->getPays())) $tableau_donnee['pays_facturation_id'] = $shipping_address->getPays()->getId(); else $tableau_donnee['pays_facturation_id'] = NULL;
  1079.         if(is_object($shipping_address) && is_object($shipping_address->getVille())) $tableau_donnee['ville_facturation_id'] = $shipping_address->getVille()->getId(); else $tableau_donnee['ville_facturation_id'] = NULL;
  1080.         if(is_object($shipping_address) && is_object($shipping_address->getCodePostal())) $tableau_donnee['code_postal_facturation_id'] = $shipping_address->getCodePostal()->getId(); else $tableau_donnee['code_postal_facturation_id'] = NULL;
  1081.         */
  1082.         $tableau_donnee['adresse_facturation_id']      = null;
  1083.         $tableau_donnee['ville_facturation_txt']       = trim($order->ShippingAddress->CityName);
  1084.         $tableau_donnee['pays_facturation_txt']        = trim($order->ShippingAddress->CountryName);
  1085.         $tableau_donnee['code_postal_facturation_txt'] = trim($order->ShippingAddress->PostalCode);
  1086.         $tableau_donnee['libelle_facturation']         = trim($order->ShippingAddress->Name);
  1087.         //$tableau_donnee['numero_facturation'] = '';
  1088.         $tableau_donnee['rue_facturation']               = trim($order->ShippingAddress->Street1);
  1089.         $tableau_donnee['complement_facturation']        = trim($order->ShippingAddress->Street2);
  1090.         $tableau_donnee['code_iso_facturation']          = trim($order->ShippingAddress->Country);
  1091.         $tableau_donnee['state_or_province_facturation'] = trim($order->ShippingAddress->StateOrProvince);
  1092.         //$tableau_donnee['complement_facturation_2'] = ;
  1093.         //ShippingCarrierUsed
  1094.         //transporteur_id
  1095.         //ShipmentTrackingNumber
  1096.         //numero_suivi
  1097.         /*
  1098.         [CheckoutStatus] => DTS\eBaySDK\Trading\Types\CheckoutStatusType Object
  1099.                 (
  1100.                     [values:DTS\eBaySDK\Types\BaseType:private] => Array
  1101.                         (
  1102.                             [eBayPaymentStatus] => NoPaymentFailure
  1103.                             [LastModifiedTime] => DateTime Object
  1104.                                 (
  1105.                                     [date] => 2021-03-19 13:47:50.000000
  1106.                                     [timezone_type] => 2
  1107.                                     [timezone] => Z
  1108.                                 )
  1109.                             [PaymentMethod] => PayPal
  1110.                             [Status] => Complete
  1111.                             [IntegratedMerchantCreditCardEnabled] =>
  1112.                             [PaymentInstrument] => CreditCard
  1113.                         )
  1114.                         */
  1115.         //AmountPaid
  1116.         /*
  1117.         $tab_statut_commande = array();
  1118.         $tab_statut_commande["reference"]=$OrderStatus;
  1119.         */
  1120.         //statut de commande
  1121.         //mode de reglement marketplace
  1122.         if ( ! empty($PaymentMethod)) {
  1123.             $mode_reglement_market_place $this->marketPlaceService->getModeReglementMarketPlace($PaymentMethod$compte->getMarketPlace());
  1124.             if (is_object($mode_reglement_market_place)) {
  1125.                 $tableau_donnee['mode_reglement_market_place_id'] = $mode_reglement_market_place->getId();
  1126.                 if (is_object($mode_reglement_market_place->getModeReglement())) {
  1127.                     $tableau_donnee['mode_reglement_id'] = $mode_reglement_market_place->getModeReglement()->getId();
  1128.                 }
  1129.             }
  1130.         }
  1131.         //mode d'expedition
  1132.         if ( ! empty($ShippingServiceSelected)) {
  1133.             $tableau_donnee['mode_expedition_id'] = $this->modeExpeditionService->getModeExpedition($ShippingServiceSelected$ShippingServiceSelected$compte->getMarketPlace());
  1134.         }
  1135.         if ( ! empty($tableau_donnee['mode_expedition_id'])) {
  1136.             $mode_expedition_obj $repo_mode_expedition->find($tableau_donnee['mode_expedition_id']);
  1137.             if (is_object($mode_expedition_obj) && is_object($mode_expedition_obj->getTransporteur())) {
  1138.                 $tableau_donnee['transporteur_id'] = $mode_expedition_obj->getTransporteur()->getId();
  1139.             }
  1140.         }
  1141.         //statut commande marketplace
  1142.         if ( ! empty($OrderStatus)) {
  1143.             $statut_commande_calcule                           $this->commandeService->calculerStatutCommandeMarketPlace($compte$OrderStatus$commande_bdd);
  1144.             $tableau_donnee['statut_commande_market_place_id'] = $statut_commande_calcule["id"];
  1145.             $tableau_donnee['statut_commande_id']              = $statut_commande_calcule["action_statut_commande_id"];
  1146.             if ( ! empty($statut_commande_calcule['statut_paiement_id'])) {
  1147.                 $tableau_donnee['statut_paiement_id'] = $statut_commande_calcule['statut_paiement_id'];
  1148.             }
  1149.         }
  1150.         /*
  1151.         if(!empty($order['order_state_reason_code'])){
  1152.             $statut_paiement_calcule = $service_commande->calculerStatutPaiementMarketPlace($order['order_state_reason_code']);
  1153.             $tableau_donnee['statut_paiement_id'] = $statut_paiement_calcule["statut_paiement_id"];
  1154.             if(!empty($statut_paiement_calcule["statut_commande_id"])) $tableau_donnee['statut_commande_id'] = $statut_paiement_calcule["statut_commande_id"];
  1155.         }
  1156.         */
  1157.         /*
  1158.                                 $mode_expedition_bdd = $this->creerModeExpedition($output,$container,$compte,$tab_expedition);
  1159.                                 $tableau_donnee['mode_expedition_id']=$mode_expedition_bdd["id"];
  1160.                                 $tab_reglement = array();
  1161.                                 $tab_reglement["reference"]=$PaymentMethods;
  1162.                                 $mode_reglement_bdd = $this->creerModeReglement($output,$container,$compte,$tab_reglement);
  1163.                                 $tableau_donnee['modereglement_id']=$mode_reglement_bdd["id"];
  1164.                                 if(is_object($ville_obj)) {
  1165.                                     $tableau_donnee['ville_facturation_id']=$ville_obj->getId();
  1166.                                     $tableau_donnee['code_postal_facturation_id']=$ville_obj->getId();
  1167.                                     if(is_object($ville_obj->getParentId()) && is_object($ville_obj->getParentId()->getParentId()) && is_object($ville_obj->getParentId()->getParentId()->getParentId())) {
  1168.                                         $tableau_donnee['pays_facturation_id'] = $ville_obj->getParentId()->getParentId()->getParentId()->getId();
  1169.                                     }
  1170.                                 }
  1171.         */
  1172.         $tableau_donnee_commande $tableau_donnee;
  1173.         $nouvelle_commande_ebay true;
  1174.         //$output->writeln('ETAPE 8 '.$order->OrderID);
  1175.         if ($commande_bdd['id'] == "") {
  1176.             $commande_obj  = new Commande();
  1177.             $type_commande TypeDocumentCommercial::COMMANDE;
  1178.             $commande_obj->setTypeDocumentCommercial($type_commande);
  1179.             $tableau_donnee["reference"] = $this->numerotationDocumentService->generer($commande_obj);
  1180.             /*
  1181.             if (array_key_exists('code_postal_livraison_texte', $tableau_donnee)) {
  1182.                 if( substr($tableau_donnee['code_postal_livraison_texte'],0,2) == "20")
  1183.                 {
  1184.                     $tableau_donnee['adresse_a_changer']="1";
  1185.                     $tableau_donnee['commentaireExpedition']="ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE";
  1186.                 }
  1187.             }
  1188.             */
  1189.             if ($donnee == "Oui") {
  1190.                 $conn->insert('commerciale__commande'$tableau_donnee);
  1191.             }
  1192.             $commande_bdd['id'] = $conn->lastInsertId();
  1193.             $output->writeln('<info>TABLE COMMANDE Action : INSERT : '.$tableau_donnee["reference_market_place"].'</info>');
  1194.         } else {
  1195.             $nouvelle_commande_ebay      false;
  1196.             $tableau_donnee["reference"] = $commande_bdd['reference'];
  1197.             if ($donnee == "Oui") {
  1198.                 $conn->update('commerciale__commande'$tableau_donnee, ['id' => $commande_bdd['id']]);
  1199.             }
  1200.             $output->writeln('<info>TABLE COMMANDE Action : UPDATE : '.$tableau_donnee["reference_market_place"].' / ID : '.$commande_bdd['id'].'</info>');
  1201.         }
  1202.         //$output->writeln('ETAPE 9 '.$order->OrderID);
  1203.         //$handle_pdf = fopen($domaine.$url_pdf, 'r');
  1204.         if (isset($order->TransactionArray->Transaction)) {
  1205.             foreach ($order->TransactionArray->Transaction as $item) {
  1206.                 $Item_ShippingDetails        trim($item->ShippingDetails->SellingManagerSalesRecordNumber);
  1207.                 $CreatedDate                 $item->CreatedDate;
  1208.                 $ItemID                      trim($item->Item->ItemID);
  1209.                 $Site                        trim($item->Item->Site);
  1210.                 $Title                       trim($item->Item->Title);
  1211.                 $ConditionID                 trim($item->Item->ConditionID);
  1212.                 $ConditionDisplayName        trim($item->Item->ConditionDisplayName);
  1213.                 $QuantityPurchased           floatval(trim($item->QuantityPurchased));
  1214.                 $PaymentHoldStatus           trim($item->Status->PaymentHoldStatus);
  1215.                 $InquiryStatus               trim($item->Status->InquiryStatus);
  1216.                 $ReturnStatus                trim($item->Status->ReturnStatus);
  1217.                 $TransactionID               trim($item->TransactionID);
  1218.                 $TransactionPrice_value      floatval(trim($item->TransactionPrice->value));
  1219.                 $TransactionPrice_currencyID trim($item->TransactionPrice->currencyID);
  1220.                 //$ProductName = trim($item->SellingManagerProductDetails->ProductName);
  1221.                 //$EstimatedDeliveryTimeMin = $item->ShippingServiceSelected->ShippingPackageInfo->EstimatedDeliveryTimeMin;
  1222.                 //$EstimatedDeliveryTimeMax = $item->ShippingServiceSelected->ShippingPackageInfo->EstimatedDeliveryTimeMax;
  1223.                 $FinalValueFee_value       trim($item->FinalValueFee->value);
  1224.                 $FinalValueFee_currencyID  trim($item->FinalValueFee->currencyID);
  1225.                 $TransactionSiteID         trim($item->TransactionSiteID);
  1226.                 $Platform                  trim($item->Platform);
  1227.                 $TotalTaxAmount_value      trim($item->Taxes->TotalTaxAmount->value);
  1228.                 $TotalTaxAmount_currencyID trim($item->Taxes->TotalTaxAmount->currencyID);
  1229.                 //$Imposition = trim($item->Taxes->TaxDetails->Imposition);
  1230.                 //$TaxDescription = trim($item->Taxes->TaxDetails->TaxDescription);
  1231.                 //$TaxAmount_value = trim($item->Taxes->TaxDetails->TaxAmount->value);
  1232.                 //$TaxAmount_currencyID = trim($item->Taxes->TaxDetails->TaxAmount->currencyID);
  1233.                 //$TaxOnSubtotalAmount_value = trim($item->Taxes->TaxDetails->TaxOnSubtotalAmount->value);
  1234.                 //$TaxOnSubtotalAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnSubtotalAmount->currencyID);
  1235.                 /*
  1236.                                                 $TaxOnShippingAmount_value = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->value);
  1237.                                                 $TaxOnShippingAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->currencyID);
  1238.                                                 $TaxOnShippingAmount_value = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->value);
  1239.                                                 $TaxOnShippingAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->currencyID);
  1240.                                                 $TaxOnHandlingAmount_value = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->value);
  1241.                                                 $TaxOnHandlingAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->currencyID);
  1242.                                                 $ActualShippingCost_value = trim($item->ActualShippingCost->value);
  1243.                                                 $ActualShippingCost_currencyID = trim($item->ActualShippingCost->currencyID);
  1244.                                                 $ActualHandlingCost_value = trim($item->ActualHandlingCost->value);
  1245.                                                 $ActualHandlingCost_currencyID = trim($item->ActualHandlingCost->currencyID);
  1246.                 */
  1247.                 $OrderLineItemID     trim($item->OrderLineItemID);
  1248.                 $ExtendedOrderID     trim($item->ExtendedOrderID);
  1249.                 $eBayPlusTransaction trim($item->eBayPlusTransaction);
  1250.                 $GuaranteedShipping  trim($item->GuaranteedShipping);
  1251.                 //$TransactionPrice_value = trim($item->TransactionPrice->value);
  1252.                 /*if(isset(trim($item->Variation->value)) {
  1253.                 }
  1254.                 */
  1255.                 //$output->writeln('ETAPE 10 '.$order->OrderID);
  1256.                 /* RECHERCHE ANNONCE */
  1257.                 $select 'p.id,a.id as article_id,r.id as regle_taxe_id,r.tauxDefaut as regle_taxe_taux_defaut,fd.id as fournisseur_defaut_id';
  1258.                 $query  $repo_article_market_place->createQueryBuilder('p')
  1259.                                                     ->select($select)
  1260.                                                     ->leftJoin('p.article''a')
  1261.                                                     ->leftJoin('a.regleTaxe''r')
  1262.                                                     ->leftJoin('a.fournisseurDefaut''fd')
  1263.                                                     ->where("p.idImport = :idImport AND p.compteMarketPlace = :compte")
  1264.                                                     ->setParameters(["idImport" => $ItemID"compte" => $compte])
  1265.                                                     ->setMaxResults(1)
  1266.                                                     ->orderBy('p.id''ASC');
  1267.                 $article_market_place_bdd $query->getQuery()->getOneOrNullResult();
  1268.                 if ($article_market_place_bdd['id'] == "") {
  1269.                     //recuperer l'annonce sur ebay
  1270.                     /*
  1271.                     $donneesTmp = array();
  1272.                     $donneesTmp['update'] = 1;
  1273.                     $donneesTmp['idImport'] = $idImport;
  1274.                     $donneesTmp['reference'] = $SKU;
  1275.                     $donneesTmp['libelle'] = $Title;
  1276.                     $donneesTmp['date'] = new \Datetime();
  1277.                     $donneesTmp['date_maj'] = new \Datetime();
  1278.                     $donneesTmp['compteMarketPlace'] = $compte;
  1279.                     $donneesTmp['prix_base'] = $prix;
  1280.                     $donneesTmp['prix_vente'] = $prix;
  1281.                     $donneesTmp['unspsc'] = '';
  1282.                     $donneesTmp['ean'] = $ean;
  1283.                     $donneesTmp['stock'] = $Quantity;
  1284.                     $donneesTmp['description'] = '';
  1285.                     $donneesTmp['advertID_PriceMinister'] = NULL;
  1286.                     $donneesTmp['productID_PriceMinister'] = NULL;
  1287.                     $donneesTmp['active'] = 1;
  1288.                     //$donneesTmp['seller_product_id'] = $seller_product_id;
  1289.                     $donneesTmp['ecotaxe'] = 0;
  1290.                     */
  1291.                     $article_market_place $this->articleMarketPlaceService->getArticleMarketPlace(["idImport" => $ItemID"compteMarketPlace" => $compte], $output);
  1292.                     if (is_object($article_market_place)) {
  1293.                         $query $repo_article_market_place->createQueryBuilder('p')
  1294.                                                            ->select($select)
  1295.                                                            ->leftJoin('p.article''a')
  1296.                                                            ->leftJoin('a.regleTaxe''r')
  1297.                                                            ->leftJoin('a.fournisseurDefaut''fd')
  1298.                                                            ->where("p.id = :id")
  1299.                                                            ->setParameters(["id" => $article_market_place->getId()])
  1300.                                                            ->setMaxResults(1)
  1301.                                                            ->orderBy('p.id''ASC');
  1302.                         $article_market_place_bdd $query->getQuery()->getOneOrNullResult();
  1303.                     }
  1304.                 }
  1305.                 if ($article_market_place_bdd['id'] != "") {
  1306.                     /*
  1307.                     if($article_market_place_bdd['fournisseur_defaut_id'] == 2) {
  1308.                         $commande_vega = true;
  1309.                     }
  1310.                     if($article_market_place_bdd['fournisseur_defaut_id'] == 95) {
  1311.                         $commande_sifam = true;
  1312.                     }
  1313.                     */
  1314.                     //$output->writeln('ARTICLE TROUVE ');
  1315.                     //$output->writeln('PRIX '.$item_price.' REGLE TAXE : '.$article_market_place_bdd["regle_taxe_taux_defaut"].'% ARTICLE TROUVE AMP:'.$article_market_place_bdd["id"].' AID : '.$article_market_place_bdd["article_id"]);
  1316.                     $parametersArticleCommandeEbay = [];
  1317.                     $where                         "p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace";
  1318.                     //$where = "p.commande = :commande AND p.article = :article";
  1319.                     $parametersArticleCommandeEbay["commande"]           = $commande_bdd['id'];
  1320.                     $parametersArticleCommandeEbay["article"]            = $article_market_place_bdd["article_id"];
  1321.                     $parametersArticleCommandeEbay["articleMarketPlace"] = $article_market_place_bdd["id"];
  1322.                     //test;
  1323.                     /*
  1324.                                                         $query = $repo_article_commande->createQueryBuilder('p')
  1325.                                                                 ->select('p.id')
  1326.                                                                 ->where('p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace')
  1327.                                                                 ->setParameters(array('commande' => $commande_bdd['id'],"article"=>$article_market_place_bdd["article_id"]))
  1328.                                                                 ->setMaxResults(1)
  1329.                                                                 ->orderBy('p.id', 'ASC');
  1330.                     */
  1331.                     $compteur_variation 0;
  1332.                     $tabVariationEbay   = [];
  1333.                     if (isset($item->Variation)) {
  1334.                         if (isset($item->Variation->VariationSpecifics)) {
  1335.                             if (isset($item->Variation->VariationSpecifics)) {
  1336.                                 if (isset($item->Variation->VariationSpecifics->NameValueList)) {
  1337.                                     if (isset($item->Variation->VariationSpecifics->NameValueList)) {
  1338.                                         foreach ($item->Variation->VariationSpecifics->NameValueList as $variationArticle) {
  1339.                                             $compteur_variation++;
  1340.                                             if ($compteur_variation 4) {
  1341.                                                 $parametersArticleCommandeEbay["declinaison".$compteur_variation] = $variationArticle->Name.":".$variationArticle->Value;
  1342.                                                 $where                                                            .= " AND p.declinaison".$compteur_variation." = :declinaison".$compteur_variation;
  1343.                                                 $tabVariationEbay[] = $variationArticle->Name.":".$variationArticle->Value;
  1344.                                             }
  1345.                                         }
  1346.                                     }
  1347.                                 }
  1348.                             }
  1349.                         }
  1350.                     }
  1351.                     //print_r($parametersArticleCommandeEbay);
  1352.                     //exit;
  1353.                     //$output->writeln('ETAPE 11 '.$order->OrderID);
  1354.                     $query $repo_article_commande->createQueryBuilder('p')
  1355.                                                    ->select('p.id')
  1356.                                                    ->where($where)
  1357.                                                    ->setParameters($parametersArticleCommandeEbay)
  1358.                                                    ->setMaxResults(1)
  1359.                                                    ->orderBy('p.id''ASC');
  1360.                     $article_commande_bdd $query->getQuery()->getOneOrNullResult();
  1361.                     //print_r($article_commande_bdd);
  1362.                     //print_r($parametersArticleCommandeEbay);
  1363.                     //$prix_ht = $item_price*($item_price/($item_price+$article_market_place_bdd["regle_taxe_taux_defaut"]));
  1364.                     /*
  1365.                     $prix_ttc = round($TransactionPrice_value);
  1366.                     $prix_ht = round($TransactionPrice_value,2);
  1367.                     $item_price = round($TransactionPrice_value,2);
  1368.                     $prix_ht = $prix_ht*(100/(100+$article_market_place_bdd["regle_taxe_taux_defaut"]));
  1369.                     $prix_ht = round($prix_ht, 2);
  1370.                     $tva = (($TransactionPrice_value/$QuantityPurchased)-$prix_ht)*$QuantityPurchased;
  1371.                     */
  1372.                     $prix_ttc $TransactionPrice_value;
  1373.                     //$prix_ht = $TransactionPrice_value*(100/(100+floatval($SalesTaxPercent)));
  1374.                     $prix_ht        $TransactionPrice_value;
  1375.                     $total_with_tax $TransactionPrice_value $QuantityPurchased;
  1376.                     $total_ht       $total_with_tax * (100 / (100 floatval($SalesTaxPercent)));
  1377.                     //TaxAmount_value
  1378.                     $total_ht       $prix_ht $QuantityPurchased;
  1379.                     $prix_ttc       $TransactionPrice_value $TotalTaxAmount_value;
  1380.                     $total_with_tax $prix_ttc $QuantityPurchased;
  1381.                     $total_with_tax round($total_with_tax2);
  1382.                     $total_ht       round($total_ht2);
  1383.                     $tva            $total_with_tax $total_ht;
  1384.                     $tauxTva        $SalesTaxPercent;
  1385.                     if ($tauxTva == && $total_with_tax != 0) {
  1386.                         $tauxTva $tva $total_with_tax 100;
  1387.                         $tauxTva round($tauxTva2);
  1388.                     }
  1389.                     //recuperer la taxe
  1390.                     $taxeId $article_market_place_bdd["regle_taxe_taux_defaut"];
  1391.                     $taxe   $this->taxeService->getTaxe(floatval($SalesTaxPercent));
  1392.                     if (is_object($taxe)) {
  1393.                         $taxeId $taxe->getId();
  1394.                     }
  1395.                     //recuperer la taxe par currencyID TotalTaxAmount_currencyID
  1396.                     //exit;
  1397.                     $tableau_donnee = [];
  1398.                     for ($v 0$v count($tabVariationEbay); $v++) {
  1399.                         $tableau_donnee["declinaison_".($v 1)] = $tabVariationEbay[$v];
  1400.                     }
  1401.                     //$output->writeln('ETAPE 12 '.$order->OrderID);
  1402.                     $tableau_donnee["libelle"]                 = $Title;
  1403.                     $tableau_donnee["article_id"]              = $article_market_place_bdd["article_id"];
  1404.                     $tableau_donnee["article_market_place_id"] = $article_market_place_bdd["id"];
  1405.                     $tableau_donnee["commande_id"]             = $commande_bdd['id'];
  1406.                     $tableau_donnee["date_maj"]                = (new \Datetime)->format("Y-m-d H:i:s");
  1407.                     $tableau_donnee["position"]                = "0";
  1408.                     $tableau_donnee["reference"]               = $ItemID;
  1409.                     $tableau_donnee["quantite"]                = $QuantityPurchased;
  1410.                     $tableau_donnee["profondeur"]            = "0";
  1411.                     $tableau_donnee["hauteur"]               = "0";
  1412.                     $tableau_donnee["poids"]                 = "0";
  1413.                     $tableau_donnee["remise"]                = "0";
  1414.                     $tableau_donnee["remise_supplementaire"] = "0";
  1415.                     $tableau_donnee["prix_base"]             = $prix_ht;
  1416.                     $tableau_donnee["total_ht"]              = $total_ht;
  1417.                     $tableau_donnee["total_with_tax"]        = $total_with_tax;
  1418.                     $tableau_donnee["tva_vente"]             = $tva;
  1419.                     $tableau_donnee["tva"]                   = $tauxTva;
  1420.                     $tableau_donnee["taxe_id"]               = $taxeId;
  1421.                     /*
  1422.                     $total_frais_port_ttc = $ShippingServiceCost_value;
  1423.                     $tableau_donnee["total_frais_port"]=$total_frais_port_ttc;
  1424.                     $tableau_donnee["total_frais_port_ttc"]=$total_frais_port_ttc;
  1425.                     $tableau_donnee["total_tva_frais_port"]=0;
  1426.                     */
  1427.                     //print_r($tableau_donnee);
  1428.                     if ($article_commande_bdd['id'] == "") {
  1429.                         $tableau_donnee['date'] = (new \Datetime)->format("Y-m-d H:i:s");
  1430.                         if ($donnee == "Oui") {
  1431.                             $conn->insert('commerciale__article_commande'$tableau_donnee);
  1432.                         }
  1433.                         $article_commande_bdd['id'] = $conn->lastInsertId();
  1434.                         //$output->writeln('<info>TABLE ARTICLE COMMANDE Action : INSERT : '.$commande_bdd['id'].'</info>');
  1435.                     } else {
  1436.                         $param_update_ac_ebay                            = [];
  1437.                         $param_update_ac_ebay["article_id"]              = $article_market_place_bdd["article_id"];
  1438.                         $param_update_ac_ebay["commande_id"]             = $commande_bdd["id"];
  1439.                         $param_update_ac_ebay["article_market_place_id"] = $article_market_place_bdd["id"];
  1440.                         for ($v 0$v count($tabVariationEbay); $v++) {
  1441.                             $param_update_ac_ebay["declinaison_".($v 1)] = $tabVariationEbay[$v];
  1442.                         }
  1443.                         if ($donnee == "Oui") {
  1444.                             $conn->update('commerciale__article_commande'$tableau_donnee$param_update_ac_ebay);
  1445.                         }
  1446.                         //if($donnee == "Oui") $conn->update('commerciale__article_commande', $tableau_donnee, array('article_id' => $article_market_place_bdd["article_id"],'commande_id'=>$commande_bdd['id']));
  1447.                         //$output->writeln('<info>TABLE ARTICLE COMMANDE Action : UPDATE : '.$commande_bdd['id'].'</info>');
  1448.                     }
  1449.                     //$output->writeln('ETAPE 13 '.$order->OrderID);
  1450.                 } else {
  1451.                     $tab_introuvable[] = "MarketPlace ".$compte->getMarketPlace()->getLibelle()." : ".$compte->getLibelle(
  1452.                         )." Commande : ".$SellingManagerSalesRecordNumber." Produit : ".$ItemID;
  1453.                     $output->writeln('<error>ARTICLE INTROUVABLE '.$ItemID.'</error>');
  1454.                 }
  1455.                 //$this->calculerTotalCommande($commande_bdd['id']);
  1456.                 //if($nouvelle_commande_ebay) $this->calculerTotalCommande($output,$container,$commande_bdd['id'],$tableau_donnee_commande);
  1457.             }
  1458.         }
  1459.         //historique
  1460.         //priorisation?
  1461.         //pdf?
  1462.     }
  1463.     private function traiterCommande2($compte$order$output$donnee)
  1464.     {
  1465.         $conn $this->em->getConnection();
  1466.         $conn->getConfiguration()->setSQLLogger(null);
  1467.         $repo_commande                 $this->em->getRepository(Commande::class);
  1468.         $repo_article                  $this->em->getRepository(Article::class);
  1469.         $repo_article_commande         $this->em->getRepository(ArticleCommande::class);
  1470.         $repo_type_document_commercial $this->em->getRepository(TypeDocumentCommercial::class);
  1471.         $repo_mode_expedition          $this->em->getRepository(ModeExpedition::class);
  1472.         $repo_article_market_place     $this->em->getRepository(ArticleMarketPlace::class);
  1473.         $repo_taxe                     $this->em->getRepository(Taxe::class);
  1474.         $repo_acompte                  $this->em->getRepository(Acompte::class);
  1475.         $repo_mode_reglement           $this->em->getRepository(ModeReglement::class);
  1476.         $output->writeln('ORDER ID '.$order['orderId']);
  1477.         //print_r($order);
  1478.         $SellingManagerSalesRecordNumber "";
  1479.         if ( ! empty($order['salesRecordReference'])) {
  1480.             $SellingManagerSalesRecordNumber trim($order['salesRecordReference']);
  1481.         }
  1482.         $OrderID trim($order['orderId']);
  1483.         //ebayCollectAndRemitTax
  1484.         $OrderStatus trim($order['orderFulfillmentStatus']);
  1485.         //print_r($order["cancelStatus"]["cancelState"]=="CANCELED");
  1486.         if ( ! empty($order["cancelStatus"]["cancelState"]) && $order["cancelStatus"]["cancelState"] == "CANCELED") {
  1487.             $OrderStatus $order["cancelStatus"]["cancelState"];
  1488.         }
  1489.         $eBayPaymentStatus trim($order['orderPaymentStatus']);
  1490.         $PaymentMethod     trim($order['paymentSummary']['payments'][0]['paymentMethod']);
  1491.         $tauxChange 1;
  1492.         if ( ! empty($order['paymentSummary']['payments'][0]['amount']['value']) && ! empty($order['paymentSummary']['payments'][0]['amount']['convertedFromValue'])) {
  1493.             $tauxChange floatval($order['paymentSummary']['payments'][0]['amount']['value']) / floatval($order['paymentSummary']['payments'][0]['amount']['convertedFromValue']);
  1494.             $tauxChange round($tauxChange3);
  1495.         }
  1496.         $output->writeln('taux de change : '.$tauxChange);
  1497.         $CreatedTime = new \Datetime($order['creationDate']);
  1498.         $CreatedTime->setTimezone(new \DateTimeZone('Europe/Paris'));
  1499.         $BuyerCheckoutMessage '';
  1500.         if (array_key_exists('buyerCheckoutNotes'$order)) {
  1501.             $output->writeln($order['buyerCheckoutNotes']);
  1502.             $BuyerCheckoutMessage json_encode($order['buyerCheckoutNotes']);
  1503.             $output->writeln($BuyerCheckoutMessage);
  1504.         }
  1505.         $shippingCarrierCode '';//transporteur
  1506.         $shippingServiceCode '';//service transporteur
  1507.         $fullName            '';
  1508.         $addressLine1        '';
  1509.         $addressLine2        '';
  1510.         $city                '';
  1511.         $stateOrProvince     '';
  1512.         $postalCode          '';
  1513.         $countryCode         '';
  1514.         $telephone           '';
  1515.         $email               '';
  1516.         if (isset($order['fulfillmentStartInstructions'])) {
  1517.             $shippingStep $order['fulfillmentStartInstructions'][0]['shippingStep'];
  1518.             if (array_key_exists('shippingCarrierCode'$shippingStep)) {
  1519.                 $shippingCarrierCode trim($shippingStep['shippingCarrierCode']);
  1520.             }//transporteur
  1521.             if (array_key_exists('shippingServiceCode'$shippingStep)) {
  1522.                 $shippingServiceCode trim($shippingStep['shippingServiceCode']);
  1523.             }//service transporteur
  1524.             if (array_key_exists('fullName'$shippingStep['shipTo'])) {
  1525.                 $fullName trim($shippingStep['shipTo']['fullName']);
  1526.             }
  1527.             $contactAdress $order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['contactAddress'];
  1528.             if (array_key_exists('addressLine1'$contactAdress)) {
  1529.                 $addressLine1 trim($contactAdress['addressLine1']);
  1530.             }
  1531.             if (array_key_exists('addressLine2'$contactAdress)) {
  1532.                 $addressLine2 trim($contactAdress['addressLine2']);
  1533.             }
  1534.             if (array_key_exists('city'$contactAdress)) {
  1535.                 $city trim($contactAdress['city']);
  1536.             }
  1537.             if (array_key_exists('stateOrProvince'$contactAdress)) {
  1538.                 $stateOrProvince trim($contactAdress['stateOrProvince']);
  1539.             }
  1540.             if (array_key_exists('postalCode'$contactAdress)) {
  1541.                 $postalCode trim($contactAdress['postalCode']);
  1542.             }
  1543.             if (array_key_exists('countryCode'$contactAdress)) {
  1544.                 $countryCode trim($contactAdress['countryCode']);
  1545.             }
  1546.             if ( ! empty($order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['primaryPhone']['phoneNumber'])) {
  1547.                 $telephone $order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['primaryPhone']['phoneNumber'];
  1548.             }
  1549.             if ( ! empty($order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['email'])) {
  1550.                 $email $order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['email'];
  1551.             }
  1552.         }
  1553.         /*
  1554.         $Buyer_Email = '';
  1555.         $Buyer_UserFirstName = '';
  1556.         $Buyer_UserLastName = '';
  1557.                     if(isset($order->TransactionArray->Transaction) && count($order->TransactionArray->Transaction)) {
  1558.                         foreach($order->TransactionArray->Transaction as $transaction) {
  1559.                             $Buyer_Email = $transaction->Buyer->Email;
  1560.                             $Buyer_UserFirstName = $transaction->Buyer->UserFirstName;
  1561.                             $Buyer_UserLastName = $transaction->Buyer->UserLastName;
  1562.                         }
  1563.                     }
  1564.                     */
  1565.         //$BuyerUserID = trim($order->BuyerUserID);
  1566.         $tab_client = [
  1567.             /*
  1568.             'idImport' => 'cpt'.$compte->getId().'_'.trim($order->BuyerUserID),
  1569.             'email' => trim($order->BuyerUserID),
  1570.             'nom' => $Buyer_UserLastName,
  1571.             'prenom' => $Buyer_UserFirstName,
  1572.             */
  1573.             'pays'              => $countryCode,
  1574.             'pays_code_iso'     => $countryCode,
  1575.             'compteMarketPlace' => $compte,
  1576.         ];
  1577.         $client     $this->clientService->getClient($tab_client);
  1578.         $tauxTva 0;
  1579.         $taxe    $this->taxeService->getTaxeDefaut($countryCode);
  1580.         if (is_object($taxe)) {
  1581.             $tauxTva $taxe->getTaux();
  1582.             $output->writeln('Pays code iso : '.$countryCode);
  1583.             $output->writeln('Taxe ID : '.$taxe->getId());
  1584.             $output->writeln('Taxe taux : '.$taxe->getTaux());
  1585.         }
  1586.         $output->writeln('Apres taxe taux');
  1587.         /*
  1588.         $tab_shipping_address = array(
  1589.             'livraisonDefaut' => true,
  1590.             'societe' => trim($order->ShippingAddress->Name),
  1591.             'rue' => trim($order->ShippingAddress->Street1),
  1592.             'complement' => trim($order->ShippingAddress->Street2),
  1593.             'ville' => trim($order->ShippingAddress->CityName),
  1594.             'pays' => trim($order->ShippingAddress->CountryName),
  1595.             'pays_code_iso' => trim($order->ShippingAddress->Country),
  1596.             'idImport' => 'cpt'.$compte->getId().'_'.trim($order->ShippingAddress->AddressID),
  1597.             'telephone' => trim($order->ShippingAddress->Phone),
  1598.             'codePostal' => trim($order->ShippingAddress->PostalCode)
  1599.         );
  1600.         if(is_object($client)) $tab_shipping_address['client'] = $client;
  1601.         //$shipping_address = $service_adresse->getAdresse($tab_shipping_address, $output);
  1602.         */
  1603.         //lien commande / marketplace
  1604.         $query $repo_commande->createQueryBuilder('p')
  1605.                                ->select(
  1606.                                    'p.id,p.reference,sc.id as statut_commande_id, sc.libelle as statut_commande_libelle, scm.libelle as statut_commande_market_place_libelle,scm.reference as statut_commande_market_place_reference'
  1607.                                )//p.commentaireExpedition as commentaire_expedition,p.sifam
  1608.                                ->where(
  1609.                 '(p.archive is null or p.archive = :archive) and p.compteMarketPlace = :compteMarketPlace AND p.idImport = :idImport AND tp.id = :typeDocumentCommercial'
  1610.             )
  1611.                                ->setParameters(['archive' => '0''compteMarketPlace' => $compte->getId(), "idImport" => $OrderID'typeDocumentCommercial' => TypeDocumentCommercial::COMMANDE])
  1612.                                ->setMaxResults(1)
  1613.                                //->join('p.typeDocumentCommercial', 'tp')
  1614.                                ->join('p.statutCommande''sc')
  1615.                                ->leftJoin('p.statutCommandeMarketPlace''scm')
  1616.                                ->orderBy('p.id''ASC');
  1617.         $output->writeln('debut recherche commande');
  1618.         $commande_bdd $query->getQuery()->getOneOrNullResult();
  1619.         $output->writeln('fin recherche commande');
  1620.         $tableau_donnee = [];
  1621.         //$dateCommande = new \Datetime($CreatedTime);
  1622.         //$tableau_donnee["reference"]=$purchaseid;
  1623.         //$tableau_donnee["reference_market_place"]=$SellingManagerSalesRecordNumber;
  1624.         $tableau_donnee["reference_market_place"] = $OrderID;
  1625.         if (is_object($client)) {
  1626.             $tableau_donnee["client_id"] = $client->getId();
  1627.         } else {
  1628.             $tableau_donnee["client_id"] = null;
  1629.         }
  1630.         $tableau_donnee["id_import"]              = $OrderID;
  1631.         $tableau_donnee["compte_market_place_id"] = $compte->getId();
  1632.         $tableau_donnee["dateMaj"]                = (new \Datetime)->format("Y-m-d H:i:s");
  1633.         //$tableau_donnee["date"] = $dateCommande->format('Y-m-d H:i:s');
  1634.         $tableau_donnee["date"]                        = $CreatedTime->format('Y-m-d H:i:s');
  1635.         $tableau_donnee["type_document_commercial_id"] = TypeDocumentCommercial::COMMANDE;
  1636.         $tableau_donnee["archive"]                     = 0;
  1637.         $tableau_donnee["avecTaxe"]                    = 1;
  1638.         $tableau_donnee["statut_paiement_id"]          = 1;
  1639.         $tableau_donnee["etat_commande_id"]            = 1;
  1640.         $tableau_donnee["bascule_comptabilite"]        = 0;
  1641.         $tableau_donnee["visible"]                     = "1";
  1642.         $tableau_donnee["modifiable"]                  = "0";
  1643.         $tableau_donnee["temps_passe"]                 = "0";
  1644.         $tableau_donnee["temps_facture"]               = "0";
  1645.         $tableau_donnee["attente_facturation"]         = "0";
  1646.         $tableau_donnee["origine_saisie"]              = "commande";
  1647.         $tableau_donnee["statut_commande_id"]          = "2";
  1648.         $tableau_donnee["telephone"]                   = $telephone;
  1649.         $tableau_donnee["email"]                       = $email;
  1650.         /*
  1651.         $devise = $service_devise->getDevise(trim($order->Total->currencyID), $output)
  1652.         if(is_object($devise)) $tableau_donnee["devise_id"] = $devise->getId();
  1653.         */
  1654.         /*
  1655.         $tableau_donnee["total_frais_port_ttc"] = floatval($order['pricingSummary']['deliveryCost']['value']);
  1656.         if(!empty($order['pricingSummary']['deliveryDiscount'])) $tableau_donnee["total_frais_port_ttc"] += floatval($order['pricingSummary']['deliveryDiscount']['value']);
  1657.         $tableau_donnee["total_frais_port"] = $tableau_donnee["total_frais_port_ttc"]*(100/(100+floatval($tauxTva)));
  1658.         $tableau_donnee["total_frais_port"] = round($tableau_donnee["total_frais_port"], 2);
  1659.         $tableau_donnee["total_tva_frais_port"] = $tableau_donnee["total_frais_port_ttc"] - $tableau_donnee["total_frais_port"] ;
  1660.         $tableau_donnee["total_ttc"] = floatval($order['pricingSummary']['total']['value']);
  1661.         $tableau_donnee["total"] = floatval($order['pricingSummary']['priceSubtotal']['value'])*(100/(100+floatval($tauxTva)));
  1662.         $tableau_donnee["total"] = round($tableau_donnee["total"], 2);
  1663.         */
  1664.         $tableau_donnee['commentaire'] = $BuyerCheckoutMessage;
  1665.         //livraison
  1666.         /*
  1667.         if(is_object($shipping_address)) $tableau_donnee['adresse_livraison_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_livraison_id'] = NULL;
  1668.         if(is_object($shipping_address) && is_object($shipping_address->getPays())) $tableau_donnee['pays_livraison_id'] = $shipping_address->getPays()->getId(); else $tableau_donnee['pays_livraison_id'] = NULL;
  1669.         if(is_object($shipping_address) && is_object($shipping_address->getVille())) $tableau_donnee['ville_livraison_id'] = $shipping_address->getVille()->getId(); else $tableau_donnee['ville_livraison_id'] = NULL;
  1670.         if(is_object($shipping_address) && is_object($shipping_address->getCodePostal())) $tableau_donnee['code_postal_livraison_id'] = $shipping_address->getCodePostal()->getId(); else $tableau_donnee['code_postal_livraison_id'] = NULL;
  1671.         */
  1672.         $tableau_donnee['adresse_livraison_id']      = null;
  1673.         $tableau_donnee['ville_livraison_txt']       = $city;
  1674.         $tableau_donnee['pays_livraison_txt']        = $countryCode;
  1675.         $tableau_donnee['code_postal_livraison_txt'] = $postalCode;
  1676.         $tableau_donnee['libelle_livraison']         = $fullName;
  1677.         //$tableau_donnee['numero_livraison'] = '';
  1678.         $tableau_donnee['rue_livraison']               = $addressLine1;
  1679.         $tableau_donnee['complement_livraison']        = $addressLine2;
  1680.         $tableau_donnee['code_iso_livraison']          = $countryCode;
  1681.         $tableau_donnee['state_or_province_livraison'] = $countryCode;
  1682.         //facturation
  1683.         /*
  1684.         if(is_object($shipping_address)) $tableau_donnee['adresse_facturation_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_facturation_id'] = NULL;
  1685.         if(is_object($shipping_address) && is_object($shipping_address->getPays())) $tableau_donnee['pays_facturation_id'] = $shipping_address->getPays()->getId(); else $tableau_donnee['pays_facturation_id'] = NULL;
  1686.         if(is_object($shipping_address) && is_object($shipping_address->getVille())) $tableau_donnee['ville_facturation_id'] = $shipping_address->getVille()->getId(); else $tableau_donnee['ville_facturation_id'] = NULL;
  1687.         if(is_object($shipping_address) && is_object($shipping_address->getCodePostal())) $tableau_donnee['code_postal_facturation_id'] = $shipping_address->getCodePostal()->getId(); else $tableau_donnee['code_postal_facturation_id'] = NULL;
  1688.         */
  1689.         $tableau_donnee['adresse_facturation_id']      = null;
  1690.         $tableau_donnee['ville_facturation_txt']       = $city;
  1691.         $tableau_donnee['pays_facturation_txt']        = $countryCode;
  1692.         $tableau_donnee['code_postal_facturation_txt'] = $postalCode;
  1693.         $tableau_donnee['libelle_facturation']         = $fullName;
  1694.         //$tableau_donnee['numero_facturation'] = '';
  1695.         $tableau_donnee['rue_facturation']               = $addressLine1;
  1696.         $tableau_donnee['complement_facturation']        = $addressLine2;
  1697.         $tableau_donnee['code_iso_facturation']          = $countryCode;
  1698.         $tableau_donnee['state_or_province_facturation'] = $countryCode;
  1699.         //ShippingCarrierUsed
  1700.         //transporteur_id
  1701.         //ShipmentTrackingNumber
  1702.         //numero_suivi
  1703.         //AmountPaid
  1704.         /*
  1705.         $tab_statut_commande = array();
  1706.         $tab_statut_commande["reference"]=$OrderStatus;
  1707.         */
  1708.         //statut de commande
  1709.         //mode de reglement marketplace
  1710.         $output->writeln('debut mode de reglement');
  1711.         if ( ! empty($PaymentMethod)) {
  1712.             $mode_reglement_market_place $this->marketPlaceService->getModeReglementMarketPlace($PaymentMethod$compte->getMarketPlace());
  1713.             if (is_object($mode_reglement_market_place)) {
  1714.                 $tableau_donnee['mode_reglement_market_place_id'] = $mode_reglement_market_place->getId();
  1715.                 if (is_object($mode_reglement_market_place->getModeReglement())) {
  1716.                     $tableau_donnee['mode_reglement_id'] = $mode_reglement_market_place->getModeReglement()->getId();
  1717.                 }
  1718.             }
  1719.         }
  1720.         $output->writeln('fin mode de reglement');
  1721.         //mode d'expedition
  1722.         $output->writeln('debut mode expedition');
  1723.         if ( ! empty($shippingServiceCode)) {
  1724.             $tableau_donnee['mode_expedition_id'] = $this->modeExpeditionService->getModeExpedition($shippingServiceCode$shippingServiceCode$compte->getMarketPlace());
  1725.         }
  1726.         if ( ! empty($tableau_donnee['mode_expedition_id'])) {
  1727.             $mode_expedition_obj $repo_mode_expedition->find($tableau_donnee['mode_expedition_id']);
  1728.             if (is_object($mode_expedition_obj) && is_object($mode_expedition_obj->getTransporteur())) {
  1729.                 $tableau_donnee['transporteur_id'] = $mode_expedition_obj->getTransporteur()->getId();
  1730.             }
  1731.         }
  1732.         $output->writeln('fin mode expedition');
  1733.         //statut commande marketplace
  1734.         $output->writeln('debut calculerStatutCommandeMarketPlace');
  1735.         if ( ! empty($OrderStatus)) {
  1736.             $statut_commande_calcule                           $this->commandeService->calculerStatutCommandeMarketPlace($compte$OrderStatus$commande_bdd);
  1737.             $tableau_donnee['statut_commande_market_place_id'] = $statut_commande_calcule["id"];
  1738.             $tableau_donnee['statut_commande_id']              = $statut_commande_calcule["action_statut_commande_id"];
  1739.             if ( ! empty($statut_commande_calcule['statut_paiement_id'])) {
  1740.                 $tableau_donnee['statut_paiement_id'] = $statut_commande_calcule['statut_paiement_id'];
  1741.             }
  1742.         }
  1743.         $output->writeln('fin calculerStatutCommandeMarketPlace');
  1744.         if ($order['orderPaymentStatus'] == 'PAID') {
  1745.             $tableau_donnee['statut_paiement_id'] = 2;
  1746.         }
  1747.         /*
  1748.         if(!empty($order['order_state_reason_code'])){
  1749.             $statut_paiement_calcule = $service_commande->calculerStatutPaiementMarketPlace($order['order_state_reason_code']);
  1750.             $tableau_donnee['statut_paiement_id'] = $statut_paiement_calcule["statut_paiement_id"];
  1751.             if(!empty($statut_paiement_calcule["statut_commande_id"])) $tableau_donnee['statut_commande_id'] = $statut_paiement_calcule["statut_commande_id"];
  1752.         }
  1753.         */
  1754.         /*
  1755.                                 $mode_expedition_bdd = $this->creerModeExpedition($output,$container,$compte,$tab_expedition);
  1756.                                 $tableau_donnee['mode_expedition_id']=$mode_expedition_bdd["id"];
  1757.                                 $tab_reglement = array();
  1758.                                 $tab_reglement["reference"]=$PaymentMethods;
  1759.                                 $mode_reglement_bdd = $this->creerModeReglement($output,$container,$compte,$tab_reglement);
  1760.                                 $tableau_donnee['modereglement_id']=$mode_reglement_bdd["id"];
  1761.                                 if(is_object($ville_obj)) {
  1762.                                     $tableau_donnee['ville_facturation_id']=$ville_obj->getId();
  1763.                                     $tableau_donnee['code_postal_facturation_id']=$ville_obj->getId();
  1764.                                     if(is_object($ville_obj->getParentId()) && is_object($ville_obj->getParentId()->getParentId()) && is_object($ville_obj->getParentId()->getParentId()->getParentId())) {
  1765.                                         $tableau_donnee['pays_facturation_id'] = $ville_obj->getParentId()->getParentId()->getParentId()->getId();
  1766.                                     }
  1767.                                 }
  1768.         */
  1769.         $tableau_donnee_commande $tableau_donnee;
  1770.         $nouvelle_commande_ebay true;
  1771.         //$output->writeln('ETAPE 8 '.$order->OrderID);
  1772.         $mettre_a_jour_cmde        true;
  1773.         $est_une_nouvelle_commande false;
  1774.         if ($commande_bdd['id'] == "") {
  1775.             $est_une_nouvelle_commande true;
  1776.             $commande_obj              = new Commande();
  1777.             $type_commande             TypeDocumentCommercial::COMMANDE;
  1778.             $commande_obj->setTypeDocumentCommercial($type_commande);
  1779.             $tableau_donnee["reference"] = $this->numerotationDocumentService->generer($commande_obj);
  1780.             /*
  1781.             if (array_key_exists('code_postal_livraison_texte', $tableau_donnee)) {
  1782.                 if( substr($tableau_donnee['code_postal_livraison_texte'],0,2) == "20")
  1783.                 {
  1784.                     $tableau_donnee['adresse_a_changer']="1";
  1785.                     $tableau_donnee['commentaireExpedition']="ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE";
  1786.                 }
  1787.             }
  1788.             */
  1789.             $donnees_commande $tableau_donnee;
  1790.             if ($donnee == "Oui") {
  1791.                 $conn->insert('commerciale__commande'$tableau_donnee);
  1792.             }
  1793.             $commande_bdd['id'] = $conn->lastInsertId();
  1794.             $commande_obj $repo_commande->find($commande_bdd['id']);
  1795.             $this->commandeService->creerHistorique($commande_obj10);
  1796.             $output->writeln('<info>TABLE COMMANDE Action : INSERT : '.$tableau_donnee["reference_market_place"].'</info>');
  1797.             $output->writeln('ETAPE 6');
  1798.         } else {
  1799.             if (== && in_array($tableau_donnee["reference_market_place"], ['17-07342-02348'])) {
  1800.             } elseif (
  1801.                 == 1
  1802.                 and
  1803.                 ! empty($commande_bdd['statut_commande_id'])
  1804.                 and
  1805.                 (
  1806.                     //Confirmation d'expédition market place en cours
  1807.                     $commande_bdd["statut_commande_id"] == 36
  1808.                 )
  1809.             ) {
  1810.                 $output->writeln("ON NE MET PLUS A JOUR LA COMMANDE CAR STATUT COMMANDE_ID = ".$commande_bdd["statut_commande_id"]."(Confirmation d'expédition market place en cours)");
  1811.             } elseif (
  1812.                 == 1
  1813.                 and
  1814.                 (
  1815.                     //Partiel préparé
  1816.                     $commande_bdd['statut_commande_id'] == 1
  1817.                     or
  1818.                     // Préparée
  1819.                     $commande_bdd['statut_commande_id'] == 6
  1820.                     or
  1821.                     // Partiellement livrée
  1822.                     $commande_bdd['statut_commande_id'] == 28
  1823.                     or
  1824.                     // Livrée
  1825.                     $commande_bdd['statut_commande_id'] == 29
  1826.                     or
  1827.                     // Confirmation d'expédition market place en cours
  1828.                     $commande_bdd['statut_commande_id'] == 36
  1829.                     or
  1830.                     // Expédiée
  1831.                     $commande_bdd['statut_commande_id'] == 37
  1832.                     or
  1833.                     // En attente du numéro de suivi
  1834.                     $commande_bdd['statut_commande_id'] == 40
  1835.                 )
  1836.             ) {
  1837.                 // Si la commande redescend en expédié on passe la commande dans l'erp en expédiée
  1838.                 $commande_redescendu_comme_expedie false;
  1839.                 if ($commande_bdd["statut_commande_id"] == 6) {
  1840.                     //$OrderStatus = "FULFILLED";
  1841.                     if ( ! empty($OrderStatus)) {
  1842.                         //$donnees_commande['statut_commande_market_place_id'] = $service_market_place->getStatutCommandeMarketPlace($OrderState, $marketPlace);
  1843.                         $statut_commande_calcule $this->commandeService->calculerStatutCommandeMarketPlace($compte$OrderStatus$commande_bdd);
  1844.                         //print_r($statut_commande_calcule);
  1845.                         if ( ! empty($statut_commande_calcule["action_statut_commande_id"]) && $statut_commande_calcule["action_statut_commande_id"] == "37") {
  1846.                             $commande_obj $repo_commande->find($commande_bdd['id']);
  1847.                             $this->commandeService->creerHistorique($commande_obj14);
  1848.                             $commande_redescendu_comme_expedie true;
  1849.                             $req_ligne_commande "select id,ral_client,article_id,quantite from commerciale__article_commande where commande_id = ".$commande_bdd["id"];
  1850.                             $output->writeln($req_ligne_commande);
  1851.                             $stmt               $conn->executeQuery($req_ligne_commande);
  1852.                             $ligne_commande_bdd $stmt->fetchAllAssociative();
  1853.                             if (count($ligne_commande_bdd) > 0) {
  1854.                                 foreach ($ligne_commande_bdd as $l_bdd) {
  1855.                                     $donnees_ac               = [];
  1856.                                     $donnees_ac['ral_client'] = 0;
  1857.                                     $conn->update('commerciale__article_commande'$donnees_ac, ['id' => $l_bdd['id']]);
  1858.                                     $output->writeln("ID_ARTICLE_COMMANDE:".$l_bdd['id']);
  1859.                                     //$variation = floatval($ac_bdd['quantite']) - floatval($Quantity);
  1860.                                     $article_obj $repo_article->find($l_bdd['article_id']);
  1861.                                     if ($l_bdd['ral_client'] > 0) {
  1862.                                         $stock_reserve floatval($article_obj->getStockReserve()) - $l_bdd['quantite'];
  1863.                                         $stock_reserve max(0$stock_reserve);
  1864.                                         $conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article_obj->getId()]);
  1865.                                     }
  1866.                                     $sql_bp "select id,reference,statut_commande_id
  1867.                                       FROM `commerciale__commande`
  1868.                                       WHERE commande_id = ".$commande_bdd["id"]."
  1869.                                       and type_document_commercial_id = ".TypeDocumentCommercial::BP."
  1870.                                       and statut_commande_id = 10
  1871.                                       ";
  1872.                                     $stmt   $conn->executeQuery($sql_bp);
  1873.                                     $bp_bdd $stmt->fetchAllAssociative();
  1874.                                     if (count($bp_bdd) > 0) {
  1875.                                         foreach ($bp_bdd as $un_bp_bdd) {
  1876.                                             $output->writeln("ON ANNULE LE BP :".$un_bp_bdd['id']." REF:".$un_bp_bdd['reference']);
  1877.                                             $donnees_historique             = [];
  1878.                                             $donnees_historique["message "] = "";
  1879.                                             $bp_obj                         $repo_commande->find($un_bp_bdd['id']);
  1880.                                             $this->commandeService->creerHistorique($bp_obj29$donnees_historique);
  1881.                                             $donnees_bp_annule                       = [];
  1882.                                             $donnees_bp_annule["statut_commande_id"] = 24;
  1883.                                             $conn->update('commerciale__commande'$donnees_bp_annule, ['id' => $un_bp_bdd['id']]);
  1884.                                         }
  1885.                                     }
  1886.                                     $donnees_commande_temp                                    = [];
  1887.                                     $donnees_commande_temp['statut_commande_market_place_id'] = $statut_commande_calcule["id"];
  1888.                                     $donnees_commande_temp['statut_commande_id']              = $statut_commande_calcule["action_statut_commande_id"];
  1889.                                     //print_r($donnees_commande_temp);
  1890.                                     $conn->update('commerciale__commande'$donnees_commande_temp, ['id' => $commande_bdd["id"]]);
  1891.                                 }
  1892.                             }
  1893.                             /*
  1894.                             $donnees_ac['ral_client'] = 0;
  1895.                             $conn->update('commerciale__article_commande',$donnees_ac, array('id'=>$ac_bdd['id']));
  1896.                             //$variation = floatval($ac_bdd['quantite']) - floatval($Quantity);
  1897.                             $stock_reserve = floatval($article->getStockReserve()) - $ac_bdd['quantite'];
  1898.                             $stock_reserve = max(0, $stock_reserve);
  1899.                             $conn->update('article__article',array('stock_reserve'=>$stock_reserve), array('id'=>$article->getId()));
  1900.                             */
  1901.                         }
  1902.                     }
  1903.                 }
  1904.                 $trad_libelle_statut_commande "";
  1905.                 if ($commande_bdd["statut_commande_id"] == 37) {
  1906.                     $trad_libelle_statut_commande "Expédiée";
  1907.                 } elseif ($commande_bdd["statut_commande_id"] == 1) {
  1908.                     $trad_libelle_statut_commande "Partiel préparé";
  1909.                 } elseif ($commande_bdd["statut_commande_id"] == 6) {
  1910.                     $trad_libelle_statut_commande "Passé en BP";
  1911.                 } elseif ($commande_bdd["statut_commande_id"] == 7) {
  1912.                     $trad_libelle_statut_commande "Annulée";
  1913.                 } elseif ($commande_bdd["statut_commande_id"] == 28) {
  1914.                     $trad_libelle_statut_commande "Partiellement livrée";
  1915.                 } elseif ($commande_bdd["statut_commande_id"] == 29) {
  1916.                     $trad_libelle_statut_commande "Livrée";
  1917.                 }
  1918.                 if ($commande_redescendu_comme_expedie) {
  1919.                     $output->writeln(
  1920.                         "ON PASSE LA COMMANDE EN EXPEDIE CAR STATUT COMMANDE_ID ERP = ".$commande_bdd["statut_commande_id"]."(".$trad_libelle_statut_commande.") ET STATUT MARKET PLACE : ".$OrderStatus
  1921.                     );
  1922.                 } else {
  1923.                     // ON FAIT RIEN
  1924.                     $output->writeln("ON NE MET PLUS A JOUR LA COMMANDE CAR STATUT COMMANDE_ID = ".$commande_bdd["statut_commande_id"]."(".$trad_libelle_statut_commande.")");
  1925.                 }
  1926.                 $mettre_a_jour_cmde false;
  1927.             }
  1928.             $output->writeln('ETAPE 7');
  1929.             $nouvelle_commande_ebay      false;
  1930.             $tableau_donnee["reference"] = $commande_bdd['reference'];
  1931.             $donnees_commande $tableau_donnee;
  1932.             if ($donnee == "Oui" && $mettre_a_jour_cmde) {
  1933.                 $conn->update('commerciale__commande'$tableau_donnee, ['id' => $commande_bdd['id']]);
  1934.             }
  1935.             $commande_obj $repo_commande->find($commande_bdd['id']);
  1936.             if ($mettre_a_jour_cmde) {
  1937.                 $this->commandeService->creerHistorique($commande_obj14);
  1938.             }
  1939.             if ($mettre_a_jour_cmde) {
  1940.                 $output->writeln('<info>TABLE COMMANDE Action : UPDATE : '.$tableau_donnee["reference_market_place"].' / ID : '.$commande_bdd['id'].'</info>');
  1941.             } else {
  1942.                 $output->writeln(
  1943.                     '<info>TABLE COMMANDE Action : AUCUNE CAR statut_commande_id = '.$commande_bdd['statut_commande_id'].' : '.$tableau_donnee["reference_market_place"].' / ID : '.$commande_bdd['id'].'</info>'
  1944.                 );
  1945.                 $output->writeln('TEST AA');
  1946.             }
  1947.         }
  1948.         //$output->writeln('ETAPE 9 '.$order->OrderID);
  1949.         //$handle_pdf = fopen($domaine.$url_pdf, 'r');
  1950.         //$mettre_a_jour_cmde = true;//pour test
  1951.         $calculerHt false;
  1952.         if ($mettre_a_jour_cmde && isset($order['lineItems'])) {
  1953.             //print_r($order);
  1954.             $output->writeln('ETAPE 10 ');
  1955.             $total_poids 0;
  1956.             if ( ! empty($order['lineItems'])) {
  1957.                 $output->writeln('lines '.count($order['lineItems']));
  1958.             }
  1959.             $total_tva_de_la_commande 0;
  1960.             foreach ($order['lineItems'] as $item) {
  1961.                 $output->writeln('line ');
  1962.                 $ItemID          trim($item['legacyItemId']);
  1963.                 $OrderLineItemID trim($item['lineItemId']);
  1964.                 /* RECHERCHE ANNONCE */
  1965.                 $article_market_place $this->articleMarketPlaceService->getArticleMarketPlace(["idImport" => $ItemID"compteMarketPlace" => $compte], $output);
  1966.                 if (is_object($article_market_place)) {
  1967.                     $select 'p.id,a.id as article_id,r.id as regle_taxe_id,r.tauxDefaut as regle_taxe_taux_defaut,fd.id as fournisseur_defaut_id';
  1968.                     $query  $repo_article_market_place->createQueryBuilder('p')
  1969.                                                         ->select($select)
  1970.                                                         ->leftJoin('p.article''a')
  1971.                                                         ->leftJoin('a.regleTaxe''r')
  1972.                                                         ->leftJoin('a.fournisseurDefaut''fd')
  1973.                                                         ->where("p.id = :id")
  1974.                                                         ->setParameters(["id" => $article_market_place->getId()])
  1975.                                                         ->setMaxResults(1)
  1976.                                                         ->orderBy('p.id''ASC');
  1977.                     $article_market_place_bdd $query->getQuery()->getOneOrNullResult();
  1978.                 }
  1979.                 if ($article_market_place_bdd['id'] != "") {
  1980.                     /*
  1981.                     if($article_market_place_bdd['fournisseur_defaut_id'] == 2) {
  1982.                         $commande_vega = true;
  1983.                     }
  1984.                     if($article_market_place_bdd['fournisseur_defaut_id'] == 95) {
  1985.                         $commande_sifam = true;
  1986.                     }
  1987.                     */
  1988.                     //$output->writeln('ARTICLE TROUVE ');
  1989.                     //$output->writeln('PRIX '.$item_price.' REGLE TAXE : '.$article_market_place_bdd["regle_taxe_taux_defaut"].'% ARTICLE TROUVE AMP:'.$article_market_place_bdd["id"].' AID : '.$article_market_place_bdd["article_id"]);
  1990.                     $parametersArticleCommandeEbay = [];
  1991.                     $where                         "p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace";
  1992.                     //$where = "p.commande = :commande AND p.article = :article";
  1993.                     $parametersArticleCommandeEbay["commande"]           = $commande_bdd['id'];
  1994.                     $parametersArticleCommandeEbay["article"]            = $article_market_place_bdd["article_id"];
  1995.                     $parametersArticleCommandeEbay["articleMarketPlace"] = $article_market_place_bdd["id"];
  1996.                     //test;
  1997.                     /*
  1998.                     $query = $repo_article_commande->createQueryBuilder('p')
  1999.                             ->select('p.id')
  2000.                             ->where('p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace')
  2001.                             ->setParameters(array('commande' => $commande_bdd['id'],"article"=>$article_market_place_bdd["article_id"]))
  2002.                             ->setMaxResults(1)
  2003.                             ->orderBy('p.id', 'ASC');
  2004.                     */
  2005.                     $compteur_variation 0;
  2006.                     $tabVariationEbay   = [];
  2007.                     //if(!empty($item['legacyVariationId'])) $tabVariationEbay[] = $item['legacyVariationId'];
  2008.                     /*
  2009.                     if(isset($item->Variation)) {
  2010.                         if(isset($item->Variation->VariationSpecifics)) {
  2011.                             if(isset($item->Variation->VariationSpecifics)) {
  2012.                                 if(isset($item->Variation->VariationSpecifics->NameValueList)) {
  2013.                                     if(isset($item->Variation->VariationSpecifics->NameValueList)) {
  2014.                                         foreach($item->Variation->VariationSpecifics->NameValueList as $variationArticle) {
  2015.                                             $compteur_variation++;
  2016.                                             if($compteur_variation<4) {
  2017.                                                 $parametersArticleCommandeEbay["declinaison".$compteur_variation]=$variationArticle->Name.":".$variationArticle->Value;
  2018.                                                 $where .= " AND p.declinaison".$compteur_variation." = :declinaison".$compteur_variation;
  2019.                                                 $tabVariationEbay[]=$variationArticle->Name.":".$variationArticle->Value;
  2020.                                             }
  2021.                                         }
  2022.                                     }
  2023.                                 }
  2024.                             }
  2025.                         }
  2026.                     }
  2027.                     */
  2028.                     $query $repo_article_commande->createQueryBuilder('p')
  2029.                                                    ->select('p.id,p.ralClient,p.quantite')
  2030.                                                    ->where($where)
  2031.                                                    ->setParameters($parametersArticleCommandeEbay)
  2032.                                                    ->setMaxResults(1)
  2033.                                                    ->orderBy('p.id''ASC');
  2034.                     $article_commande_bdd $query->getQuery()->getOneOrNullResult();
  2035.                     $quantite floatval(trim($item['quantity']));
  2036.                     $total_poids += $quantite $article_market_place->getArticle()->getPoids();
  2037.                     //$total_ttc = floatval(trim($item['total']['value']));
  2038.                     //$total_ttc = floatval(trim($item['lineItemCost']['value']));
  2039.                     //$montantTransport = floatval(trim($item['deliveryCost']['shippingCost']['value']));
  2040.                     $devise $this->deviseService->getDevise(trim($item['lineItemCost']['currency']), $output);
  2041.                     if (count($item['taxes'])) {
  2042.                         $montantTva 0;
  2043.                         foreach ($item['taxes'] as $tax) {
  2044.                             $montantTva += floatval(trim($tax['amount']['value']));
  2045.                         }
  2046.                         //$total_ht = $total_ttc - $montantTva;
  2047.                         $total_ht floatval(trim($item['lineItemCost']['value']));
  2048.                         if (array_key_exists('discountedLineItemCost'$item)) {
  2049.                             $total_ht floatval(trim($item['discountedLineItemCost']['value']));
  2050.                         }
  2051.                         $total_ttc $montantTva $total_ht;
  2052.                         $tauxTva   $montantTva $total_ht 100;
  2053.                         $tauxTva   round($tauxTva1);
  2054.                         $taxe      $repo_taxe->findOneBy(['taux' => $tauxTva]);
  2055.                         $output->writeln('taxe taux calculé :'.$tauxTva);
  2056.                         if (is_object($taxe)) {
  2057.                             $output->writeln('taxe calculée ID :'.$taxe->getId());
  2058.                         }
  2059.                     } else {
  2060.                         $calculerHt true;
  2061.                         $total_ttc  floatval(trim($item['lineItemCost']['value']));
  2062.                         if (array_key_exists('discountedLineItemCost'$item)) {
  2063.                             $total_ttc floatval(trim($item['discountedLineItemCost']['value']));
  2064.                         }
  2065.                         if ($tauxChange) {
  2066.                             $total_ttc $total_ttc $tauxChange;
  2067.                             $total_ttc round($total_ttc3);
  2068.                         }
  2069.                         $total_ht floatval($total_ttc) * (100 / (100 $tauxTva));
  2070.                         //$totalHt -= $montantTransport;
  2071.                         //$total_ht = round($total_ht, 2);
  2072.                         $total_ht round($total_ht3);
  2073.                         //$total_ht = round($total_ht, 2,PHP_ROUND_HALF_DOWN);
  2074.                         $montantTva $total_ttc $total_ht;
  2075.                     }
  2076.                     /*
  2077.                     $total_ht = floatval($total_ttc) * (100 / (100 + $tauxTva));
  2078.                     $total_ht = round($total_ht, 2);
  2079.                     $montantTva = $total_ttc - $total_ht;
  2080.                     */
  2081.                     $prix_ht $total_ht;
  2082.                     if ( ! empty($quantite)) {
  2083.                         $prix_ht $prix_ht $quantite;
  2084.                     }
  2085.                     /*
  2086.                     $prix_ht = $TransactionPrice_value;
  2087.                     $total_ht = $prix_ht * $QuantityPurchased;
  2088.                     $total_ht = round($total_ht, 2);
  2089.                     $prix_ttc = $TransactionPrice_value + $TotalTaxAmount_value;
  2090.                     $total_with_tax = $prix_ttc * $QuantityPurchased;
  2091.                     $total_with_tax = round($total_with_tax, 2);
  2092.                     $tva = $total_with_tax - $total_ht;
  2093.                     */
  2094.                     $tableau_donnee = [];
  2095.                     for ($v 0$v count($tabVariationEbay); $v++) {
  2096.                         $tableau_donnee["declinaison_".($v 1)] = $tabVariationEbay[$v];
  2097.                     }
  2098.                     //$output->writeln('ETAPE 12 '.$order->OrderID);
  2099.                     //On passe l'article en mouvemente
  2100.                     $conn->update('article__article', ["mouvemente" => 1], ["id" => $article_market_place_bdd["article_id"]]);
  2101.                     $tableau_donnee["libelle"]                 = trim($item['title']);
  2102.                     $tableau_donnee["article_id"]              = $article_market_place_bdd["article_id"];
  2103.                     $tableau_donnee["article_market_place_id"] = $article_market_place_bdd["id"];
  2104.                     $tableau_donnee["commande_id"]             = $commande_bdd['id'];
  2105.                     $tableau_donnee["date_maj"]                = (new \Datetime)->format("Y-m-d H:i:s");
  2106.                     $tableau_donnee["position"]                = "0";
  2107.                     $tableau_donnee["reference"]               = $ItemID;
  2108.                     $tableau_donnee["quantite"]                = $quantite;
  2109.                     $tableau_donnee["profondeur"]            = "0";
  2110.                     $tableau_donnee["hauteur"]               = "0";
  2111.                     $tableau_donnee["poids"]                 = "0";
  2112.                     $tableau_donnee["remise"]                = "0";
  2113.                     $tableau_donnee["remise_supplementaire"] = "0";
  2114.                     $tableau_donnee["prix_base"]             = $prix_ht;
  2115.                     $tableau_donnee["total_ht"]              = $total_ht;
  2116.                     $tableau_donnee["total_with_tax"]        = $total_ttc;
  2117.                     $tableau_donnee["tva_vente"]             = $montantTva;
  2118.                     $tableau_donnee["tva"]                   = $tauxTva;
  2119.                     if (is_object($taxe)) {
  2120.                         $tableau_donnee["taxe_id"] = $taxe->getId();
  2121.                     } else {
  2122.                         $tableau_donnee["taxe_id"] = null;
  2123.                     }
  2124.                     $tableau_donnee["taux_change"]      = $tauxChange;
  2125.                     $tableau_donnee["total_ttc_devise"] = floatval(trim($item['lineItemCost']['value']));
  2126.                     if (array_key_exists('discountedLineItemCost'$item)) {
  2127.                         $tableau_donnee["total_ttc_devise"] = floatval(trim($item['discountedLineItemCost']['value']));
  2128.                     }
  2129.                     $output->writeln('total_ht : '.$total_ht);
  2130.                     $output->writeln('total_with_tax : '.$total_ttc);
  2131.                     $output->writeln('tva_vente : '.$tableau_donnee["tva_vente"]);
  2132.                     $output->writeln('tva : '.$tauxTva);
  2133.                     $output->writeln('taxe_id : '.$tableau_donnee["taxe_id"]);
  2134.                     $total_tva_de_la_commande += $tableau_donnee["tva_vente"];
  2135.                     /*
  2136.                     $total_frais_port_ttc = $ShippingServiceCost_value;
  2137.                     $tableau_donnee["total_frais_port"]=$total_frais_port_ttc;
  2138.                     $tableau_donnee["total_frais_port_ttc"]=$total_frais_port_ttc;
  2139.                     $tableau_donnee["total_tva_frais_port"]=0;
  2140.                     */
  2141.                     //print_r($tableau_donnee);
  2142.                     $tableau_donnee['id_import'] = $OrderLineItemID;
  2143.                     if ($article_commande_bdd['id'] == "") {
  2144.                         $tableau_donnee['ral_client'] = $tableau_donnee['quantite'];
  2145.                         if ($est_une_nouvelle_commande && ($donnees_commande['statut_commande_id'] == "37" or $donnees_commande['statut_commande_id'] == "29")) {
  2146.                             $tableau_donnee['ral_client'] = 0;
  2147.                         } else {
  2148.                             $article       $repo_article->find($article_market_place_bdd["article_id"]);
  2149.                             $stock_reserve floatval($article->getStockReserve()) + floatval($tableau_donnee['quantite']);
  2150.                             $stock_reserve max(0$stock_reserve);
  2151.                             $conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article->getId()]);
  2152.                         }
  2153.                         $tableau_donnee['date'] = (new \Datetime)->format("Y-m-d H:i:s");
  2154.                         if ($donnee == "Oui") {
  2155.                             $conn->insert('commerciale__article_commande'$tableau_donnee);
  2156.                         }
  2157.                         $article_commande_bdd['id'] = $conn->lastInsertId();
  2158.                         $output->writeln('publierAnnonce 1');
  2159.                         $this->publierAnnonce($article_market_place_bdd["article_id"], ''$output);
  2160.                         //$output->writeln('<info>TABLE ARTICLE COMMANDE Action : INSERT : '.$commande_bdd['id'].'</info>');
  2161.                     } else {
  2162.                         $param_update_ac_ebay = [];
  2163.                         //Cas d'une commande acceptée puis annulée entre temps par le client ou expédié depuis le marketplace
  2164.                         if ( ! $est_une_nouvelle_commande
  2165.                              &&
  2166.                              (
  2167.                                  $commande_bdd["statut_commande_id"] == //Acceptée
  2168.                                  or
  2169.                                  $commande_bdd["statut_commande_id"] == //En attente
  2170.                                  or
  2171.                                  $commande_bdd["statut_commande_id"] == 38 //Non identifié
  2172.                              )
  2173.                              &&
  2174.                              ($donnees_commande['statut_commande_id'] == "7" or $donnees_commande['statut_commande_id'] == "37" or $donnees_commande['statut_commande_id'] == "29")
  2175.                         ) {
  2176.                             $article $repo_article->find($article_market_place_bdd["article_id"]);
  2177.                             $param_update_ac_ebay['ral_client'] = 0;
  2178.                             //$conn->update('commerciale__article_commande',$donnees_ac, array('id'=>$article_commande_bdd['id']));
  2179.                             //$variation = floatval($ac_bdd['quantite']) - floatval($QuantityOrdered);
  2180.                             $stock_reserve floatval($article->getStockReserve()) - $tableau_donnee['quantite'];
  2181.                             $stock_reserve max(0$stock_reserve);
  2182.                             $conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article->getId()]);
  2183.                             $output->writeln('publierAnnonce 2');
  2184.                             $this->publierAnnonce($article_market_place_bdd["article_id"], ''$output);
  2185.                         } else {
  2186.                             $variation floatval($article_commande_bdd['quantite']) - floatval($tableau_donnee['quantite']);
  2187.                             if ($variation != 0) {
  2188.                                 $article $repo_article->find($article_market_place_bdd["article_id"]);
  2189.                                 //modification du ral client
  2190.                                 //$donnees_ac = array();
  2191.                                 $param_update_ac_ebay['ral_client'] = floatval($article_commande_bdd['ralClient']) + $variation;
  2192.                                 //modification de la reservation de stock
  2193.                                 $stock_reserve floatval($article->getStockReserve()) + $variation;
  2194.                                 $stock_reserve max(0$stock_reserve);
  2195.                                 $conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article->getId()]);
  2196.                                 $output->writeln('publierAnnonce 3');
  2197.                                 $this->publierAnnonce($article_market_place_bdd["article_id"], ''$output);
  2198.                             }
  2199.                             //$conn->update('commerciale__article_commande',$donnees_ac, array('id'=>$ac_bdd['id']));
  2200.                         }
  2201.                         $param_update_ac_ebay['id_import']               = $OrderLineItemID;
  2202.                         $param_update_ac_ebay["article_id"]              = $article_market_place_bdd["article_id"];
  2203.                         $param_update_ac_ebay["commande_id"]             = $commande_bdd["id"];
  2204.                         $param_update_ac_ebay["article_market_place_id"] = $article_market_place_bdd["id"];
  2205.                         for ($v 0$v count($tabVariationEbay); $v++) {
  2206.                             $param_update_ac_ebay["declinaison_".($v 1)] = $tabVariationEbay[$v];
  2207.                         }
  2208.                         if ($donnee == "Oui") {
  2209.                             $conn->update('commerciale__article_commande'$tableau_donnee$param_update_ac_ebay);
  2210.                         }
  2211.                         //if($donnee == "Oui") $conn->update('commerciale__article_commande', $tableau_donnee, array('article_id' => $article_market_place_bdd["article_id"],'commande_id'=>$commande_bdd['id']));
  2212.                         //$output->writeln('<info>TABLE ARTICLE COMMANDE Action : UPDATE : '.$commande_bdd['id'].'</info>');
  2213.                     }
  2214.                     //$output->writeln('ETAPE 13 '.$order->OrderID);
  2215.                 } else {
  2216.                     $tab_introuvable[] = "MarketPlace ".$compte->getMarketPlace()->getLibelle()." : ".$compte->getLibelle(
  2217.                         )." Commande : ".$SellingManagerSalesRecordNumber." Produit : ".$ItemID;
  2218.                     $output->writeln('<error>ARTICLE INTROUVABLE '.$ItemID.'</error>');
  2219.                 }
  2220.                 //$this->calculerTotalCommande($commande_bdd['id']);
  2221.                 //if($nouvelle_commande_ebay) $this->calculerTotalCommande($output,$container,$commande_bdd['id'],$tableau_donnee_commande);
  2222.             }
  2223.             $output->writeln('total_poids:'.$total_poids);
  2224.             //exit;
  2225.             $repo_mode_expedition_poids_transporteur $this->em->getRepository(ModeExpeditionPoidsTransporteur::class);
  2226.             $tableau_donnee                = [];
  2227.             $tableau_donnee["total_poids"] = $total_poids;
  2228.             if ( ! empty($donnees_commande['mode_expedition_id']) and $total_poids 0) {
  2229.                 $output->writeln('mode_expedition_id:'.$donnees_commande['mode_expedition_id']);
  2230.                 $mode_expedition_poids_transporteur $repo_mode_expedition_poids_transporteur->getTransporteurParPoids($total_poids 1000$donnees_commande['mode_expedition_id']);
  2231.                 if (is_object($mode_expedition_poids_transporteur) && is_object($mode_expedition_poids_transporteur->getTransporteur())) {
  2232.                     $tableau_donnee["transporteur_id"] = $mode_expedition_poids_transporteur->getTransporteur()->getId();
  2233.                 }
  2234.             }
  2235.             //taxes
  2236.             $devise $this->deviseService->getDevise(trim($order['pricingSummary']['total']['currency']), $output);
  2237.             if (is_object($devise)) {
  2238.                 $tableau_donnee["devise_id"] = $devise->getId();
  2239.             }
  2240.             $tableau_donnee["total_frais_port_ttc"] = floatval($order['pricingSummary']['deliveryCost']['value']);
  2241.             if ( ! empty($order['pricingSummary']['deliveryDiscount'])) {
  2242.                 $tableau_donnee["total_frais_port_ttc"] += floatval($order['pricingSummary']['deliveryDiscount']['value']);
  2243.             }
  2244.             if ($tauxChange != 0) {
  2245.                 $tableau_donnee["total_frais_port_ttc"] = $tableau_donnee["total_frais_port_ttc"] * $tauxChange;
  2246.                 $tableau_donnee["total_frais_port_ttc"] = round($tableau_donnee["total_frais_port_ttc"], 2);
  2247.             }
  2248.             $tableau_donnee["total_frais_port"]     = $tableau_donnee["total_frais_port_ttc"] * (100 / (100 floatval($tauxTva)));
  2249.             $tableau_donnee["total_frais_port"]     = round($tableau_donnee["total_frais_port"], 2);
  2250.             $tableau_donnee["total_tva_frais_port"] = $tableau_donnee["total_frais_port_ttc"] - $tableau_donnee["total_frais_port"];
  2251.             $tableau_donnee["total_ttc"]        = floatval($order['pricingSummary']['total']['value']);
  2252.             $tableau_donnee["total_ttc_devise"] = floatval($order['pricingSummary']['total']['value']);
  2253.             $tableau_donnee["total"]            = floatval($order['pricingSummary']['priceSubtotal']['value']);
  2254.             if (array_key_exists('priceDiscount'$order['pricingSummary'])) {
  2255.                 $tableau_donnee["total"] += floatval($order['pricingSummary']['priceDiscount']['value']);
  2256.             }
  2257.             /*
  2258.             if(array_key_exists('deliveryCost', $order['pricingSummary'])){
  2259.                 $tableau_donnee["total"] -= floatval($order['pricingSummary']['deliveryCost']['value']);
  2260.             }
  2261.             */
  2262.             if ($tauxChange != 0) {
  2263.                 $tableau_donnee["taux_change"] = $tauxChange;
  2264.                 $tableau_donnee["total_ttc"]   = $tableau_donnee["total_ttc"] * $tauxChange;
  2265.                 $tableau_donnee["total_ttc"]   = round($tableau_donnee["total_ttc"], 3);
  2266.                 $tableau_donnee["total"]       = $tableau_donnee["total"] * $tauxChange;
  2267.                 $tableau_donnee["total"]       = round($tableau_donnee["total"], 3);
  2268.                 $total_tva_de_la_commande $total_tva_de_la_commande $tauxChange;
  2269.             }
  2270.             if ($calculerHt) {
  2271.                 $tableau_donnee["total"] -= $total_tva_de_la_commande;
  2272.             }
  2273.             print_r($tableau_donnee);
  2274.             $conn->update('commerciale__commande'$tableau_donnee, ['id' => $commande_bdd['id']]);
  2275.         }
  2276.         if ( ! empty($commande_bdd['id']) && ! empty($tableau_donnee_commande["statut_commande_id"]) && $tableau_donnee_commande["statut_commande_id"] != 7) {
  2277.             $acompte $repo_acompte->findOneBy(["commande" => $commande_bdd['id']]);
  2278.             if (== && ! is_object($acompte) && $order['orderPaymentStatus'] == 'PAID' && ! empty($tableau_donnee["total_ttc"])) {
  2279.                 switch ($compte->getId()) {
  2280.                     case 11:
  2281.                         $mode_reglement_id 19;
  2282.                         break;
  2283.                     case 12:
  2284.                         $mode_reglement_id 20;
  2285.                         break;
  2286.                     case 13:
  2287.                         $mode_reglement_id 21;
  2288.                         break;
  2289.                     default:
  2290.                         $mode_reglement_id null;
  2291.                         break;
  2292.                 }
  2293.                 $acompte = [
  2294.                     //'id_import' =>
  2295.                     'date'              => $CreatedTime->format('Y-m-d H:i:s'),
  2296.                     'dateReglement'     => $CreatedTime->format('Y-m-d H:i:s'),
  2297.                     'commande_id'       => $commande_bdd['id'],
  2298.                     'mode_reglement_id' => $mode_reglement_id,
  2299.                     'nomClient'         => $fullName,
  2300.                     //'montant' => floatval($order['pricingSummary']['total']['value']),
  2301.                     'montant'           => $tableau_donnee["total_ttc"],
  2302.                     'solde'             => 0,
  2303.                     'est_parent'        => 0,
  2304.                     'operation_diverse' => 0,
  2305.                     'transfert_compta'  => 0,
  2306.                     'type_reglement_id' => 1,
  2307.                     'commentaire'       => 'Paiement de la commande '.$OrderID,
  2308.                 ];
  2309.                 if (is_object($client)) {
  2310.                     $acompte['client_id'] = $client->getId();
  2311.                     $solde                $this->acompteService->getSoldeClient($client);
  2312.                     $acompte['solde']     = $solde;
  2313.                 }
  2314.                 $acompteObj = new Acompte;
  2315.                 $acompteObj->setModeReglement($repo_mode_reglement->find($mode_reglement_id));
  2316.                 $numerotation         $this->numerotationDocumentService->generer($acompteObj);
  2317.                 $acompte['numTraite'] = $numerotation;
  2318.                 $conn->insert('commerciale__acompte'$acompte);
  2319.             }
  2320.         }
  2321.         //echo "LLLLLLL";
  2322.         //historique
  2323.         //priorisation?
  2324.         //pdf?
  2325.     }
  2326.     public function getCategories($compteMarketPlace$category 0$output '')
  2327.     {
  2328.         $authToken $this->getAuthToken($compteMarketPlace);
  2329.         if (empty($authToken)) {
  2330.             return $authToken;
  2331.         }
  2332.         //https://developer.ebay.com/api-docs/commerce/taxonomy/resources/methods
  2333.         //https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategoryTree#_samples
  2334.         $url 'https://api.ebay.com/commerce/taxonomy/v1/category_tree/'.$category;
  2335.         if (is_object($output)) {
  2336.             $output->writeln($url);
  2337.         }
  2338.         $ch curl_init();
  2339.         curl_setopt($chCURLOPT_URL$url);
  2340.         //curl_setopt($ch, CURLOPT_POST, 1);
  2341.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2342.             //'Content-Type: application/json',
  2343.             //'Accept: application/json',
  2344.             'Authorization: Bearer '.$authToken,
  2345.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2346.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2347.             'Accept-Encoding: application/gzip',
  2348.             'Accept-Language: fr-FR',
  2349.         ]);
  2350.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  2351.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2352.         curl_setopt($chCURLOPT_ENCODING"gzip");
  2353.         $retour curl_exec($ch);
  2354.         return json_decode($retour);
  2355.     }
  2356.     public function getDefaultCategoryTreeId($compteMarketPlace$marketplace_id 'EBAY_FR'$output '')
  2357.     {
  2358.         $authToken $this->getAuthToken($compteMarketPlace);
  2359.         if (empty($authToken)) {
  2360.             return $authToken;
  2361.         }
  2362.         //https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getDefaultCategoryTreeId#uri.marketplace_id
  2363.         $url 'https://api.ebay.com/commerce/taxonomy/v1/get_default_category_tree_id?marketplace_id='.$marketplace_id;
  2364.         if (is_object($output)) {
  2365.             $output->writeln($url);
  2366.         }
  2367.         $ch curl_init();
  2368.         curl_setopt($chCURLOPT_URL$url);
  2369.         //curl_setopt($ch, CURLOPT_POST, 1);
  2370.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2371.             //'Content-Type: application/json',
  2372.             //'Accept: application/json',
  2373.             'Authorization: Bearer '.$authToken,
  2374.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2375.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2376.             'Accept-Encoding: application/gzip',
  2377.             'Accept-Language: fr-FR',
  2378.         ]);
  2379.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  2380.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2381.         curl_setopt($chCURLOPT_ENCODING"gzip");
  2382.         $retour curl_exec($ch);
  2383.         return json_decode($retour);
  2384.     }
  2385.     public function getCategorySubtree($compteMarketPlace$category$output '')
  2386.     {
  2387.         $authToken $this->getAuthToken($compteMarketPlace);
  2388.         if (empty($authToken)) {
  2389.             return $authToken;
  2390.         }
  2391.         $cat $this->getDefaultCategoryTreeId($compteMarketPlace'EBAY_FR'$output);
  2392.         if ( ! is_object($cat)) {
  2393.             return;
  2394.         }
  2395.         //https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategorySubtree
  2396.         $url 'https://api.ebay.com/commerce/taxonomy/v1/category_tree/'.$cat->categoryTreeId.'/get_category_subtree?category_id='.$category;
  2397.         return $this->boucleCategories($compteMarketPlace$url$output);
  2398.         /*
  2399.         if(is_object($output)) $output->writeln($url);
  2400.         $ch = curl_init();
  2401.         curl_setopt($ch, CURLOPT_URL, $url);
  2402.         //curl_setopt($ch, CURLOPT_POST, 1);
  2403.         curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  2404.             //'Content-Type: application/json',
  2405.             //'Accept: application/json',
  2406.             'Authorization: Bearer '.$authToken,
  2407.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2408.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2409.             'Accept-Encoding: application/gzip',
  2410.             'Accept-Language: fr-FR',
  2411.         ));
  2412.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  2413.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2414.         curl_setopt($ch,CURLOPT_ENCODING , "gzip");
  2415.         $retour = curl_exec($ch);
  2416.         return json_decode($retour);
  2417.         */
  2418.     }
  2419.     private function boucleCategories($compteMarketPlace$url$output ''$tree = [])
  2420.     {
  2421.         $authToken $this->getAuthToken($compteMarketPlace);
  2422.         if (empty($authToken)) {
  2423.             return $authToken;
  2424.         }
  2425.         if (is_object($output)) {
  2426.             $output->writeln($url);
  2427.         }
  2428.         $ch curl_init();
  2429.         curl_setopt($chCURLOPT_URL$url);
  2430.         //curl_setopt($ch, CURLOPT_POST, 1);
  2431.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2432.             //'Content-Type: application/json',
  2433.             //'Accept: application/json',
  2434.             'Authorization: Bearer '.$authToken,
  2435.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2436.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2437.             'Accept-Encoding: application/gzip',
  2438.             'Accept-Language: fr-FR',
  2439.         ]);
  2440.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  2441.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2442.         curl_setopt($chCURLOPT_ENCODING"gzip");
  2443.         $retour curl_exec($ch);
  2444.         $retour json_decode($retour);
  2445.         if (is_object($retour) && ! empty($retour->categorySubtreeNode) && is_object($retour->categorySubtreeNode)) {
  2446.             if ( ! empty($retour->categorySubtreeNode->category) && is_object(
  2447.                     $retour->categorySubtreeNode->category
  2448.                 ) && ! empty($retour->categorySubtreeNode->category->categoryId) && ! empty($retour->categorySubtreeNode->category->categoryName)) {
  2449.                 $tree[] = ['categoryId' => $retour->categorySubtreeNode->category->categoryId'categoryName' => $retour->categorySubtreeNode->category->categoryName];
  2450.             }
  2451.             if ( ! empty($retour->categorySubtreeNode->parentCategoryTreeNodeHref)) {
  2452.                 $tree $this->boucleCategories($compteMarketPlace$retour->categorySubtreeNode->parentCategoryTreeNodeHref$output$tree);
  2453.             }
  2454.         }
  2455.         return array_reverse($tree);
  2456.     }
  2457.     public function majCategoriesEbay($compte$output "")
  2458.     {
  2459.         $conn $this->em->getConnection();
  2460.         $conn->getConfiguration()->setSQLLogger(null);
  2461.         $marketPlace    $compte->getMarketPlace();
  2462.         $repo_categorie $this->em->getRepository(Categorie::class);
  2463.         $cat            $this->getDefaultCategoryTreeId($compte'EBAY_FR'$output);
  2464.         if (is_object($output)) {
  2465.             $output->writeln('t1');
  2466.         }
  2467.         if (is_object($cat)) {
  2468.             $categorieRoot $this->getCategories($compte$cat->categoryTreeId$output);
  2469.             //print_r($categorieRoot);
  2470.             if (is_object($output)) {
  2471.                 $output->writeln('t2');
  2472.             }
  2473.             $parent null;
  2474.             if ( ! empty($categorieRoot) && is_object($categorieRoot) && ! empty($categorieRoot->rootCategoryNode) && is_object($categorieRoot->rootCategoryNode)) {
  2475.                 if (is_object($output)) {
  2476.                     $output->writeln('t3');
  2477.                 }
  2478.                 $this->verifierCategorieExiste($conn$marketPlace$output$repo_categorie$categorieRoot->rootCategoryNode$parent);
  2479.                 /*
  2480.                 if(is_object($categorieRoot->category)) {
  2481.                     $idImport = $categorieRoot->category->categoryId;
  2482.                     $categoryName = $categorieRoot->category->categoryId;
  2483.                     $categorie = $repo_categorie->findOneBy(array(
  2484.                         'dateSuppression' => NULL,
  2485.                         'idImport' => $idImport,
  2486.                         'marketPlace' => $marketPlace
  2487.                     ));
  2488.                     $conn->insert('article__categorie',array(
  2489.                         'date' => (new \Datetime)->format('Y-m-d h:i:s'),
  2490.                         'id_import' => $idImport,
  2491.                         'market_place_id' => $marketPlace->getId(),
  2492.                         'libelle' => $categoryName,
  2493.                         'reference' => $idImport
  2494.                     ));
  2495.                     $parent = $conn->lastInsertId();
  2496.                 }
  2497.                 */
  2498.             }
  2499.         }
  2500.     }
  2501.     private function verifierCategorieExiste($conn$marketPlace$output$repo_categorie$category$parent)
  2502.     {
  2503.         //print_r($category);
  2504.         if (is_object($category->category)) {
  2505.             $idImport     $category->category->categoryId;
  2506.             $categoryName $category->category->categoryName;
  2507.             $categorie    $repo_categorie->findOneBy([
  2508.                                                            'dateSuppression' => null,
  2509.                                                            'idImport'        => $idImport,
  2510.                                                            'marketPlace'     => $marketPlace,
  2511.                                                        ]);
  2512.             if (is_object($categorie)) {
  2513.                 $parent $categorie->getId();
  2514.                 if (is_object($output)) {
  2515.                     $output->writeln('La catégorie "'.$categoryName.'" existe.');
  2516.                 }
  2517.             } else {
  2518.                 $conn->insert('article__categorie', [
  2519.                     'date'                => (new \Datetime)->format('Y-m-d H:i:s'),
  2520.                     'id_import'           => $idImport,
  2521.                     'market_place_id'     => $marketPlace->getId(),
  2522.                     'libelle'             => $categoryName,
  2523.                     'reference'           => $idImport,
  2524.                     'categorie_parent_id' => $parent,
  2525.                 ]);
  2526.                 $parent $conn->lastInsertId();
  2527.                 if (is_object($output)) {
  2528.                     $output->writeln('Création de la catégorie : '.$categoryName);
  2529.                 }
  2530.             }
  2531.         }
  2532.         if ( ! empty($category->childCategoryTreeNodes) && count($category->childCategoryTreeNodes)) {
  2533.             foreach ($category->childCategoryTreeNodes as $catTmp) {
  2534.                 $this->verifierCategorieExiste($conn$marketPlace$output$repo_categorie$catTmp$parent);
  2535.             }
  2536.         }
  2537.     }
  2538.     public function CreateShippingFulfillment($commande$ShippingFulfillmentDetails$output '')
  2539.     {
  2540.         $compteMarketPlace $commande->getCompteMarketPlace();
  2541.         $authToken         $this->getAuthToken($compteMarketPlace);
  2542.         if (empty($authToken)) {
  2543.             return $authToken;
  2544.         }
  2545.         #https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/shipping_fulfillment/methods/createShippingFulfillment#request.lineItems.lineItemId
  2546.         //$url = 'https://api.ebay.com/sell/fulfillment/v1/order/'.$commande->getIdImport().'/shipping_fulfillment';
  2547.         $url 'https://api.ebay.com/sell/fulfillment/v1/order/'.$commande->getIdImport().'/shipping_fulfillment';
  2548.         if (is_object($output)) {
  2549.             $output->writeln($url);
  2550.         }
  2551.         $ch curl_init();
  2552.         curl_setopt($chCURLOPT_URL$url);
  2553.         //curl_setopt($ch, CURLOPT_POST, 1);
  2554.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2555.             'Content-Type: application/json',
  2556.             'Accept: application/json',
  2557.             'Authorization: Bearer '.$authToken,
  2558.             //'Content-Language: fr-FR',
  2559.             //'Accept-Language: fr-FR',
  2560.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2561.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2562.         ]);
  2563.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  2564.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  2565.         if ($ShippingFulfillmentDetails != '') {
  2566.             curl_setopt($chCURLOPT_POST1);
  2567.             curl_setopt($chCURLOPT_POSTFIELDS$ShippingFulfillmentDetails);
  2568.         }
  2569.         $retour curl_exec($ch);
  2570.         print_r(json_decode($retour));
  2571.         //return 202;
  2572.         return curl_getinfo($chCURLINFO_HTTP_CODE);
  2573.     }
  2574.     public function getOffer($articleMarketPlace$output '')
  2575.     {
  2576.         $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  2577.         $authToken         $this->getAuthToken($compteMarketPlace);
  2578.         if (empty($authToken)) {
  2579.             return $authToken;
  2580.         }
  2581.         #https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getOffer
  2582.         $url 'https://api.ebay.com/sell/inventory/v1/offer/'.$articleMarketPlace->getIdImport();
  2583.         if (is_object($output)) {
  2584.             $output->writeln($url);
  2585.         }
  2586.         $ch curl_init();
  2587.         curl_setopt($chCURLOPT_URL$url);
  2588.         //curl_setopt($ch, CURLOPT_POST, 1);
  2589.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2590.             //'Content-Type: application/json',
  2591.             //'Accept: application/json',
  2592.             'Authorization: Bearer '.$authToken,
  2593.             //'Content-Language: fr-FR',
  2594.             //'Accept-Language: fr-FR',
  2595.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2596.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2597.         ]);
  2598.         //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2599.         $retour curl_exec($ch);
  2600.         print_r($retour);
  2601.         $output->writeln('getOffer CURLINFO_HTTP_CODE : '.curl_getinfo($chCURLINFO_HTTP_CODE));
  2602.         if (curl_getinfo($chCURLINFO_HTTP_CODE) != 200) {
  2603.             return false;
  2604.         }
  2605.         return json_decode($retour);
  2606.     }
  2607.     public function getOffers($articleMarketPlace$output '')
  2608.     {
  2609.         $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  2610.         $authToken         $this->getAuthToken($compteMarketPlace);
  2611.         if (empty($authToken)) {
  2612.             return $authToken;
  2613.         }
  2614.         #https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getOffer
  2615.         $url 'https://api.ebay.com/sell/inventory/v1/offer?';
  2616.         $url .= 'sku='.$articleMarketPlace->getSku();
  2617.         if (is_object($output)) {
  2618.             $output->writeln($url);
  2619.         }
  2620.         $ch curl_init();
  2621.         curl_setopt($chCURLOPT_URL$url);
  2622.         //curl_setopt($ch, CURLOPT_POST, 1);
  2623.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2624.             //'Content-Type: application/json',
  2625.             //'Accept: application/json',
  2626.             'Authorization: Bearer '.$authToken,
  2627.             //'Content-Language: fr-FR',
  2628.             //'Accept-Language: fr-FR',
  2629.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2630.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2631.         ]);
  2632.         //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2633.         $retour curl_exec($ch);
  2634.         print_r($retour);
  2635.         $output->writeln('getOffer CURLINFO_HTTP_CODE : '.curl_getinfo($chCURLINFO_HTTP_CODE));
  2636.         if (curl_getinfo($chCURLINFO_HTTP_CODE) != 200) {
  2637.             return false;
  2638.         }
  2639.         return json_decode($retour);
  2640.     }
  2641.     public function updateOffer($articleMarketPlace$output '')
  2642.     {
  2643.         $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  2644.         $authToken         $this->getAuthToken($compteMarketPlace);
  2645.         if (empty($authToken)) {
  2646.             return $authToken;
  2647.         }
  2648.         $post_data $this->getOffer($articleMarketPlace$output);
  2649.         if ( ! $post_data) {
  2650.             return false;
  2651.         }
  2652.         #https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/updateOffer
  2653.         $url 'https://api.ebay.com/sell/inventory/v1/offer/'.$articleMarketPlace->getIdImport();
  2654.         if (is_object($output)) {
  2655.             $output->writeln($url);
  2656.         }
  2657.         $ch curl_init();
  2658.         curl_setopt($chCURLOPT_URL$url);
  2659.         curl_setopt($chCURLOPT_POST1);
  2660.         curl_setopt($chCURLOPT_HTTPHEADER, [
  2661.             //'Content-Type: application/json',
  2662.             //'Accept: application/json',
  2663.             'Authorization: Bearer '.$authToken,
  2664.             'Content-Language: fr-FR',
  2665.             //'Accept-Language: fr-FR',
  2666.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  2667.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  2668.         ]);
  2669.         //qte 30
  2670.         //prix 28.9
  2671.         print_r($post_data);
  2672.         $post_data['availableQuantity']                = 29;
  2673.         $post_data['pricingSummary']['price']['value'] = 28.9;
  2674.         $post_data                                     json_encode($post_data);
  2675.         print_r($post_data);
  2676.         //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  2677.         curl_setopt($chCURLOPT_POSTFIELDS$post_data);
  2678.         //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2679.         $retour curl_exec($ch);
  2680.         print_r(json_decode($retour));
  2681.         if (curl_getinfo($chCURLINFO_HTTP_CODE) == 204) {
  2682.             return true;
  2683.         }
  2684.         return false;
  2685.         /*
  2686.         return 202;
  2687.         return curl_getinfo($ch, CURLINFO_HTTP_CODE);
  2688.         */
  2689.     }
  2690.     public function GetSellerList($articleMarketPlace ''$compteMarketPlace ''$nbHeures 5$output)
  2691.     {
  2692.         if (empty($compteMarketPlace) && ! empty($articleMarketPlace)) {
  2693.             $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  2694.         }
  2695.         $authToken $this->getAuthToken($compteMarketPlace);
  2696.         if (empty($authToken)) {
  2697.             return $authToken;
  2698.         }
  2699.         $conn $this->em->getConnection();
  2700.         $conn->getConfiguration()->setSQLLogger(null);
  2701.         $request                                      = new Types\GetSellerListRequestType();
  2702.         $request->RequesterCredentials                = new Types\CustomSecurityHeaderType();
  2703.         $request->RequesterCredentials->eBayAuthToken $authToken;
  2704.         if ( ! empty($articleMarketPlace)) {
  2705.             $SKUArray          = new Types\SKUArrayType();
  2706.             $SKUArray->SKU[]   = $articleMarketPlace->getSku();
  2707.             $request->SKUArray $SKUArray;
  2708.         }
  2709.         $request->StartTimeFrom = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"))->modify('- '.$nbHeures.' hours');
  2710.         $request->StartTimeTo   = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"));
  2711.         $response               = @$this->getTradingService($compteMarketPlace$output)->getSellerList($request);
  2712.         //print_r($response);
  2713.         return $response;
  2714.     }
  2715.     public function reviseFixedPriceItem($articleMarketPlace$donnees$output$authToken ''$count 0)
  2716.     {
  2717.         //limit api calls
  2718.         $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  2719.         if (($compteMarketPlace->getAppelApiHeure() / $compteMarketPlace->getAppelApiHeureLimit() * 100) > 80) {
  2720.             return;
  2721.         }
  2722.         if (($compteMarketPlace->getAppelApiJour() / $compteMarketPlace->getAppelApiJourLimit() * 100) > 80) {
  2723.             return;
  2724.         }
  2725.         if (empty($articleMarketPlace->getIdImport())) {
  2726.             return;
  2727.         }
  2728.         //verifier erreur
  2729.         $erreurExiste $this->em->getRepository(ErreurPublicationArticleMarketPlace::class)->findOneBy(['articleMarketPlace' => $articleMarketPlace'verifie' => false]);
  2730.         if ($erreurExiste) {
  2731.             return;
  2732.         }
  2733.         if (empty($authToken)) {
  2734.             $authToken $this->getAuthToken($compteMarketPlace$output);
  2735.         }
  2736.         if (empty($authToken)) {
  2737.             return $authToken;
  2738.         }
  2739.         $conn $this->em->getConnection();
  2740.         $conn->getConfiguration()->setSQLLogger(null);
  2741.         $output->writeln('t1.2');
  2742.         $date           = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"));
  2743.         $endTime        $articleMarketPlace->getEndTime();
  2744.         $mettreAjour    false;
  2745.         $seuilMiseAjour 5000;
  2746.         if ((array_key_exists('quantite'$donnees) && floatval($donnees['quantite']) === $articleMarketPlace->getStockMarketPlace()) || (floatval(
  2747.                                                                                                                                               $articleMarketPlace->getStockMarketPlace()
  2748.                                                                                                                                           ) > $seuilMiseAjour && array_key_exists(
  2749.                                                                                                                                               'quantite',
  2750.                                                                                                                                               $donnees
  2751.                                                                                                                                           ) && floatval(
  2752.                                                                                                                                                    $donnees['quantite']
  2753.                                                                                                                                                ) > $seuilMiseAjour)) {
  2754.             $output->writeln('quantite identique sur le market place ou stock > '.$seuilMiseAjour);
  2755.             $tableau_donnee["statut_article_market_place_id"] = 2;//publié
  2756.             $tableau_donnee["date_publication_market_place"]  = $date->format("Y-m-d H:i:s");
  2757.             $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlace->getId()]);
  2758.             return;
  2759.         } elseif ( ! is_object($endTime) || (is_object($endTime) && $date $endTime)) {
  2760.             $mettreAjour true;
  2761.         } else {
  2762.             $response $this->getItem($articleMarketPlace'ReturnAll'$authToken);
  2763.             if ($response->Ack === 'Failure' && $count 3) {
  2764.                 $count++;
  2765.                 $this->reviseFixedPriceItem($articleMarketPlace$donnees$output''$count);
  2766.             }
  2767.             if ($response->Ack !== 'Failure') {
  2768.                 $output->writeln('t2');
  2769.                 $endTime      $response->Item->ListingDetails->EndTime;
  2770.                 $itemOriginel $response->Item;
  2771.                 //print_r($endTime);
  2772.                 if (is_object($endTime) && $date $endTime) {
  2773.                     $output->writeln('Annonce terminée');
  2774.                     $tableau_donnee["statut_article_market_place_id"] = 2;//publié
  2775.                     //$tableau_donnee["statut"]=0;
  2776.                     //$tableau_donnee["visible"]=0;
  2777.                     $tableau_donnee["date_publication_market_place"] = (new \Datetime)->format("Y-m-d H:i:s");
  2778.                     $tableau_donnee["end_time"]                      = $endTime->format("Y-m-d H:i:s");
  2779.                     $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlace->getId()]);
  2780.                     return;
  2781.                 }
  2782.                 if (array_key_exists('quantite'$donnees)) {
  2783.                     $output->writeln('qte bdd '.floatval($donnees['quantite']).' == qte ebay'.$response->Item->Quantity);
  2784.                 }
  2785.                 if (array_key_exists('prix'$donnees)) {
  2786.                     $output->writeln('prix bdd '.floatval($donnees['prix'])).'==? prix ebay'.$response->Item->StartPrice->value;
  2787.                 }
  2788.                 if (array_key_exists('quantite'$donnees) && floatval($donnees['quantite']) == $response->Item->Quantity && array_key_exists(
  2789.                         'prix',
  2790.                         $donnees
  2791.                     ) && $response->Item->StartPrice->value == floatval($donnees['prix'])) {
  2792.                     $output->writeln('Pas de modification');
  2793.                     $tableau_donnee["statut_article_market_place_id"] = 2;//publié
  2794.                     $tableau_donnee["date_publication_market_place"]  = (new \Datetime)->format("Y-m-d H:i:s");
  2795.                     $tableau_donnee["end_time"]                       = $endTime->format("Y-m-d H:i:s");
  2796.                     $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlace->getId()]);
  2797.                     return;
  2798.                 }
  2799.                 $mettreAjour true;
  2800.             }
  2801.         }
  2802.         if ($mettreAjour) {
  2803.             $output->writeln('t3');
  2804.             $item = new Types\ItemType();
  2805.             if (array_key_exists('prix'$donnees)) {
  2806.                 //$item->BuyItNowPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
  2807.                 //$item->FloorPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
  2808.                 //$item->CeilingPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
  2809.                 //decommenter celui ci-dessous
  2810.                 //$item->StartPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
  2811.                 if ( ! empty($itemOriginel)) {
  2812.                     $output->writeln("Modification du prix ".$itemOriginel->StartPrice->value.' -> '.floatval($donnees['prix']));
  2813.                 }
  2814.             }
  2815.             if (array_key_exists('quantite'$donnees)) {
  2816.                 $item->Quantity intval($donnees['quantite']);
  2817.             }
  2818.             //identifier l'annonce
  2819.             $item->ItemID $articleMarketPlace->getIdImport();
  2820.             //$item->SKU = $articleMarketPlace->getSku();
  2821.             //Revise item
  2822.             $request                                      = new Types\ReviseFixedPriceItemRequestType();
  2823.             $request->RequesterCredentials                = new Types\CustomSecurityHeaderType();
  2824.             $request->RequesterCredentials->eBayAuthToken $authToken;
  2825.             $request->Item                                $item;
  2826.             $response                                     = @$this->getTradingService($compteMarketPlace$output)->reviseFixedPriceItem($request);
  2827.             $output->writeln('t4');
  2828.             if ($response->Ack !== 'Failure') {
  2829.                 $output->writeln('t5');
  2830.                 $output->writeln("The item was successfully revised on eBay.");
  2831.                 $tableau_donnee                                   = [];
  2832.                 $date                                             = new \Datetime();
  2833.                 $tableau_donnee["statut_article_market_place_id"] = 2;//publié
  2834.                 $tableau_donnee["statut"]                         = 1;
  2835.                 $tableau_donnee["date_publication_market_place"]  = $date->format("Y-m-d H:i:s");
  2836.                 if (array_key_exists('quantite'$donnees)) {
  2837.                     $tableau_donnee['stock_market_place'] = intval($donnees['quantite']);
  2838.                 }
  2839.                 $tableau_donnee["end_time"] = $response->EndTime->format("Y-m-d H:i:s");
  2840.                 //$article_market_place->setEndTime($response->EndTime);
  2841.                 //print_r($tableau_donnee);
  2842.                 $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlace->getId()]);
  2843.                 $this->supprimerErreur($response->ItemID);
  2844.                 $this->articleMarketPlaceService->creerHistorique($articleMarketPlace8, []);
  2845.                 return;
  2846.             } else {
  2847.                 foreach ($response->Errors as $error) {
  2848.                     if (in_array($error->ErrorCode, [10007'10007']) && $count 3) {
  2849.                         $count++;
  2850.                         sleep(1);
  2851.                         $this->reviseFixedPriceItem($articleMarketPlace$donnees$output''$count);
  2852.                     } elseif (in_array($error->ErrorCode, [291'291'])) {
  2853.                         $output->writeln('Annonce terminée');
  2854.                         $tableau_donnee["statut_article_market_place_id"] = 2;//publié
  2855.                         //$tableau_donnee["statut"]=0;
  2856.                         //$tableau_donnee["visible"]=0;
  2857.                         $tableau_donnee["date_publication_market_place"] = (new \Datetime)->format("Y-m-d H:i:s");
  2858.                         if ( ! empty($response->EndTime)) {
  2859.                             $tableau_donnee["end_time"] = $response->EndTime->format("Y-m-d H:i:s");
  2860.                         } else {
  2861.                             $tableau_donnee["end_time"] = (new \Datetime)->format("Y-m-d H:i:s");
  2862.                         }
  2863.                         $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlace->getId()]);
  2864.                         return;
  2865.                     }
  2866.                 }
  2867.                 $this->creerErreur($response$item->ItemID'''MarketPlaceEnvoiArticle reviseFixedPriceItem');
  2868.                 $this->articleMarketPlaceService->creerHistorique($articleMarketPlace15, []);
  2869.             }
  2870.         }
  2871.     }
  2872.     public function publierAnnonce($articleId ''$articleMarketPlaceId ''$output '')
  2873.     {
  2874.         if (is_object($output)) {
  2875.             $output->writeln('publierAnnonce');
  2876.         }
  2877.         $conn $this->em->getConnection();
  2878.         $conn->getConfiguration()->setSQLLogger(null);
  2879.         $em                                               $this->em;
  2880.         $tableau_donnee                                   = [];
  2881.         $date                                             = new \Datetime();
  2882.         $tableau_donnee["statut_article_market_place_id"] = 1;// à publier
  2883.         $tableau_donnee["date_publication_market_place"]  = $date->format("Y-m-d H:i:s");
  2884.         if ( ! empty($articleId)) {
  2885.             $conn->update('article__article', ['maj_dispo' => 1], ['id' => $articleId]);
  2886.             $conn->update('market_place__article'$tableau_donnee, ['article_id' => $articleId]);
  2887.             //getComposantsComposeVirtuel
  2888.             $repo_article_composant $em->getRepository(ArticleComposant::class);
  2889.             $composants             $repo_article_composant->getComposantsComposeVirtuel($articleId)->getQuery()->getResult();
  2890.             if (count($composants) > 0) {
  2891.                 foreach ($composants as $cp) {
  2892.                     if (is_object($cp->getArticleCompose())) {
  2893.                         $this->publierAnnonce($cp->getArticleCompose()->getId());
  2894.                     }
  2895.                 }
  2896.             }
  2897.         } elseif ( ! empty($articleMarketPlaceId)) {
  2898.             /*
  2899.             $historique = $service_article_market_place->creerHistorique($articleMarketPlaceId, 3);
  2900.             if(!empty($historique->getTitre())){
  2901.                 $donneesHisto = array(
  2902.                     'article_market_place_id' => $articleMarketPlaceId
  2903.                     'titre' => $historique->getTitre(),
  2904.                     'message' => $historique->getMessage(),
  2905.                 );
  2906.                 if(is_object($historique->getUtilisateur())) $donneesHisto['utilisateur_id'] = $historique->getUtilisateur()->getId();
  2907.                 $conn->insert('market_place__historique_article_market_place', );
  2908.             }
  2909.             */
  2910.             $conn->update('market_place__article'$tableau_donnee, ['id' => $articleMarketPlaceId]);
  2911.         }
  2912.     }
  2913.     private function supprimerErreur($idImportArticleMaketPlace$idArticleMaketPlace '')
  2914.     {
  2915.         $em                        $this->em;
  2916.         $repo_article_market_place $this->em->getRepository(ArticleMarketPlace::class);
  2917.         if ($idArticleMaketPlace != '') {
  2918.             $articleMarketPlace $repo_article_market_place->find($idArticleMaketPlace);
  2919.         } else {
  2920.             $articleMarketPlace $repo_article_market_place->findOneBy(['idImport' => $idImportArticleMaketPlace]);
  2921.         }
  2922.         $erreur '';
  2923.         if (is_object($articleMarketPlace)) {
  2924.             $erreur $this->em->getRepository(ErreurPublicationArticleMarketPlace::class)->findOneBy(['articleMarketPlace' => $articleMarketPlace'verifie' => false]);
  2925.         }
  2926.         if (is_object($erreur)) {
  2927.             echo 'supprimer erreur : id -> '.$erreur->getId().'<br>';
  2928.             $erreur->setVerifie(true);
  2929.             $em->persist($erreur);
  2930.             $em->flush();
  2931.         }
  2932.     }
  2933.     private function creerErreur($response$idImportArticleMaketPlace$idArticleMaketPlace ''$origine 'MarketPlaceEnvoiArticle')
  2934.     {
  2935.         $log                       '';
  2936.         $em                        $this->em;
  2937.         $repo_article_market_place $this->em->getRepository(ArticleMarketPlace::class);
  2938.         if ($idArticleMaketPlace != '') {
  2939.             $articleMarketPlace $repo_article_market_place->find($idArticleMaketPlace);
  2940.         } else {
  2941.             $articleMarketPlace $repo_article_market_place->findOneBy(['idImport' => $idImportArticleMaketPlace]);
  2942.         }
  2943.         $log '<?xml version="1.0" encoding="UTF-8"?>';
  2944.         $log .= '<messages>';
  2945.         foreach ($response->Errors as $error) {
  2946.             printf(
  2947.                 "%s: %s\n%s\n\n",
  2948.                 $error->SeverityCode === Enums\SeverityCodeType::C_ERROR 'Error' 'Warning',
  2949.                 $error->ShortMessage,
  2950.                 $error->LongMessage
  2951.             );
  2952.             $log .= '<message>';
  2953.             $error->SeverityCode === Enums\SeverityCodeType::C_ERROR $log .= '<type>Error</type>' $log .= '<type>Warning</type>';
  2954.             $log .= '<ErrorCode>'.$error->ErrorCode.'</ErrorCode>';
  2955.             $log .= '<Origine>'.$origine.'</Origine>';
  2956.             $log .= '<ShortMessage>"'.$error->ShortMessage.'"</ShortMessage>';
  2957.             $log .= '<LongMessage>"'.str_replace(['<''>'], ''$error->LongMessage).'"</LongMessage>';
  2958.             $log .= '</message>';
  2959.         }
  2960.         $log    .= '</messages>';
  2961.         $erreur '';
  2962.         if (is_object($articleMarketPlace)) {
  2963.             echo 'erreur articleMarketPlace : '.$articleMarketPlace->getId().'<br>';
  2964.             $erreur $this->em->getRepository(ErreurPublicationArticleMarketPlace::class)->findOneBy(['articleMarketPlace' => $articleMarketPlace'verifie' => false]);
  2965.         }
  2966.         if ( ! is_object($erreur)) {
  2967.             $erreur = new ErreurPublicationArticleMarketPlace;
  2968.             $erreur->setVerifie(false);
  2969.             echo 'creerErreur : nouvelle erreur<br>';
  2970.         } else {
  2971.             echo 'creerErreur : id -> '.$erreur->getId().'<br>';
  2972.         }
  2973.         $erreur->setLogs($log);
  2974.         if (is_object($articleMarketPlace)) {
  2975.             $erreur->setArticleMarketPlace($articleMarketPlace);
  2976.             $article $articleMarketPlace->getArticle();
  2977.             if (is_object($article)) {
  2978.                 $erreur->setArticle($article);
  2979.             }
  2980.         }
  2981.         $em->persist($erreur);
  2982.         $em->flush();
  2983.     }
  2984.     public function uploadFile()
  2985.     {
  2986.         /*
  2987.         POST /FileTransferService HTTP/1.1
  2988. Content-type: multipart/related; boundary=
  2989. MIMEBoundaryurn_uuid_C0FC77A812E40EAE841226969745133;type="application/xop+xml";start="<0.
  2990. urn:uuid:883CA9C91CE9C469D912223894056542>";start-info="text/xml"
  2991. X-EBAY-SOA-SERVICE-NAME: FileTransferService
  2992. X-EBAY-SOA-OPERATION-NAME: uploadFile
  2993. X-EBAY-SOA-SECURITY-TOKEN: ABC...123
  2994. X-EBAY-SOA-REQUEST-DATA-FORMAT: XML
  2995. X-EBAY-SOA-RESPONSE-DATA-FORMAT: XML
  2996. User-Agent: Jakarta Commons-HttpClient/3.1
  2997. Host: beta.storage.sandbox.ebay.com:8082
  2998. Content-Length: 2680
  2999. --MIMEBoundaryurn_uuid_C0FC77A812E40EAE841226969745133
  3000. Content-Type: application/xop+xml; charset=UTF-8; type="text/xml; charset=UTF-8"
  3001. Content-Transfer-Encoding: binary
  3002. Content-ID: <0.urn:uuid:883CA9C91CE9C469D912223894056542>
  3003. <?xml version='1.0' encoding='UTF-8'?><uploadFileRequest
  3004. xmlns:sct="http://www.ebay.com/soaframework/common/types"
  3005. xmlns="http://www.ebay.com/marketplace/services"><taskReferenceId>
  3006. 5********19</taskReferenceId><fileReferenceId>5********69</fileReferenceId><fileFormat>
  3007. gzip</fileFormat><fileAttachment><Data><xop:Include
  3008. xmlns:xop="http://www.w3.org/2004/08/xop/include"
  3009. href="cid:urn:uuid:EE69C2F1D5C814ADF71222389408640" /></Data> </fileAttachment>
  3010. </uploadFileRequest>
  3011. --MIMEBoundaryurn_uuid_C0FC77A812E40EAE841226969745133
  3012. Content-Type: application/octet-stream
  3013. Content-Transfer-Encoding: binary
  3014. Content-ID: <urn:uuid:EE69C2F1D5C814ADF71222389408640>
  3015. */
  3016.         $compteMarketPlace $articleMarketPlace->getCompteMarketPlace();
  3017.         $authToken         $this->getAuthToken($compteMarketPlace);
  3018.         if (empty($authToken)) {
  3019.             return $authToken;
  3020.         }
  3021.         $post_data $this->getOffer($articleMarketPlace$output);
  3022.         if ( ! $post_data) {
  3023.             return false;
  3024.         }
  3025. #https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/updateOffer
  3026.         $url 'https://api.ebay.com/sell/inventory/v1/offer/'.$articleMarketPlace->getIdImport();
  3027.         if (is_object($output)) {
  3028.             $output->writeln($url);
  3029.         }
  3030.         $ch curl_init();
  3031.         curl_setopt($chCURLOPT_URL$url);
  3032.         curl_setopt($chCURLOPT_POST1);
  3033.         curl_setopt($chCURLOPT_HTTPHEADER, [
  3034.             //'Content-Type: application/json',
  3035.             //'Accept: application/json',
  3036.             'X-EBAY-SOA-SECURITY-TOKEN: '.$authToken,
  3037.             'X-EBAY-SOA-OPERATION-NAME: uploadFile',
  3038.             //'Accept-Language: fr-FR',
  3039.             //'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
  3040.             //'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
  3041.         ]);
  3042. //qte 30
  3043. //prix 28.9
  3044.         print_r($post_data);
  3045.         $post_data['availableQuantity']                = 29;
  3046.         $post_data['pricingSummary']['price']['value'] = 28.9;
  3047.         $post_data                                     json_encode($post_data);
  3048.         print_r($post_data);
  3049. //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
  3050.         curl_setopt($chCURLOPT_POSTFIELDS$post_data);
  3051. //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3052.         $retour curl_exec($ch);
  3053.         print_r(json_decode($retour));
  3054.         if (curl_getinfo($chCURLINFO_HTTP_CODE) == 204) {
  3055.             return true;
  3056.         }
  3057.         return false;
  3058.     }
  3059. }