<?php
namespace App\Service\MarketPlace;
use App\Entity\Articles\ArticleComposant;
use App\Entity\Articles\Categorie;
use App\Entity\GestionComerciale\ArticleCommande;
use App\Entity\GestionComerciale\ModeExpedition;
use App\Entity\GestionComerciale\ModeExpeditionPoidsTransporteur;
use App\Entity\GestionComerciale\ModeReglement;
use App\Model\GestionCommerciale\TypeDocumentCommercial;
use App\Entity\Taxes\Taxe;
use App\Service\Articles\DeviseService;
use App\Service\Clients\ClientService;
use App\Service\GestionComerciale\AcompteService;
use App\Service\GestionComerciale\CommandeService;
use App\Service\GestionComerciale\EmailService;
use App\Service\GestionComerciale\ModeExpeditionService;
use App\Service\GestionComerciale\NumerotationDocumentService;
use App\Service\Taxes\TaxeService;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Container;
use App\Entity\FO\Societe;
use App\Entity\Traductions\Traduction;
use App\Entity\MarketPlace\CompteMarketPlace;
use App\Entity\MarketPlace\ArticleMarketPlace;
use App\Entity\MarketPlace\ArticleMarketPlaceImage;
use App\Entity\Articles\Article;
use App\Entity\MarketPlace\HistoriqueArticleMarketPlace;
use App\Entity\GestionComerciale\Commande;
use App\Entity\MarketPlace\ErreurPublicationArticleMarketPlace;
use App\Entity\GestionComerciale\Acompte;
//require __DIR__.'/../../../../web/ebay-api/vendor/autoload.php';
//require __DIR__."/../../../../web/ebay-api/order/XML_Serializer-0.21.0/XML/Serializer.php";
/**
* The namespaces provided by the SDK.
*/
use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use \DTS\eBaySDK\Trading\Enums;
use \DTS\eBaySDK\Product\Services as ProductService;
use \DTS\eBaySDK\Product\Types as ProductTypes;
use \DTS\eBaySDK\Product\Enums as ProductEnums;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
class EbayService
{
private $em;
private $filters;
private $config;
private $siteId;
//private $service;
//private $compteMarketPlace;
private NumerotationDocumentService $numerotationDocumentService;
private ArticleMarketPlaceService $articleMarketPlaceService;
private ClientService $clientService;
private CommandeService $commandeService;
private AcompteService $acompteService;
private TaxeService $taxeService;
private EmailService $emailService;
private MarketPlaceService $marketPlaceService;
private ModeExpeditionService $modeExpeditionService;
private DeviseService $deviseService;
public function __construct(EntityManagerInterface $em, NumerotationDocumentService $numerotationDocumentService, ArticleMarketPlaceService $articleMarketPlaceService,
ClientService $clientService, CommandeService $commandeService, AcompteService $acompteService, TaxeService $taxeService,
EmailService $emailService, MarketPlaceService $marketPlaceService, ModeExpeditionService $modeExpeditionService, DeviseService $deviseService
) {
$this->em = $em;
$this->siteId = Constants\SiteIds::FR;
/*
$this->compteMarketPlace = $em->getRepository(CompteMarketPlace::class)->find(11);
/*
ebay_client_id: CazinSAR-Test-PRD-572546526-9ea7c340
ebay_client_id_dev: ID4a96ec78-dfae-45f5-b190-f410f01a8607
ebay_client_secret: PRD-72546526c41c-714f-4efc-b412-1881
//$this->config = require __DIR__.'/../../../../web/ebay-api/configuration.php';
if(is_object($this->compteMarketPlace)){
$this->service = new Services\TradingService([
//'authorization' => $this->getAuthToken(),
'credentials' => array(
'devId' => $this->compteMarketPlace->getDevID(),
'appId' => $this->compteMarketPlace->getIdentifiant(),
'certId' => $this->compteMarketPlace->getSecret(),
),
'sandbox' => false,
'siteId' => $this->siteId
]);
}
*/
//$this->authToken = $this->config['production']['authToken'];
$this->numerotationDocumentService = $numerotationDocumentService;
$this->articleMarketPlaceService = $articleMarketPlaceService;
$this->clientService = $clientService;
$this->commandeService = $commandeService;
$this->acompteService = $acompteService;
$this->taxeService = $taxeService;
$this->emailService = $emailService;
$this->marketPlaceService = $marketPlaceService;
$this->modeExpeditionService = $modeExpeditionService;
$this->deviseService = $deviseService;
}
public function getTradingService($compteMarketPlace, $output = '')
{
$service = '';
if (is_object($compteMarketPlace)) {
$service = new Services\TradingService([
'credentials' => [
'devId' => $compteMarketPlace->getDevID(),
'appId' => $compteMarketPlace->getIdentifiant(),
'certId' => $compteMarketPlace->getSecret(),
],
'sandbox' => false,
'siteId' => $this->siteId,
]);
}
return $service;
}
public function getProductService($compteMarketPlace)
{
$service = '';
if (is_object($compteMarketPlace)) {
$service = new ProductService\ProductService([
'credentials' => [
'devId' => $compteMarketPlace->getDevID(),
'appId' => $compteMarketPlace->getIdentifiant(),
'certId' => $compteMarketPlace->getSecret(),
],
'globalId' => Constants\GlobalIds::MOTORS,
//'globalId' => Constants\GlobalIds::FR
'sandbox' => false,
'siteId' => $this->siteId,
]);
}
return $service;
}
public function getAuthToken($compteMarketPlace, $output = '')
{
if (is_object($compteMarketPlace)) {
$this->em->refresh($compteMarketPlace);
$dateValiditeAuthToken = $compteMarketPlace->getDateValiditeAuthToken();
$dateValiditeAuthToken->modify('- 5 minutes');
$authToken = $compteMarketPlace->getAuthToken();
if ($dateValiditeAuthToken > (new \Datetime)) {
if (is_object($output)) {
$output->writeln('Auth token en cours de validité');
}
return $authToken;
}
//verifier la validite
//$authToken = 'frrrrr';
/*
$url = 'https://api.ebay.com/buy/browse/v1/item/get_item_by_legacy_id?';
$url .= 'legacy_item_id=000000';
//$url = 'https://api.ebay.com/buy/browse/v1/item/V1|'.$itemId.'|0?';
//$url .= 'legacy_item_id=string&';
//$url .= 'legacy_variation_id=string&';
//$url .= 'legacy_variation_sku=string&';
$url .= 'fieldgroups=PRODUCT';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer '.$authToken,
'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
));
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
//print_r($retour);
$retour = json_decode($retour);
if(is_object($output)) print_r($retour);
if(is_object($retour) && !empty($retour->errors) && $retour->errors[0]->errorId == '1001'){
//pb Invalid access token
if(is_object($output)) $output->writeln('Invalid access token');
} else {
return $authToken;
}
*/
//return '';
/*
if(!empty($authToken) && is_object($dateValiditeAuthToken) && $dateValiditeAuthToken > (new \Datetime)){
return $authToken;
}
*/
/*
if($this->container->getParameter('ebay_prod')){
$url = 'https://api.ebay.com/identity/v1/oauth2/token';
$ebay_client_id = $this->container->getParameter('ebay_client_id');
$ebay_client_secret = $this->container->getParameter('ebay_client_secret');
} else {
$url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token';
$ebay_client_id = $this->container->getParameter('ebay_client_id_dev');
$ebay_client_secret = $this->container->getParameter('ebay_client_secret');
}
*/
if (is_object($output)) {
$output->writeln('Début renouvellement Auth');
}
$url = 'https://api.ebay.com/identity/v1/oauth2/token';
$ebay_client_id = $compteMarketPlace->getIdentifiant();
$ebay_client_secret = $compteMarketPlace->getSecret();
//var_dump($url);
//var_dump($ebay_client_id);
//var_dump($ebay_client_secret);
$authorization = base64_encode($ebay_client_id.':'.$ebay_client_secret);
$scopes = [
'https://api.ebay.com/oauth/api_scope',// View public data from eBay
//'https://api.ebay.com/oauth/api_scope/sell.marketing',// View and manage your eBay marketing activities, such as ad campaigns and listing promotions
//'https://api.ebay.com/oauth/api_scope/sell.inventory',// View and manage your inventory and offers
//'https://api.ebay.com/oauth/api_scope/sell.account',// View and manage your account settings
//'https://api.ebay.com/oauth/api_scope/sell.onboarding',// Share your merchant profile data with eBay
//'https://api.ebay.com/oauth/api_scope/sell.fulfillment',//
];
$scopes = [
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
];
$scope = urlencode(implode(' ', $scopes));
$scope = implode(' ', $scopes);
/*
$post_data = array(
'grant_type' => 'client_credentials',
'scope' => $scope
);
var_dump($scope);
*/
$post_data = [
'grant_type' => 'refresh_token',
'refresh_token' => $compteMarketPlace->getRefreshToken(),
'scope' => $scope,
];
//var_dump(http_build_query($post_data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic '.$authorization,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
//var_dump($retour);
$retour = json_decode($retour, true);
$err = curl_error($ch);
curl_close($ch);
//var_dump($err);
//if(is_object($output)) print_r($retour);
if (is_object($output)) {
$output->writeln('Fin renouvellement Auth');
}
if ( ! empty($retour['access_token'])) {
//echo $retour['access_token'];
$date = new \Datetime();
$date->modify('+ '.floatval($retour['expires_in']).'seconds');
$compteMarketPlace->setDateValiditeAuthToken($date);
$compteMarketPlace->setAuthToken($retour['access_token']);
$this->em->persist($compteMarketPlace);
$this->em->flush();
return $retour['access_token'];
}
}
return '';
}
public function getOrders2($compteMarketPlace, $hours = 15, $output = '', $donnee, $count = 0)
{
$repo_compte_market_place = $this->em->getRepository(CompteMarketPlace::class);
$compteMarketPlaceId = $compteMarketPlace->getId();
//https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/methods/getOrders
/*
GET https://api.ebay.com/sell/fulfillment/v1/order?
orderIds=string&
filter=FilterField&
limit=string&
offset=string&
fieldGroups=string
*/
//'224358007693-2533745807012';//RU
//'124232724894-2390972902002';//FR
$date_debut = new \DateTime('UTC');
//22-07096-37205
date_modify($date_debut, '- '.$hours.' hours');
$compteur_boucle_pagination = 0;
$continuer_boucle_pagination = true;
$parameters = ''
//.'orderIds=27-07599-22085'
//.'orderIds=07-07812-51390'
.'&filter='.rawurlencode('lastmodifieddate:['.$date_debut->format('Y-m-d\TH:i:s\.000\Z').'..]')
//.'&limit=500'
.'&limit=20'
//.'&offset=string'
//.'&fieldGroups=TAX_BREAKDOWN'
;
//$parameters = 'orderIds=21-07691-36968';
//$parameters = 'orderIds=23-07692-87805';
$url = 'https://api.ebay.com/sell/fulfillment/v1/order?'.$parameters;
while ($continuer_boucle_pagination) {
//$continuer_boucle_pagination = false;
$compteur_boucle_pagination++;
if (is_object($output)) {
$output->writeln('url : '.$url);
}
//return;
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer '.$authToken,
'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
// $directory = __DIR__."/../../../../web/ebay-api/ORDERS/EXPORT/".date("Y/m/d");
$file = $directory."/export_orders_ebay_".$compteMarketPlace->getId()."_".date("dmY")."-".$compteur_boucle_pagination.".json";
$dirname = dirname($file);
if ( ! is_dir($dirname)) {
mkdir($dirname, 0755, true);
}
$fp = fopen($file, 'w') or die("Erreur d'écriture du fichier");
fwrite($fp, $retour);
fclose($fp);
//var_dump($retour);
$retour = json_decode($retour, true);
//var_dump($retour);
$err = curl_error($ch);
curl_close($ch);
//$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";
$json = file_get_contents($file);
$retour = json_decode($json, true);
if (is_object($output)) {
$output->writeln("TEST ".$file);
}
//exit;
/*
if(empty($retour['total']) && $compteur_boucle_pagination == 1){
//il faut remonter à la dernière commande
$hours = 24;
$count++;
if($count < 2) $this->getOrders2($compteMarketPlace, $hours, $output, $donnee, $count);
}
*/
if ( ! empty($retour['total']) && ! empty($retour['orders'])) {
if (is_object($output)) {
$output->writeln('Nb de commandes : '.count($retour['orders']));
}
$compteur_boucle = 1;
foreach ($retour['orders'] as $order) {
if (is_object($output)) {
$output->writeln('Commande '.$compteur_boucle.'/'.count($retour['orders']));
}
//if($compteur_boucle == 1) print_r($order);
$compteur_boucle++;
try {
//$this->traiterCommande2($compteMarketPlace, $order, $output, $donnee);
//if($order["orderId"] == "10-07210-53488" or 1==1) {
$output->writeln($order["orderId"]);
//if($compteur_boucle == 2) print_r($order);
//rechercher si la commande a été saisie manuellement
$commande = $this->em->getRepository(Commande::class)->findOneBy(['referenceClient' => $order["orderId"]]);
if (is_object($commande)) {
} elseif ($order["orderId"] == "06-07343-90360" or 1 == 1) {//
//print_r($order);
$this->traiterCommande2($compteMarketPlace, $order, $output, $donnee);
if ($compteur_boucle % 10 == 0) {
$this->em->clear();
$compteMarketPlace = $repo_compte_market_place->find($compteMarketPlaceId);
}
//echo "fintest";
//exit;
}
} catch (\Exception $e) {
//var_dump($order);
$output->writeln('Exception');
$output->writeln($e->getMessage());
//envoyer un email
$this->emailService->envoyerEmailErrorCron("Erreur dans le traitement de la commande ebay ".$order["orderId"].' '.$e->getMessage());
}
//break;
if ($order["orderId"] == "18-07178-25982") {
//echo "STOPSTOP";
//exit;
}
}
if ( ! empty($retour['next'])) {
$url = $retour['next'];
} else {
$continuer_boucle_pagination = false;
}
} else {
if (is_object($output)) {
$output->writeln('Aucune commande!');
}
$continuer_boucle_pagination = false;
//erreurs?
}
}
}
public function getApiAccessRules($compteMarketPlace, $output = '')
{
//$authToken = $this->getAuthToken();
$authToken = $this->getAuthToken($compteMarketPlace, $output);
if (empty($authToken)) {
return $authToken;
}
$request = new Types\GetApiAccessRulesRequestType();
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $authToken;
$response = @$this->getTradingService($compteMarketPlace)->getApiAccessRules($request);
/*
$request = new Types\GeteBayOfficialTimeRequestType();
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $authToken;
$request->RequesterCredentials->authorization = $authToken;
$response = $this->service->geteBayOfficialTime($request);
*/
return $response;
}
public function getMyeBaySellingRequestType($compteMarketPlace, $output = '')
{
if (is_object($output)) {
$output->writeln('getMyeBaySellingRequestType');
}
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$request = new Types\GetMyeBaySellingRequestType();
/**
* An user token is required when using the Trading service.
*/
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $authToken;
/**
* Request that eBay returns the list of actively selling items.
* We want 10 items per page and they should be sorted in descending order by the current price.
*/
$request->ActiveList = new Types\ItemListCustomizationType();
$request->ActiveList->Include = true;
$request->ActiveList->Pagination = new Types\PaginationType();
$request->ActiveList->Pagination->EntriesPerPage = 10;
//$request->ActiveList->DurationInDays = 1;
//$request->ActiveList->Sort = Enums\ItemSortTypeCodeType::C_CURRENT_PRICE_DESCENDING;
$request->ActiveList->Sort = Enums\ItemSortTypeCodeType::C_START_TIME_DESCENDING;
$pageNum = 1;
$s = "ItemID;Title;currencyID;CurrentPriceId;CurrentPriceValue;PictureDetails";
$s = "ItemID;Title;CurrentPriceId;CurrentPriceValue;Quantity;PictureDetails;SKU;StartTime;EAN;NbVendus";
$string_csv = $s;
$string_csv .= "\n";
//$string_csv .= chr(13);
//echo $s;
$directory = "";
// $file = __DIR__."/../../../../web/ebay-api/PRODUCTS/".date("Y")."/".date("m")."/".date("d")."/export_ebay_".$compteMarketPlace->getId()."_".date("dmY").".csv";
$dirname = dirname($file);
if ( ! is_dir($dirname)) {
mkdir($dirname, 0755, true);
}
do {
$request->ActiveList->Pagination->PageNumber = $pageNum;
$response = @$this->getTradingService($compteMarketPlace)->getMyeBaySelling($request);
if (isset($response->Errors)) {
foreach ($response->Errors as $error) {
/*
printf(
"%s: %s\n%s\n\n",
$error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning',
$error->ShortMessage,
$error->LongMessage
);
*/
}
}
$cpt = 0;
//print_r($response);
//break;
//echo "<div>atp ".$response->ActiveList->PaginationResult->TotalNumberOfPages."</div>";
//echo "<div>pageNum ".$pageNum."</div>";
if ($response->Ack !== 'Failure' && isset($response->ActiveList)) {
foreach ($response->ActiveList->ItemArray->Item as $item) {
/*printf(
"(%s) %s: %s %.2f\n",
$item->ItemID,
$item->Title,
$item->SellingStatus->CurrentPrice->currencyID,
$item->SellingStatus->CurrentPrice->value
);
*/
if ($cpt == 0) {
/*foreach($item as $k=>$v) {
print_r($k);
print_r($v);
}
*/
//echo "<div>------------------------------------------------</div>";
//print_r($item->PictureDetails);
//exit;
}
$cpt++;
//print_r($item);
//exit;
$s = trim($item->ItemID).";"
.trim($item->Title).";"
.trim($item->SellingStatus->CurrentPrice->currencyID).";"
.trim($item->SellingStatus->CurrentPrice->value).";"
//.$item->Seller->UserID.";"
.trim($item->Quantity).";"
.trim(stripslashes($item->PictureDetails->GalleryURL)).";"
.trim($item->SKU).";"
.trim($item->ListingDetails->StartTime->format("dmY")).";";
if ( ! empty($item->ProductListingDetails) && is_object($item->ProductListingDetails)) {
$s .= trim($item->ProductListingDetails->EAN).";";
} else {
$s .= ";";
}
$s .= trim($item->SellingStatus->QuantitySold).";";
//if(is_object($output)) $output->writeln('getMyeBaySellingRequestType t4');
if (is_object($output)) {
$output->writeln($s);
}
$string_csv .= utf8_decode($s);
$string_csv .= "\n";
//$string_csv .= chr(13);
// echo "<div>".utf8_decode($s)."</div>";
//exit;
}
}
$pageNum += 1;
} while (isset($response->ActiveList));//&& $pageNum <= 1
$fp = fopen($file, 'w') or die("Erreur d'écriture du fichier");
fwrite($fp, $string_csv);
fclose($fp);
}
public function getItem($articleMarketPlace, $detailLevel = 'ReturnAll', $authToken = '', $count = 0)
{
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
if (empty($authToken)) {
$authToken = $this->getAuthToken($compteMarketPlace);
}
//$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$request = new Types\GetItemRequestType();
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $authToken;
$request->ItemID = $articleMarketPlace->getIdImport();//$item->ItemID;
$request->DetailLevel[] = $detailLevel;
$request->IncludeItemCompatibilityList = true;
try {
$response = @$this->getTradingService($compteMarketPlace)->getItem($request);
} catch (\Exception $e) {
$count++;
sleep(1);
$response = $this->getItem($articleMarketPlace, $detailLevel, '', $count);
}
if (isset($response->Errors)) {
foreach ($response->Errors as $error) {
if (in_array($error->ErrorCode, [518, '518'])) {
return $response;
}
}
}
if (isset($response->Errors) && $count < 3) {
$count++;
sleep(1);
$response = $this->getItem($articleMarketPlace, $detailLevel, '', $count);
}
if (isset($response->Errors)) {
$date = new \Datetime();
$dateNonRenouvellable = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"))->modify('- 90 days');
$endTime = $articleMarketPlace->getEndTime();
foreach ($response->Errors as $error) {
if (in_array($error->ErrorCode, [17, '17']) && is_object($endTime) && $endTime < $dateNonRenouvellable) {
//$output->writeln('Annonce non renouvelable');
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$tableau_donnee["statut_article_market_place_id"] = 2;//publié
$tableau_donnee["statut"] = 0;
$tableau_donnee["visible"] = 0;
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlace->getId()]);
$this->supprimerErreur($articleMarketPlace->getIdImport());
return $response;
}
}
$this->creerErreur($response, $articleMarketPlace->getIdImport(), '', 'MarketPlaceEnvoiArticle getItem');
} else {
$this->supprimerErreur($articleMarketPlace->getIdImport());
}
return $response;
}
public function getItem2($compteMarketPlace, $itemId, $output = '')
{
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$url = 'https://api.ebay.com/buy/browse/v1/item/V1|'.$itemId.'|0?';
//$url .= '&fieldgroups=PRODUCT';
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer '.$authToken,
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
return json_decode($retour);
}
public function getItemByLegacyId($compteMarketPlace, $itemId, $output = '')
{
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
#https://developer.ebay.com/api-docs/buy/browse/resources/item/methods/getItemByLegacyId
$url = 'https://api.ebay.com/buy/browse/v1/item/get_item_by_legacy_id?';
$url .= 'legacy_item_id='.$itemId;
//$url = 'https://api.ebay.com/buy/browse/v1/item/V1|'.$itemId.'|0?';
//$url .= 'legacy_item_id=string&';
//$url .= 'legacy_variation_id=string&';
//$url .= '&legacy_variation_sku=KC01104';
$url .= '&fieldgroups=PRODUCT';
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer '.$authToken,
'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
return json_decode($retour);
}
public function getProductCompatibilities2($compteMarketPlace, $sku, $output = '')
{
//https://developer.ebay.com/devzone/xml/docs/reference/ebay/types/ItemCompatibilityListType.html
//https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/product_compatibility/methods/getProductCompatibility
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
#https://developer.ebay.com/api-docs/buy/browse/resources/item/methods/getItemByLegacyId
$url = 'https://api.ebay.com/sell/inventory/v1/inventory_item/A'.$sku.'0/product_compatibility';
$itemId = '274265966060';
$itemId = $sku;
$url = 'https://api.ebay.com/buy/browse/v1/item/'.$itemId.'/check_compatibility';
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
'Content-Language: fr-FR',
//'Accept-Language: fr-FR',
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
return json_decode($retour);
}
public function getProductCompatibilities($compteMarketPlace, $ePID, $output = '')
{
$authToken = $this->getAuthToken($compteMarketPlace);
//if(empty($authToken)) return $authToken;
$request = new ProductTypes\GetProductCompatibilitiesRequest();
//$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
//$request->RequesterCredentials->eBayAuthToken = $authToken;
//$request->ItemID = $itemId;//$item->ItemID;
$request->dataset = ['DisplayableProductDetails'];
/**
* Assign the ePID.
*/
$request->productIdentifier = new ProductTypes\ProductIdentifier();
//$request->productIdentifier->ePID = '193042315';
$request->productIdentifier->ePID = $ePID;
//$request->productIdentifier->ePID = '228436781';
//$request->productIdentifier->EAN = $ean;
//$request->productIdentifier->EAN = '3306430033692';
//$request->productIdentifier->SKU = 'SC22141';
//$request->productIdentifier->productId = '4C67E8DA7C7042FBBA03C1313F47A5A4';
//$request->productIdentifier->UPC = '4C67E8DA7C7042FBBA03C1313F47A5A4';
/**
* Limit the results to 10 items per page.
*/
$request->paginationInput = new ProductTypes\PaginationInput();
$request->paginationInput->entriesPerPage = 10;
$pageNum = 1;
$retour = [];
do {
$request->paginationInput->pageNumber = $pageNum;
/**
* Send the request.
*/
$response = $this->getProductService($compteMarketPlace)->getProductCompatibilities($request);
print_r($response);
/**
* Output the result of calling the service operation.
*/
if (is_object($output)) {
$output->writeln("==================Results for page ".$pageNum."==================");
}
if (isset($response->errorMessage)) {
foreach ($response->errorMessage->error as $error) {
printf(
"%s: %s\n\n",
$error->severity === ProductEnums\ErrorSeverity::C_ERROR ? 'Error' : 'Warning',
$error->message
);
}
}
$countTmp = 0;
if ($response->ack !== 'Failure') {
if ( ! empty($response->compatibilityDetails)) {
foreach ($response->compatibilityDetails as $details) {
if ($countTmp == 0) {
print_r($details);
}
$countTmp++;
//if(is_object($output)) $output->writeln('==================Compatibility==================');
$tmp = [];
foreach ($details->productDetails as $detail) {
//printf("\n%s :", $detail->propertyName);
//print_r($detail);
foreach ($detail->value as $value) {
//print_r($detail->propertyName);
$tmp[$detail->propertyName] = isset($value->number) ? $value->number->value : '';
$tmp[$detail->propertyName] .= isset($value->text) ? ' '.$value->text->value : '';
$tmp[$detail->propertyName] .= isset($value->URL) ? ' '.$value->URL->value : '';
$tmp[$detail->propertyName] = trim($tmp[$detail->propertyName]);
/*
printf(
"%s %s %s ",
isset($value->number) ? $value->number->value : '',
isset($value->text) ? $value->text->value : '',
isset($value->URL) ? $value->URL->value : ''
);
*/
}
}
$retour[] = $tmp;
}
}
}
$pageNum += 1;
} while (isset($response->compatibilityDetails) && $pageNum <= $response->paginationOutput->totalPages);
return $retour;
}
public function getOrders($compteMarketPlace, $hours = 15, $output = '', $donnee)
{
$authToken = $this->getAuthToken($compteMarketPlace);
//if(is_object($output)) $output->writeln($authToken);
if (empty($authToken)) {
return $authToken;
}
$request = new Types\GetMyeBaySellingRequestType();
$date_debut = new \DateTime();
date_modify($date_debut, '- '.$hours.' hours');
$date_fin = new \DateTime();
$args = [
//"OrderStatus" => "Completed",
"OrderStatus" => "All",
//"SortingOrder" => "Descending",
//"OrderRole" => "Seller",
"ModTimeFrom" => $date_debut,
"ModTimeTo" => $date_fin,
//"siteId" => $this->siteId,
//"CreateTimeFrom" => $date_debut,
//"CreateTimeTo" => $date_fin,
];
//$jSON = "";
//$args = array('OrderIDArray'=>array(224358007693));
$orders = [];
$getOrders = new Types\GetOrdersRequestType($args);
$getOrders->RequesterCredentials = new Types\CustomSecurityHeaderType();
$getOrders->RequesterCredentials->eBayAuthToken = $authToken;
$getOrders->IncludeFinalValueFee = true;
$getOrders->Pagination = new Types\PaginationType();
$getOrders->Pagination->EntriesPerPage = 10;
$getOrders->DetailLevel[] = 'ReturnAll';
$getOrders->OrderIDArray = new Types\OrderIDArrayType();
$getOrders->OrderIDArray->OrderID[] = '224358007693-2533745807012';//RU
$getOrders->OrderIDArray->OrderID[] = '124232724894-2390972902002';//FR
$pageNum = 1;
$getOrders->Pagination->PageNumber = $pageNum;
// $directory = __DIR__."/../../../../web/ebay-api/ORDERS/EXPORT/".date("Y/m/d");
$file = $directory."/export_orders_ebay_".$compteMarketPlace->getId()."_".date("dmY").".xml";
$dirname = dirname($file);
if ( ! is_dir($dirname)) {
mkdir($dirname, 0755, true);
}
$fp = fopen($file, 'w') or die("Erreur d'écriture du fichier");
fwrite($fp, '<?xml version="1.0" encoding="UTF-8"?>');
fwrite($fp, '<Orders>');
$nbLignes = 0;
do {
$getOrders->Pagination->PageNumber = $pageNum;
//var_dump($getOrders);
$response = @$this->getTradingService($compteMarketPlace, $output)->getOrders($getOrders);
foreach ($response->OrderArray->Order as $order) {
$orders[] = $order;
//$this->traiterCommande($compteMarketPlace, $order, $output);
//if(is_object($output) && $pageNum == 1) print_r($order);
$nbLignes++;
$output->writeln('Enregistrement line '.$nbLignes);
fwrite($fp, $this->json_to_xml($order));
}
//printf($response->OrderArray);break;
$pageNum += 1;
} while (isset($response->HasMoreOrders) && $response->HasMoreOrders == true && $pageNum <= 2);
fwrite($fp, '</Orders>');
fclose($fp);
$nbLignes = 0;
if (count($orders)) {
$compteur_boucle = 0;
foreach ($orders as $order) {
$nbLignes++;
$output->writeln('Traitement line '.$nbLignes);
print_r($order);
$this->traiterCommande($compteMarketPlace, $order, $output, $donnee);
}
}
$this->em->clear();
//return $orders;
//return $response;
}
// TODO TEST
private function json_to_xml($json)
{
$normalizers = [new ObjectNormalizer()];
$encoders = [new XmlEncoder()];
$serializer = new Serializer($normalizers, $encoders);
$obj = json_decode($json);
$xml = $serializer->serialize($obj, 'xml');
if ( ! empty($xml)) {
$xml = str_replace("<stdClass>", "<Order>", $xml);
$xml = str_replace("</stdClass>", "</Order>", $xml);
return $xml;
} else {
return null;
}
}
private function traiterCommande($compte, $order, $output, $donnee)
{
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$repo_commande = $this->em->getRepository(Commande::class);
$repo_article_commande = $this->em->getRepository(ArticleCommande::class);
$repo_type_document_commercial = $this->em->getRepository(TypeDocumentCommercial::class);
$repo_article_market_place = $this->em->getRepository(ArticleMarketPlace::class);
$output->writeln('ORDER ID '.$order->OrderID);
$SellingManagerSalesRecordNumber = trim($order->ShippingDetails->SellingManagerSalesRecordNumber);
$OrderID = trim($order->OrderID);
$OrderStatus = trim($order->OrderStatus);
$AdjustmentAmount_value = trim($order->AdjustmentAmount->value);
$AdjustmentAmount_currencyID = trim($order->AdjustmentAmount->currencyID);
$AmountPaid_value = trim($order->AmountPaid->value);
$AmountPaid_currencyID = trim($order->AmountPaid->currencyID);
$AmountSaved_value = trim($order->AmountSaved->value);
$AmountSaved_currencyID = trim($order->AmountSaved->currencyID);
$eBayPaymentStatus = trim($order->CheckoutStatus->eBayPaymentStatus);
$LastModifiedTime = $order->CheckoutStatus->LastModifiedTime;
$PaymentMethod = trim($order->CheckoutStatus->PaymentMethod);
$Status = trim($order->CheckoutStatus->Status);
$IntegratedMerchantCreditCardEnabled = trim($order->CheckoutStatus->IntegratedMerchantCreditCardEnabled);
$PaymentInstrument = trim($order->CheckoutStatus->PaymentInstrument);
$SalesTaxPercent = trim($order->ShippingDetails->SalesTax->SalesTaxPercent);
$SalesTaxState = trim($order->ShippingDetails->SalesTax->SalesTaxState);
$ShippingIncludedInTax = trim($order->ShippingDetails->SalesTax->ShippingIncludedInTax);
//print_r($order->TransactionArray->Transaction);
/*
$ShippingService = trim($order->ShippingDetails->ShippingServiceOptions->ShippingService);
$ShippingServiceCost_value = trim($order->ShippingDetails->ShippingServiceOptions->ShippingServiceCost->value);
$ShippingServiceCost_currencyID = trim($order->ShippingDetails->ShippingServiceOptions->ShippingServiceCost->currencyID);
$ShippingServicePriority = trim($order->ShippingDetails->ShippingServiceOptions->ShippingServicePriority);
$ExpeditedService = trim($order->ShippingDetails->ShippingServiceOptions->ExpeditedService);
$ShippingTimeMin = trim($order->ShippingDetails->ShippingServiceOptions->ShippingTimeMin);
$ShippingTimeMax = trim($order->ShippingDetails->ShippingServiceOptions->ShippingTimeMax);
*/
$CreatingUserRole = trim($order->CreatingUserRole);
$CreatedTime = $order->CreatedTime;
/*
$PaymentMethods ="";
if(isset($order->PaymentMethods)) $PaymentMethods = trim($order->PaymentMethods);
*/
$SellerEmail = trim($order->SellerEmail);
/*
$ShippingAddress_Name = trim($order->ShippingAddress->Name);
$ShippingAddress_Street1 = trim($order->ShippingAddress->Street1);
$ShippingAddress_Street2 = trim($order->ShippingAddress->Street2);
$ShippingAddress_CityName = trim($order->ShippingAddress->CityName);
$ShippingAddress_StateOrProvince = trim($order->ShippingAddress->StateOrProvince);
$ShippingAddress_Country = trim($order->ShippingAddress->Country);
$ShippingAddress_CountryName = trim($order->ShippingAddress->CountryName);
$ShippingAddress_Phone = trim($order->ShippingAddress->Phone);
$ShippingAddress_PostalCode = trim($order->ShippingAddress->PostalCode);
$ShippingAddress_AddressID = trim($order->ShippingAddress->AddressID);
$ShippingAddress_AddressOwner = trim($order->ShippingAddress->AddressOwner);
$ShippingAddress_ExternalAddressID = trim($order->ShippingAddress->ExternalAddressID);
*/
$ShippingServiceSelected = trim($order->ShippingServiceSelected->ShippingService);
$ShippingServiceCost_value = trim($order->ShippingServiceSelected->ShippingServiceCost->value);
$ShippingServiceCost_currencyID = trim($order->ShippingServiceSelected->ShippingServiceCost->currencyID);
$Subtotal_value = trim($order->Subtotal->value);
$Subtotal_currencyID = trim($order->Subtotal->currencyID);
$Total_value = trim($order->Total->value);
$Total_currencyID = trim($order->Total->currencyID);
//$Buyer_Email = trim($order->Total->currencyID);
$BuyerCheckoutMessage = trim($order->BuyerCheckoutMessage);
//$output->writeln('ETAPE 2 '.$order->OrderID);
$Buyer_Email = '';
$Buyer_UserFirstName = '';
$Buyer_UserLastName = '';
if (isset($order->TransactionArray->Transaction) && count($order->TransactionArray->Transaction)) {
foreach ($order->TransactionArray->Transaction as $transaction) {
$Buyer_Email = $transaction->Buyer->Email;
$Buyer_UserFirstName = $transaction->Buyer->UserFirstName;
$Buyer_UserLastName = $transaction->Buyer->UserLastName;
}
}
//$BuyerUserID = trim($order->BuyerUserID);
$PaidTime = $order->PaidTime;
$ShippedTime = $order->ShippedTime;
$IntegratedMerchantCreditCardEnabled = trim($order->IntegratedMerchantCreditCardEnabled);
$PaymentHoldStatus = trim($order->PaymentHoldStatus);
$ExtendedOrderID = trim($order->ExtendedOrderID);
$tab_client = [
'idImport' => 'cpt'.$compte->getId().'_'.trim($order->BuyerUserID),
'email' => trim($order->BuyerUserID),
'nom' => $Buyer_UserLastName,
'prenom' => $Buyer_UserFirstName,
'pays' => trim($order->ShippingAddress->CountryName),
'pays_code_iso' => trim($order->ShippingAddress->Country),
'compteMarketPlace' => $compte,
];
$client = $this->clientService->getClient($tab_client);
//getClientMarketPlace
//pays
//compteMarketPlace
//si non trouve verifier si pays ue ou reste du monde et chercher à nouveau
$tab_shipping_address = [
'livraisonDefaut' => true,
'societe' => trim($order->ShippingAddress->Name),
'rue' => trim($order->ShippingAddress->Street1),
'complement' => trim($order->ShippingAddress->Street2),
'ville' => trim($order->ShippingAddress->CityName),
'pays' => trim($order->ShippingAddress->CountryName),
'pays_code_iso' => trim($order->ShippingAddress->Country),
'idImport' => 'cpt'.$compte->getId().'_'.trim($order->ShippingAddress->AddressID),
'telephone' => trim($order->ShippingAddress->Phone),
'codePostal' => trim($order->ShippingAddress->PostalCode),
];
if (is_object($client)) {
$tab_shipping_address['client'] = $client;
}
//$shipping_address = $service_adresse->getAdresse($tab_shipping_address, $output);
//lien commande / marketplace
$query = $repo_commande->createQueryBuilder('p')
->select(
'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'
)//p.commentaireExpedition as commentaire_expedition,p.sifam
->where(
'(p.archive is null or p.archive = :archive) and p.compteMarketPlace = :compteMarketPlace AND p.idImport = :idImport AND tp.id = :typeDocumentCommercial'
)
->setParameters(['archive' => '0', 'compteMarketPlace' => $compte->getId(), "idImport" => $OrderID, 'typeDocumentCommercial' => TypeDocumentCommercial::COMMANDE])
->setMaxResults(1)
//->join('p.typeDocumentCommercial', 'tp')
->join('p.statutCommande', 'sc')
->leftJoin('p.statutCommandeMarketPlace', 'scm')
->orderBy('p.id', 'ASC');
$commande_bdd = $query->getQuery()->getOneOrNullResult();
$tableau_donnee = [];
//$dateCommande = new \Datetime($CreatedTime);
//$tableau_donnee["reference"]=$purchaseid;
$tableau_donnee["reference_market_place"] = $SellingManagerSalesRecordNumber;
if (is_object($client)) {
$tableau_donnee["client_id"] = $client->getId();
} else {
$tableau_donnee["client_id"] = null;
}
$tableau_donnee["id_import"] = $OrderID;
$tableau_donnee["compte_market_place_id"] = $compte->getId();
$tableau_donnee["dateMaj"] = (new \Datetime)->format("Y-m-d H:i:s");
//$tableau_donnee["date"] = $dateCommande->format('Y-m-d H:i:s');
$tableau_donnee["date"] = $CreatedTime->format('Y-m-d H:i:s');
$tableau_donnee["type_document_commercial_id"] = TypeDocumentCommercial::COMMANDE;
$tableau_donnee["archive"] = 0;
$tableau_donnee["avecTaxe"] = 1;
$tableau_donnee["statut_paiement_id"] = 1;
$tableau_donnee["etat_commande_id"] = 1;
$tableau_donnee["bascule_comptabilite"] = 0;
$tableau_donnee["visible"] = "1";
$tableau_donnee["modifiable"] = "0";
$tableau_donnee["temps_passe"] = "0";
$tableau_donnee["temps_facture"] = "0";
$tableau_donnee["attente_facturation"] = "0";
$tableau_donnee["origine_saisie"] = "commande";
$tableau_donnee["statut_commande_id"] = "1";
$tableau_donnee["total_frais_port"] = $ShippingServiceCost_value;
$tableau_donnee["total_frais_port_ttc"] = $ShippingServiceCost_value;
$tableau_donnee["total_tva_frais_port"] = 0;
//Subtotal_value
$tableau_donnee["total_ttc"] = $Total_value;
//$tableau_donnee["total"] = $Total_value*(100/(100+floatval($SalesTaxPercent)));
$tableau_donnee["total"] = $Subtotal_value;
//$Total_currencyID = trim($order->Total->currencyID);
$tableau_donnee["devise_id"] = $this->deviseService->getDevise($Total_currencyID, $output)->getId();
/*
$tableau_donnee['destinataire_livraison_texte']=$ShippingAddress_Name;
$tableau_donnee['destinataire_facturation_texte']=$ShippingAddress_Name;
$tableau_donnee['pays_livraison_texte']=$this->trouverPays($tab_adresse['pays']);;
$tableau_donnee['ville_livraison_texte']=$tab_adresse["ville"];
$tableau_donnee['code_postal_livraison_texte']=$tab_adresse["codePostal"];
$tableau_donnee['pays_facturation_texte']=$this->trouverPays($tab_adresse['pays']);;
$tableau_donnee['ville_facturation_texte']=$tab_adresse["ville"];
$tableau_donnee['code_postal_facturation_texte']=$tab_adresse["codePostal"];
*/
$tableau_donnee['commentaire'] = $BuyerCheckoutMessage;
//livraison
/*
if(is_object($shipping_address)) $tableau_donnee['adresse_livraison_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_livraison_id'] = NULL;
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;
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;
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;
*/
$tableau_donnee['adresse_livraison_id'] = null;
$tableau_donnee['ville_livraison_txt'] = trim($order->ShippingAddress->CityName);
$tableau_donnee['pays_livraison_txt'] = trim($order->ShippingAddress->CountryName);
$tableau_donnee['code_postal_livraison_txt'] = trim($order->ShippingAddress->PostalCode);
$tableau_donnee['libelle_livraison'] = trim($order->ShippingAddress->Name);
//$tableau_donnee['numero_livraison'] = '';
$tableau_donnee['rue_livraison'] = trim($order->ShippingAddress->Street1);
$tableau_donnee['complement_livraison'] = trim($order->ShippingAddress->Street2);
$tableau_donnee['code_iso_livraison'] = trim($order->ShippingAddress->Country);
$tableau_donnee['state_or_province_livraison'] = trim($order->ShippingAddress->StateOrProvince);
//$tableau_donnee['complement_livraison_2'] = ;
//facturation
/*
if(is_object($shipping_address)) $tableau_donnee['adresse_facturation_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_facturation_id'] = NULL;
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;
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;
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;
*/
$tableau_donnee['adresse_facturation_id'] = null;
$tableau_donnee['ville_facturation_txt'] = trim($order->ShippingAddress->CityName);
$tableau_donnee['pays_facturation_txt'] = trim($order->ShippingAddress->CountryName);
$tableau_donnee['code_postal_facturation_txt'] = trim($order->ShippingAddress->PostalCode);
$tableau_donnee['libelle_facturation'] = trim($order->ShippingAddress->Name);
//$tableau_donnee['numero_facturation'] = '';
$tableau_donnee['rue_facturation'] = trim($order->ShippingAddress->Street1);
$tableau_donnee['complement_facturation'] = trim($order->ShippingAddress->Street2);
$tableau_donnee['code_iso_facturation'] = trim($order->ShippingAddress->Country);
$tableau_donnee['state_or_province_facturation'] = trim($order->ShippingAddress->StateOrProvince);
//$tableau_donnee['complement_facturation_2'] = ;
//ShippingCarrierUsed
//transporteur_id
//ShipmentTrackingNumber
//numero_suivi
/*
[CheckoutStatus] => DTS\eBaySDK\Trading\Types\CheckoutStatusType Object
(
[values:DTS\eBaySDK\Types\BaseType:private] => Array
(
[eBayPaymentStatus] => NoPaymentFailure
[LastModifiedTime] => DateTime Object
(
[date] => 2021-03-19 13:47:50.000000
[timezone_type] => 2
[timezone] => Z
)
[PaymentMethod] => PayPal
[Status] => Complete
[IntegratedMerchantCreditCardEnabled] =>
[PaymentInstrument] => CreditCard
)
*/
//AmountPaid
/*
$tab_statut_commande = array();
$tab_statut_commande["reference"]=$OrderStatus;
*/
//statut de commande
//mode de reglement marketplace
if ( ! empty($PaymentMethod)) {
$mode_reglement_market_place = $this->marketPlaceService->getModeReglementMarketPlace($PaymentMethod, $compte->getMarketPlace());
if (is_object($mode_reglement_market_place)) {
$tableau_donnee['mode_reglement_market_place_id'] = $mode_reglement_market_place->getId();
if (is_object($mode_reglement_market_place->getModeReglement())) {
$tableau_donnee['mode_reglement_id'] = $mode_reglement_market_place->getModeReglement()->getId();
}
}
}
//mode d'expedition
if ( ! empty($ShippingServiceSelected)) {
$tableau_donnee['mode_expedition_id'] = $this->modeExpeditionService->getModeExpedition($ShippingServiceSelected, $ShippingServiceSelected, $compte->getMarketPlace());
}
if ( ! empty($tableau_donnee['mode_expedition_id'])) {
$mode_expedition_obj = $repo_mode_expedition->find($tableau_donnee['mode_expedition_id']);
if (is_object($mode_expedition_obj) && is_object($mode_expedition_obj->getTransporteur())) {
$tableau_donnee['transporteur_id'] = $mode_expedition_obj->getTransporteur()->getId();
}
}
//statut commande marketplace
if ( ! empty($OrderStatus)) {
$statut_commande_calcule = $this->commandeService->calculerStatutCommandeMarketPlace($compte, $OrderStatus, $commande_bdd);
$tableau_donnee['statut_commande_market_place_id'] = $statut_commande_calcule["id"];
$tableau_donnee['statut_commande_id'] = $statut_commande_calcule["action_statut_commande_id"];
if ( ! empty($statut_commande_calcule['statut_paiement_id'])) {
$tableau_donnee['statut_paiement_id'] = $statut_commande_calcule['statut_paiement_id'];
}
}
/*
if(!empty($order['order_state_reason_code'])){
$statut_paiement_calcule = $service_commande->calculerStatutPaiementMarketPlace($order['order_state_reason_code']);
$tableau_donnee['statut_paiement_id'] = $statut_paiement_calcule["statut_paiement_id"];
if(!empty($statut_paiement_calcule["statut_commande_id"])) $tableau_donnee['statut_commande_id'] = $statut_paiement_calcule["statut_commande_id"];
}
*/
/*
$mode_expedition_bdd = $this->creerModeExpedition($output,$container,$compte,$tab_expedition);
$tableau_donnee['mode_expedition_id']=$mode_expedition_bdd["id"];
$tab_reglement = array();
$tab_reglement["reference"]=$PaymentMethods;
$mode_reglement_bdd = $this->creerModeReglement($output,$container,$compte,$tab_reglement);
$tableau_donnee['modereglement_id']=$mode_reglement_bdd["id"];
if(is_object($ville_obj)) {
$tableau_donnee['ville_facturation_id']=$ville_obj->getId();
$tableau_donnee['code_postal_facturation_id']=$ville_obj->getId();
if(is_object($ville_obj->getParentId()) && is_object($ville_obj->getParentId()->getParentId()) && is_object($ville_obj->getParentId()->getParentId()->getParentId())) {
$tableau_donnee['pays_facturation_id'] = $ville_obj->getParentId()->getParentId()->getParentId()->getId();
}
}
*/
$tableau_donnee_commande = $tableau_donnee;
$nouvelle_commande_ebay = true;
//$output->writeln('ETAPE 8 '.$order->OrderID);
if ($commande_bdd['id'] == "") {
$commande_obj = new Commande();
$type_commande = TypeDocumentCommercial::COMMANDE;
$commande_obj->setTypeDocumentCommercial($type_commande);
$tableau_donnee["reference"] = $this->numerotationDocumentService->generer($commande_obj);
/*
if (array_key_exists('code_postal_livraison_texte', $tableau_donnee)) {
if( substr($tableau_donnee['code_postal_livraison_texte'],0,2) == "20")
{
$tableau_donnee['adresse_a_changer']="1";
$tableau_donnee['commentaireExpedition']="ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE";
}
}
*/
if ($donnee == "Oui") {
$conn->insert('commerciale__commande', $tableau_donnee);
}
$commande_bdd['id'] = $conn->lastInsertId();
$output->writeln('<info>TABLE COMMANDE Action : INSERT : '.$tableau_donnee["reference_market_place"].'</info>');
} else {
$nouvelle_commande_ebay = false;
$tableau_donnee["reference"] = $commande_bdd['reference'];
if ($donnee == "Oui") {
$conn->update('commerciale__commande', $tableau_donnee, ['id' => $commande_bdd['id']]);
}
$output->writeln('<info>TABLE COMMANDE Action : UPDATE : '.$tableau_donnee["reference_market_place"].' / ID : '.$commande_bdd['id'].'</info>');
}
//$output->writeln('ETAPE 9 '.$order->OrderID);
//$handle_pdf = fopen($domaine.$url_pdf, 'r');
if (isset($order->TransactionArray->Transaction)) {
foreach ($order->TransactionArray->Transaction as $item) {
$Item_ShippingDetails = trim($item->ShippingDetails->SellingManagerSalesRecordNumber);
$CreatedDate = $item->CreatedDate;
$ItemID = trim($item->Item->ItemID);
$Site = trim($item->Item->Site);
$Title = trim($item->Item->Title);
$ConditionID = trim($item->Item->ConditionID);
$ConditionDisplayName = trim($item->Item->ConditionDisplayName);
$QuantityPurchased = floatval(trim($item->QuantityPurchased));
$PaymentHoldStatus = trim($item->Status->PaymentHoldStatus);
$InquiryStatus = trim($item->Status->InquiryStatus);
$ReturnStatus = trim($item->Status->ReturnStatus);
$TransactionID = trim($item->TransactionID);
$TransactionPrice_value = floatval(trim($item->TransactionPrice->value));
$TransactionPrice_currencyID = trim($item->TransactionPrice->currencyID);
//$ProductName = trim($item->SellingManagerProductDetails->ProductName);
//$EstimatedDeliveryTimeMin = $item->ShippingServiceSelected->ShippingPackageInfo->EstimatedDeliveryTimeMin;
//$EstimatedDeliveryTimeMax = $item->ShippingServiceSelected->ShippingPackageInfo->EstimatedDeliveryTimeMax;
$FinalValueFee_value = trim($item->FinalValueFee->value);
$FinalValueFee_currencyID = trim($item->FinalValueFee->currencyID);
$TransactionSiteID = trim($item->TransactionSiteID);
$Platform = trim($item->Platform);
$TotalTaxAmount_value = trim($item->Taxes->TotalTaxAmount->value);
$TotalTaxAmount_currencyID = trim($item->Taxes->TotalTaxAmount->currencyID);
//$Imposition = trim($item->Taxes->TaxDetails->Imposition);
//$TaxDescription = trim($item->Taxes->TaxDetails->TaxDescription);
//$TaxAmount_value = trim($item->Taxes->TaxDetails->TaxAmount->value);
//$TaxAmount_currencyID = trim($item->Taxes->TaxDetails->TaxAmount->currencyID);
//$TaxOnSubtotalAmount_value = trim($item->Taxes->TaxDetails->TaxOnSubtotalAmount->value);
//$TaxOnSubtotalAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnSubtotalAmount->currencyID);
/*
$TaxOnShippingAmount_value = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->value);
$TaxOnShippingAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->currencyID);
$TaxOnShippingAmount_value = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->value);
$TaxOnShippingAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->currencyID);
$TaxOnHandlingAmount_value = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->value);
$TaxOnHandlingAmount_currencyID = trim($item->Taxes->TaxDetails->TaxOnShippingAmount->currencyID);
$ActualShippingCost_value = trim($item->ActualShippingCost->value);
$ActualShippingCost_currencyID = trim($item->ActualShippingCost->currencyID);
$ActualHandlingCost_value = trim($item->ActualHandlingCost->value);
$ActualHandlingCost_currencyID = trim($item->ActualHandlingCost->currencyID);
*/
$OrderLineItemID = trim($item->OrderLineItemID);
$ExtendedOrderID = trim($item->ExtendedOrderID);
$eBayPlusTransaction = trim($item->eBayPlusTransaction);
$GuaranteedShipping = trim($item->GuaranteedShipping);
//$TransactionPrice_value = trim($item->TransactionPrice->value);
/*if(isset(trim($item->Variation->value)) {
}
*/
//$output->writeln('ETAPE 10 '.$order->OrderID);
/* RECHERCHE ANNONCE */
$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';
$query = $repo_article_market_place->createQueryBuilder('p')
->select($select)
->leftJoin('p.article', 'a')
->leftJoin('a.regleTaxe', 'r')
->leftJoin('a.fournisseurDefaut', 'fd')
->where("p.idImport = :idImport AND p.compteMarketPlace = :compte")
->setParameters(["idImport" => $ItemID, "compte" => $compte])
->setMaxResults(1)
->orderBy('p.id', 'ASC');
$article_market_place_bdd = $query->getQuery()->getOneOrNullResult();
if ($article_market_place_bdd['id'] == "") {
//recuperer l'annonce sur ebay
/*
$donneesTmp = array();
$donneesTmp['update'] = 1;
$donneesTmp['idImport'] = $idImport;
$donneesTmp['reference'] = $SKU;
$donneesTmp['libelle'] = $Title;
$donneesTmp['date'] = new \Datetime();
$donneesTmp['date_maj'] = new \Datetime();
$donneesTmp['compteMarketPlace'] = $compte;
$donneesTmp['prix_base'] = $prix;
$donneesTmp['prix_vente'] = $prix;
$donneesTmp['unspsc'] = '';
$donneesTmp['ean'] = $ean;
$donneesTmp['stock'] = $Quantity;
$donneesTmp['description'] = '';
$donneesTmp['advertID_PriceMinister'] = NULL;
$donneesTmp['productID_PriceMinister'] = NULL;
$donneesTmp['active'] = 1;
//$donneesTmp['seller_product_id'] = $seller_product_id;
$donneesTmp['ecotaxe'] = 0;
*/
$article_market_place = $this->articleMarketPlaceService->getArticleMarketPlace(["idImport" => $ItemID, "compteMarketPlace" => $compte], $output);
if (is_object($article_market_place)) {
$query = $repo_article_market_place->createQueryBuilder('p')
->select($select)
->leftJoin('p.article', 'a')
->leftJoin('a.regleTaxe', 'r')
->leftJoin('a.fournisseurDefaut', 'fd')
->where("p.id = :id")
->setParameters(["id" => $article_market_place->getId()])
->setMaxResults(1)
->orderBy('p.id', 'ASC');
$article_market_place_bdd = $query->getQuery()->getOneOrNullResult();
}
}
if ($article_market_place_bdd['id'] != "") {
/*
if($article_market_place_bdd['fournisseur_defaut_id'] == 2) {
$commande_vega = true;
}
if($article_market_place_bdd['fournisseur_defaut_id'] == 95) {
$commande_sifam = true;
}
*/
//$output->writeln('ARTICLE TROUVE ');
//$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"]);
$parametersArticleCommandeEbay = [];
$where = "p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace";
//$where = "p.commande = :commande AND p.article = :article";
$parametersArticleCommandeEbay["commande"] = $commande_bdd['id'];
$parametersArticleCommandeEbay["article"] = $article_market_place_bdd["article_id"];
$parametersArticleCommandeEbay["articleMarketPlace"] = $article_market_place_bdd["id"];
//test;
/*
$query = $repo_article_commande->createQueryBuilder('p')
->select('p.id')
->where('p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace')
->setParameters(array('commande' => $commande_bdd['id'],"article"=>$article_market_place_bdd["article_id"]))
->setMaxResults(1)
->orderBy('p.id', 'ASC');
*/
$compteur_variation = 0;
$tabVariationEbay = [];
if (isset($item->Variation)) {
if (isset($item->Variation->VariationSpecifics)) {
if (isset($item->Variation->VariationSpecifics)) {
if (isset($item->Variation->VariationSpecifics->NameValueList)) {
if (isset($item->Variation->VariationSpecifics->NameValueList)) {
foreach ($item->Variation->VariationSpecifics->NameValueList as $variationArticle) {
$compteur_variation++;
if ($compteur_variation < 4) {
$parametersArticleCommandeEbay["declinaison".$compteur_variation] = $variationArticle->Name.":".$variationArticle->Value;
$where .= " AND p.declinaison".$compteur_variation." = :declinaison".$compteur_variation;
$tabVariationEbay[] = $variationArticle->Name.":".$variationArticle->Value;
}
}
}
}
}
}
}
//print_r($parametersArticleCommandeEbay);
//exit;
//$output->writeln('ETAPE 11 '.$order->OrderID);
$query = $repo_article_commande->createQueryBuilder('p')
->select('p.id')
->where($where)
->setParameters($parametersArticleCommandeEbay)
->setMaxResults(1)
->orderBy('p.id', 'ASC');
$article_commande_bdd = $query->getQuery()->getOneOrNullResult();
//print_r($article_commande_bdd);
//print_r($parametersArticleCommandeEbay);
//$prix_ht = $item_price*($item_price/($item_price+$article_market_place_bdd["regle_taxe_taux_defaut"]));
/*
$prix_ttc = round($TransactionPrice_value);
$prix_ht = round($TransactionPrice_value,2);
$item_price = round($TransactionPrice_value,2);
$prix_ht = $prix_ht*(100/(100+$article_market_place_bdd["regle_taxe_taux_defaut"]));
$prix_ht = round($prix_ht, 2);
$tva = (($TransactionPrice_value/$QuantityPurchased)-$prix_ht)*$QuantityPurchased;
*/
$prix_ttc = $TransactionPrice_value;
//$prix_ht = $TransactionPrice_value*(100/(100+floatval($SalesTaxPercent)));
$prix_ht = $TransactionPrice_value;
$total_with_tax = $TransactionPrice_value * $QuantityPurchased;
$total_ht = $total_with_tax * (100 / (100 + floatval($SalesTaxPercent)));
//TaxAmount_value
$total_ht = $prix_ht * $QuantityPurchased;
$prix_ttc = $TransactionPrice_value + $TotalTaxAmount_value;
$total_with_tax = $prix_ttc * $QuantityPurchased;
$total_with_tax = round($total_with_tax, 2);
$total_ht = round($total_ht, 2);
$tva = $total_with_tax - $total_ht;
$tauxTva = $SalesTaxPercent;
if ($tauxTva == 0 && $total_with_tax != 0) {
$tauxTva = $tva / $total_with_tax * 100;
$tauxTva = round($tauxTva, 2);
}
//recuperer la taxe
$taxeId = $article_market_place_bdd["regle_taxe_taux_defaut"];
$taxe = $this->taxeService->getTaxe(floatval($SalesTaxPercent));
if (is_object($taxe)) {
$taxeId = $taxe->getId();
}
//recuperer la taxe par currencyID TotalTaxAmount_currencyID
//exit;
$tableau_donnee = [];
for ($v = 0; $v < count($tabVariationEbay); $v++) {
$tableau_donnee["declinaison_".($v + 1)] = $tabVariationEbay[$v];
}
//$output->writeln('ETAPE 12 '.$order->OrderID);
$tableau_donnee["libelle"] = $Title;
$tableau_donnee["article_id"] = $article_market_place_bdd["article_id"];
$tableau_donnee["article_market_place_id"] = $article_market_place_bdd["id"];
$tableau_donnee["commande_id"] = $commande_bdd['id'];
$tableau_donnee["date_maj"] = (new \Datetime)->format("Y-m-d H:i:s");
$tableau_donnee["position"] = "0";
$tableau_donnee["reference"] = $ItemID;
$tableau_donnee["quantite"] = $QuantityPurchased;
$tableau_donnee["profondeur"] = "0";
$tableau_donnee["hauteur"] = "0";
$tableau_donnee["poids"] = "0";
$tableau_donnee["remise"] = "0";
$tableau_donnee["remise_supplementaire"] = "0";
$tableau_donnee["prix_base"] = $prix_ht;
$tableau_donnee["total_ht"] = $total_ht;
$tableau_donnee["total_with_tax"] = $total_with_tax;
$tableau_donnee["tva_vente"] = $tva;
$tableau_donnee["tva"] = $tauxTva;
$tableau_donnee["taxe_id"] = $taxeId;
/*
$total_frais_port_ttc = $ShippingServiceCost_value;
$tableau_donnee["total_frais_port"]=$total_frais_port_ttc;
$tableau_donnee["total_frais_port_ttc"]=$total_frais_port_ttc;
$tableau_donnee["total_tva_frais_port"]=0;
*/
//print_r($tableau_donnee);
if ($article_commande_bdd['id'] == "") {
$tableau_donnee['date'] = (new \Datetime)->format("Y-m-d H:i:s");
if ($donnee == "Oui") {
$conn->insert('commerciale__article_commande', $tableau_donnee);
}
$article_commande_bdd['id'] = $conn->lastInsertId();
//$output->writeln('<info>TABLE ARTICLE COMMANDE Action : INSERT : '.$commande_bdd['id'].'</info>');
} else {
$param_update_ac_ebay = [];
$param_update_ac_ebay["article_id"] = $article_market_place_bdd["article_id"];
$param_update_ac_ebay["commande_id"] = $commande_bdd["id"];
$param_update_ac_ebay["article_market_place_id"] = $article_market_place_bdd["id"];
for ($v = 0; $v < count($tabVariationEbay); $v++) {
$param_update_ac_ebay["declinaison_".($v + 1)] = $tabVariationEbay[$v];
}
if ($donnee == "Oui") {
$conn->update('commerciale__article_commande', $tableau_donnee, $param_update_ac_ebay);
}
//if($donnee == "Oui") $conn->update('commerciale__article_commande', $tableau_donnee, array('article_id' => $article_market_place_bdd["article_id"],'commande_id'=>$commande_bdd['id']));
//$output->writeln('<info>TABLE ARTICLE COMMANDE Action : UPDATE : '.$commande_bdd['id'].'</info>');
}
//$output->writeln('ETAPE 13 '.$order->OrderID);
} else {
$tab_introuvable[] = "MarketPlace ".$compte->getMarketPlace()->getLibelle()." : ".$compte->getLibelle(
)." Commande : ".$SellingManagerSalesRecordNumber." Produit : ".$ItemID;
$output->writeln('<error>ARTICLE INTROUVABLE '.$ItemID.'</error>');
}
//$this->calculerTotalCommande($commande_bdd['id']);
//if($nouvelle_commande_ebay) $this->calculerTotalCommande($output,$container,$commande_bdd['id'],$tableau_donnee_commande);
}
}
//historique
//priorisation?
//pdf?
}
private function traiterCommande2($compte, $order, $output, $donnee)
{
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$repo_commande = $this->em->getRepository(Commande::class);
$repo_article = $this->em->getRepository(Article::class);
$repo_article_commande = $this->em->getRepository(ArticleCommande::class);
$repo_type_document_commercial = $this->em->getRepository(TypeDocumentCommercial::class);
$repo_mode_expedition = $this->em->getRepository(ModeExpedition::class);
$repo_article_market_place = $this->em->getRepository(ArticleMarketPlace::class);
$repo_taxe = $this->em->getRepository(Taxe::class);
$repo_acompte = $this->em->getRepository(Acompte::class);
$repo_mode_reglement = $this->em->getRepository(ModeReglement::class);
$output->writeln('ORDER ID '.$order['orderId']);
//print_r($order);
$SellingManagerSalesRecordNumber = "";
if ( ! empty($order['salesRecordReference'])) {
$SellingManagerSalesRecordNumber = trim($order['salesRecordReference']);
}
$OrderID = trim($order['orderId']);
//ebayCollectAndRemitTax
$OrderStatus = trim($order['orderFulfillmentStatus']);
//print_r($order["cancelStatus"]["cancelState"]=="CANCELED");
if ( ! empty($order["cancelStatus"]["cancelState"]) && $order["cancelStatus"]["cancelState"] == "CANCELED") {
$OrderStatus = $order["cancelStatus"]["cancelState"];
}
$eBayPaymentStatus = trim($order['orderPaymentStatus']);
$PaymentMethod = trim($order['paymentSummary']['payments'][0]['paymentMethod']);
$tauxChange = 1;
if ( ! empty($order['paymentSummary']['payments'][0]['amount']['value']) && ! empty($order['paymentSummary']['payments'][0]['amount']['convertedFromValue'])) {
$tauxChange = floatval($order['paymentSummary']['payments'][0]['amount']['value']) / floatval($order['paymentSummary']['payments'][0]['amount']['convertedFromValue']);
$tauxChange = round($tauxChange, 3);
}
$output->writeln('taux de change : '.$tauxChange);
$CreatedTime = new \Datetime($order['creationDate']);
$CreatedTime->setTimezone(new \DateTimeZone('Europe/Paris'));
$BuyerCheckoutMessage = '';
if (array_key_exists('buyerCheckoutNotes', $order)) {
$output->writeln($order['buyerCheckoutNotes']);
$BuyerCheckoutMessage = json_encode($order['buyerCheckoutNotes']);
$output->writeln($BuyerCheckoutMessage);
}
$shippingCarrierCode = '';//transporteur
$shippingServiceCode = '';//service transporteur
$fullName = '';
$addressLine1 = '';
$addressLine2 = '';
$city = '';
$stateOrProvince = '';
$postalCode = '';
$countryCode = '';
$telephone = '';
$email = '';
if (isset($order['fulfillmentStartInstructions'])) {
$shippingStep = $order['fulfillmentStartInstructions'][0]['shippingStep'];
if (array_key_exists('shippingCarrierCode', $shippingStep)) {
$shippingCarrierCode = trim($shippingStep['shippingCarrierCode']);
}//transporteur
if (array_key_exists('shippingServiceCode', $shippingStep)) {
$shippingServiceCode = trim($shippingStep['shippingServiceCode']);
}//service transporteur
if (array_key_exists('fullName', $shippingStep['shipTo'])) {
$fullName = trim($shippingStep['shipTo']['fullName']);
}
$contactAdress = $order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['contactAddress'];
if (array_key_exists('addressLine1', $contactAdress)) {
$addressLine1 = trim($contactAdress['addressLine1']);
}
if (array_key_exists('addressLine2', $contactAdress)) {
$addressLine2 = trim($contactAdress['addressLine2']);
}
if (array_key_exists('city', $contactAdress)) {
$city = trim($contactAdress['city']);
}
if (array_key_exists('stateOrProvince', $contactAdress)) {
$stateOrProvince = trim($contactAdress['stateOrProvince']);
}
if (array_key_exists('postalCode', $contactAdress)) {
$postalCode = trim($contactAdress['postalCode']);
}
if (array_key_exists('countryCode', $contactAdress)) {
$countryCode = trim($contactAdress['countryCode']);
}
if ( ! empty($order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['primaryPhone']['phoneNumber'])) {
$telephone = $order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['primaryPhone']['phoneNumber'];
}
if ( ! empty($order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['email'])) {
$email = $order['fulfillmentStartInstructions'][0]['shippingStep']['shipTo']['email'];
}
}
/*
$Buyer_Email = '';
$Buyer_UserFirstName = '';
$Buyer_UserLastName = '';
if(isset($order->TransactionArray->Transaction) && count($order->TransactionArray->Transaction)) {
foreach($order->TransactionArray->Transaction as $transaction) {
$Buyer_Email = $transaction->Buyer->Email;
$Buyer_UserFirstName = $transaction->Buyer->UserFirstName;
$Buyer_UserLastName = $transaction->Buyer->UserLastName;
}
}
*/
//$BuyerUserID = trim($order->BuyerUserID);
$tab_client = [
/*
'idImport' => 'cpt'.$compte->getId().'_'.trim($order->BuyerUserID),
'email' => trim($order->BuyerUserID),
'nom' => $Buyer_UserLastName,
'prenom' => $Buyer_UserFirstName,
*/
'pays' => $countryCode,
'pays_code_iso' => $countryCode,
'compteMarketPlace' => $compte,
];
$client = $this->clientService->getClient($tab_client);
$tauxTva = 0;
$taxe = $this->taxeService->getTaxeDefaut($countryCode);
if (is_object($taxe)) {
$tauxTva = $taxe->getTaux();
$output->writeln('Pays code iso : '.$countryCode);
$output->writeln('Taxe ID : '.$taxe->getId());
$output->writeln('Taxe taux : '.$taxe->getTaux());
}
$output->writeln('Apres taxe taux');
/*
$tab_shipping_address = array(
'livraisonDefaut' => true,
'societe' => trim($order->ShippingAddress->Name),
'rue' => trim($order->ShippingAddress->Street1),
'complement' => trim($order->ShippingAddress->Street2),
'ville' => trim($order->ShippingAddress->CityName),
'pays' => trim($order->ShippingAddress->CountryName),
'pays_code_iso' => trim($order->ShippingAddress->Country),
'idImport' => 'cpt'.$compte->getId().'_'.trim($order->ShippingAddress->AddressID),
'telephone' => trim($order->ShippingAddress->Phone),
'codePostal' => trim($order->ShippingAddress->PostalCode)
);
if(is_object($client)) $tab_shipping_address['client'] = $client;
//$shipping_address = $service_adresse->getAdresse($tab_shipping_address, $output);
*/
//lien commande / marketplace
$query = $repo_commande->createQueryBuilder('p')
->select(
'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'
)//p.commentaireExpedition as commentaire_expedition,p.sifam
->where(
'(p.archive is null or p.archive = :archive) and p.compteMarketPlace = :compteMarketPlace AND p.idImport = :idImport AND tp.id = :typeDocumentCommercial'
)
->setParameters(['archive' => '0', 'compteMarketPlace' => $compte->getId(), "idImport" => $OrderID, 'typeDocumentCommercial' => TypeDocumentCommercial::COMMANDE])
->setMaxResults(1)
//->join('p.typeDocumentCommercial', 'tp')
->join('p.statutCommande', 'sc')
->leftJoin('p.statutCommandeMarketPlace', 'scm')
->orderBy('p.id', 'ASC');
$output->writeln('debut recherche commande');
$commande_bdd = $query->getQuery()->getOneOrNullResult();
$output->writeln('fin recherche commande');
$tableau_donnee = [];
//$dateCommande = new \Datetime($CreatedTime);
//$tableau_donnee["reference"]=$purchaseid;
//$tableau_donnee["reference_market_place"]=$SellingManagerSalesRecordNumber;
$tableau_donnee["reference_market_place"] = $OrderID;
if (is_object($client)) {
$tableau_donnee["client_id"] = $client->getId();
} else {
$tableau_donnee["client_id"] = null;
}
$tableau_donnee["id_import"] = $OrderID;
$tableau_donnee["compte_market_place_id"] = $compte->getId();
$tableau_donnee["dateMaj"] = (new \Datetime)->format("Y-m-d H:i:s");
//$tableau_donnee["date"] = $dateCommande->format('Y-m-d H:i:s');
$tableau_donnee["date"] = $CreatedTime->format('Y-m-d H:i:s');
$tableau_donnee["type_document_commercial_id"] = TypeDocumentCommercial::COMMANDE;
$tableau_donnee["archive"] = 0;
$tableau_donnee["avecTaxe"] = 1;
$tableau_donnee["statut_paiement_id"] = 1;
$tableau_donnee["etat_commande_id"] = 1;
$tableau_donnee["bascule_comptabilite"] = 0;
$tableau_donnee["visible"] = "1";
$tableau_donnee["modifiable"] = "0";
$tableau_donnee["temps_passe"] = "0";
$tableau_donnee["temps_facture"] = "0";
$tableau_donnee["attente_facturation"] = "0";
$tableau_donnee["origine_saisie"] = "commande";
$tableau_donnee["statut_commande_id"] = "2";
$tableau_donnee["telephone"] = $telephone;
$tableau_donnee["email"] = $email;
/*
$devise = $service_devise->getDevise(trim($order->Total->currencyID), $output)
if(is_object($devise)) $tableau_donnee["devise_id"] = $devise->getId();
*/
/*
$tableau_donnee["total_frais_port_ttc"] = floatval($order['pricingSummary']['deliveryCost']['value']);
if(!empty($order['pricingSummary']['deliveryDiscount'])) $tableau_donnee["total_frais_port_ttc"] += floatval($order['pricingSummary']['deliveryDiscount']['value']);
$tableau_donnee["total_frais_port"] = $tableau_donnee["total_frais_port_ttc"]*(100/(100+floatval($tauxTva)));
$tableau_donnee["total_frais_port"] = round($tableau_donnee["total_frais_port"], 2);
$tableau_donnee["total_tva_frais_port"] = $tableau_donnee["total_frais_port_ttc"] - $tableau_donnee["total_frais_port"] ;
$tableau_donnee["total_ttc"] = floatval($order['pricingSummary']['total']['value']);
$tableau_donnee["total"] = floatval($order['pricingSummary']['priceSubtotal']['value'])*(100/(100+floatval($tauxTva)));
$tableau_donnee["total"] = round($tableau_donnee["total"], 2);
*/
$tableau_donnee['commentaire'] = $BuyerCheckoutMessage;
//livraison
/*
if(is_object($shipping_address)) $tableau_donnee['adresse_livraison_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_livraison_id'] = NULL;
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;
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;
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;
*/
$tableau_donnee['adresse_livraison_id'] = null;
$tableau_donnee['ville_livraison_txt'] = $city;
$tableau_donnee['pays_livraison_txt'] = $countryCode;
$tableau_donnee['code_postal_livraison_txt'] = $postalCode;
$tableau_donnee['libelle_livraison'] = $fullName;
//$tableau_donnee['numero_livraison'] = '';
$tableau_donnee['rue_livraison'] = $addressLine1;
$tableau_donnee['complement_livraison'] = $addressLine2;
$tableau_donnee['code_iso_livraison'] = $countryCode;
$tableau_donnee['state_or_province_livraison'] = $countryCode;
//facturation
/*
if(is_object($shipping_address)) $tableau_donnee['adresse_facturation_id'] = $shipping_address->getId(); else $tableau_donnee['adresse_facturation_id'] = NULL;
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;
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;
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;
*/
$tableau_donnee['adresse_facturation_id'] = null;
$tableau_donnee['ville_facturation_txt'] = $city;
$tableau_donnee['pays_facturation_txt'] = $countryCode;
$tableau_donnee['code_postal_facturation_txt'] = $postalCode;
$tableau_donnee['libelle_facturation'] = $fullName;
//$tableau_donnee['numero_facturation'] = '';
$tableau_donnee['rue_facturation'] = $addressLine1;
$tableau_donnee['complement_facturation'] = $addressLine2;
$tableau_donnee['code_iso_facturation'] = $countryCode;
$tableau_donnee['state_or_province_facturation'] = $countryCode;
//ShippingCarrierUsed
//transporteur_id
//ShipmentTrackingNumber
//numero_suivi
//AmountPaid
/*
$tab_statut_commande = array();
$tab_statut_commande["reference"]=$OrderStatus;
*/
//statut de commande
//mode de reglement marketplace
$output->writeln('debut mode de reglement');
if ( ! empty($PaymentMethod)) {
$mode_reglement_market_place = $this->marketPlaceService->getModeReglementMarketPlace($PaymentMethod, $compte->getMarketPlace());
if (is_object($mode_reglement_market_place)) {
$tableau_donnee['mode_reglement_market_place_id'] = $mode_reglement_market_place->getId();
if (is_object($mode_reglement_market_place->getModeReglement())) {
$tableau_donnee['mode_reglement_id'] = $mode_reglement_market_place->getModeReglement()->getId();
}
}
}
$output->writeln('fin mode de reglement');
//mode d'expedition
$output->writeln('debut mode expedition');
if ( ! empty($shippingServiceCode)) {
$tableau_donnee['mode_expedition_id'] = $this->modeExpeditionService->getModeExpedition($shippingServiceCode, $shippingServiceCode, $compte->getMarketPlace());
}
if ( ! empty($tableau_donnee['mode_expedition_id'])) {
$mode_expedition_obj = $repo_mode_expedition->find($tableau_donnee['mode_expedition_id']);
if (is_object($mode_expedition_obj) && is_object($mode_expedition_obj->getTransporteur())) {
$tableau_donnee['transporteur_id'] = $mode_expedition_obj->getTransporteur()->getId();
}
}
$output->writeln('fin mode expedition');
//statut commande marketplace
$output->writeln('debut calculerStatutCommandeMarketPlace');
if ( ! empty($OrderStatus)) {
$statut_commande_calcule = $this->commandeService->calculerStatutCommandeMarketPlace($compte, $OrderStatus, $commande_bdd);
$tableau_donnee['statut_commande_market_place_id'] = $statut_commande_calcule["id"];
$tableau_donnee['statut_commande_id'] = $statut_commande_calcule["action_statut_commande_id"];
if ( ! empty($statut_commande_calcule['statut_paiement_id'])) {
$tableau_donnee['statut_paiement_id'] = $statut_commande_calcule['statut_paiement_id'];
}
}
$output->writeln('fin calculerStatutCommandeMarketPlace');
if ($order['orderPaymentStatus'] == 'PAID') {
$tableau_donnee['statut_paiement_id'] = 2;
}
/*
if(!empty($order['order_state_reason_code'])){
$statut_paiement_calcule = $service_commande->calculerStatutPaiementMarketPlace($order['order_state_reason_code']);
$tableau_donnee['statut_paiement_id'] = $statut_paiement_calcule["statut_paiement_id"];
if(!empty($statut_paiement_calcule["statut_commande_id"])) $tableau_donnee['statut_commande_id'] = $statut_paiement_calcule["statut_commande_id"];
}
*/
/*
$mode_expedition_bdd = $this->creerModeExpedition($output,$container,$compte,$tab_expedition);
$tableau_donnee['mode_expedition_id']=$mode_expedition_bdd["id"];
$tab_reglement = array();
$tab_reglement["reference"]=$PaymentMethods;
$mode_reglement_bdd = $this->creerModeReglement($output,$container,$compte,$tab_reglement);
$tableau_donnee['modereglement_id']=$mode_reglement_bdd["id"];
if(is_object($ville_obj)) {
$tableau_donnee['ville_facturation_id']=$ville_obj->getId();
$tableau_donnee['code_postal_facturation_id']=$ville_obj->getId();
if(is_object($ville_obj->getParentId()) && is_object($ville_obj->getParentId()->getParentId()) && is_object($ville_obj->getParentId()->getParentId()->getParentId())) {
$tableau_donnee['pays_facturation_id'] = $ville_obj->getParentId()->getParentId()->getParentId()->getId();
}
}
*/
$tableau_donnee_commande = $tableau_donnee;
$nouvelle_commande_ebay = true;
//$output->writeln('ETAPE 8 '.$order->OrderID);
$mettre_a_jour_cmde = true;
$est_une_nouvelle_commande = false;
if ($commande_bdd['id'] == "") {
$est_une_nouvelle_commande = true;
$commande_obj = new Commande();
$type_commande = TypeDocumentCommercial::COMMANDE;
$commande_obj->setTypeDocumentCommercial($type_commande);
$tableau_donnee["reference"] = $this->numerotationDocumentService->generer($commande_obj);
/*
if (array_key_exists('code_postal_livraison_texte', $tableau_donnee)) {
if( substr($tableau_donnee['code_postal_livraison_texte'],0,2) == "20")
{
$tableau_donnee['adresse_a_changer']="1";
$tableau_donnee['commentaireExpedition']="ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE ATTENTION CORSE";
}
}
*/
$donnees_commande = $tableau_donnee;
if ($donnee == "Oui") {
$conn->insert('commerciale__commande', $tableau_donnee);
}
$commande_bdd['id'] = $conn->lastInsertId();
$commande_obj = $repo_commande->find($commande_bdd['id']);
$this->commandeService->creerHistorique($commande_obj, 10);
$output->writeln('<info>TABLE COMMANDE Action : INSERT : '.$tableau_donnee["reference_market_place"].'</info>');
$output->writeln('ETAPE 6');
} else {
if (1 == 0 && in_array($tableau_donnee["reference_market_place"], ['17-07342-02348'])) {
} elseif (
1 == 1
and
! empty($commande_bdd['statut_commande_id'])
and
(
//Confirmation d'expédition market place en cours
$commande_bdd["statut_commande_id"] == 36
)
) {
$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)");
} elseif (
1 == 1
and
(
//Partiel préparé
$commande_bdd['statut_commande_id'] == 1
or
// Préparée
$commande_bdd['statut_commande_id'] == 6
or
// Partiellement livrée
$commande_bdd['statut_commande_id'] == 28
or
// Livrée
$commande_bdd['statut_commande_id'] == 29
or
// Confirmation d'expédition market place en cours
$commande_bdd['statut_commande_id'] == 36
or
// Expédiée
$commande_bdd['statut_commande_id'] == 37
or
// En attente du numéro de suivi
$commande_bdd['statut_commande_id'] == 40
)
) {
// Si la commande redescend en expédié on passe la commande dans l'erp en expédiée
$commande_redescendu_comme_expedie = false;
if ($commande_bdd["statut_commande_id"] == 6) {
//$OrderStatus = "FULFILLED";
if ( ! empty($OrderStatus)) {
//$donnees_commande['statut_commande_market_place_id'] = $service_market_place->getStatutCommandeMarketPlace($OrderState, $marketPlace);
$statut_commande_calcule = $this->commandeService->calculerStatutCommandeMarketPlace($compte, $OrderStatus, $commande_bdd);
//print_r($statut_commande_calcule);
if ( ! empty($statut_commande_calcule["action_statut_commande_id"]) && $statut_commande_calcule["action_statut_commande_id"] == "37") {
$commande_obj = $repo_commande->find($commande_bdd['id']);
$this->commandeService->creerHistorique($commande_obj, 14);
$commande_redescendu_comme_expedie = true;
$req_ligne_commande = "select id,ral_client,article_id,quantite from commerciale__article_commande where commande_id = ".$commande_bdd["id"];
$output->writeln($req_ligne_commande);
$stmt = $conn->executeQuery($req_ligne_commande);
$ligne_commande_bdd = $stmt->fetchAllAssociative();
if (count($ligne_commande_bdd) > 0) {
foreach ($ligne_commande_bdd as $l_bdd) {
$donnees_ac = [];
$donnees_ac['ral_client'] = 0;
$conn->update('commerciale__article_commande', $donnees_ac, ['id' => $l_bdd['id']]);
$output->writeln("ID_ARTICLE_COMMANDE:".$l_bdd['id']);
//$variation = floatval($ac_bdd['quantite']) - floatval($Quantity);
$article_obj = $repo_article->find($l_bdd['article_id']);
if ($l_bdd['ral_client'] > 0) {
$stock_reserve = floatval($article_obj->getStockReserve()) - $l_bdd['quantite'];
$stock_reserve = max(0, $stock_reserve);
$conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article_obj->getId()]);
}
$sql_bp = "select id,reference,statut_commande_id
FROM `commerciale__commande`
WHERE commande_id = ".$commande_bdd["id"]."
and type_document_commercial_id = ".TypeDocumentCommercial::BP."
and statut_commande_id = 10
";
$stmt = $conn->executeQuery($sql_bp);
$bp_bdd = $stmt->fetchAllAssociative();
if (count($bp_bdd) > 0) {
foreach ($bp_bdd as $un_bp_bdd) {
$output->writeln("ON ANNULE LE BP :".$un_bp_bdd['id']." REF:".$un_bp_bdd['reference']);
$donnees_historique = [];
$donnees_historique["message "] = "";
$bp_obj = $repo_commande->find($un_bp_bdd['id']);
$this->commandeService->creerHistorique($bp_obj, 29, $donnees_historique);
$donnees_bp_annule = [];
$donnees_bp_annule["statut_commande_id"] = 24;
$conn->update('commerciale__commande', $donnees_bp_annule, ['id' => $un_bp_bdd['id']]);
}
}
$donnees_commande_temp = [];
$donnees_commande_temp['statut_commande_market_place_id'] = $statut_commande_calcule["id"];
$donnees_commande_temp['statut_commande_id'] = $statut_commande_calcule["action_statut_commande_id"];
//print_r($donnees_commande_temp);
$conn->update('commerciale__commande', $donnees_commande_temp, ['id' => $commande_bdd["id"]]);
}
}
/*
$donnees_ac['ral_client'] = 0;
$conn->update('commerciale__article_commande',$donnees_ac, array('id'=>$ac_bdd['id']));
//$variation = floatval($ac_bdd['quantite']) - floatval($Quantity);
$stock_reserve = floatval($article->getStockReserve()) - $ac_bdd['quantite'];
$stock_reserve = max(0, $stock_reserve);
$conn->update('article__article',array('stock_reserve'=>$stock_reserve), array('id'=>$article->getId()));
*/
}
}
}
$trad_libelle_statut_commande = "";
if ($commande_bdd["statut_commande_id"] == 37) {
$trad_libelle_statut_commande = "Expédiée";
} elseif ($commande_bdd["statut_commande_id"] == 1) {
$trad_libelle_statut_commande = "Partiel préparé";
} elseif ($commande_bdd["statut_commande_id"] == 6) {
$trad_libelle_statut_commande = "Passé en BP";
} elseif ($commande_bdd["statut_commande_id"] == 7) {
$trad_libelle_statut_commande = "Annulée";
} elseif ($commande_bdd["statut_commande_id"] == 28) {
$trad_libelle_statut_commande = "Partiellement livrée";
} elseif ($commande_bdd["statut_commande_id"] == 29) {
$trad_libelle_statut_commande = "Livrée";
}
if ($commande_redescendu_comme_expedie) {
$output->writeln(
"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
);
} else {
// ON FAIT RIEN
$output->writeln("ON NE MET PLUS A JOUR LA COMMANDE CAR STATUT COMMANDE_ID = ".$commande_bdd["statut_commande_id"]."(".$trad_libelle_statut_commande.")");
}
$mettre_a_jour_cmde = false;
}
$output->writeln('ETAPE 7');
$nouvelle_commande_ebay = false;
$tableau_donnee["reference"] = $commande_bdd['reference'];
$donnees_commande = $tableau_donnee;
if ($donnee == "Oui" && $mettre_a_jour_cmde) {
$conn->update('commerciale__commande', $tableau_donnee, ['id' => $commande_bdd['id']]);
}
$commande_obj = $repo_commande->find($commande_bdd['id']);
if ($mettre_a_jour_cmde) {
$this->commandeService->creerHistorique($commande_obj, 14);
}
if ($mettre_a_jour_cmde) {
$output->writeln('<info>TABLE COMMANDE Action : UPDATE : '.$tableau_donnee["reference_market_place"].' / ID : '.$commande_bdd['id'].'</info>');
} else {
$output->writeln(
'<info>TABLE COMMANDE Action : AUCUNE CAR statut_commande_id = '.$commande_bdd['statut_commande_id'].' : '.$tableau_donnee["reference_market_place"].' / ID : '.$commande_bdd['id'].'</info>'
);
$output->writeln('TEST AA');
}
}
//$output->writeln('ETAPE 9 '.$order->OrderID);
//$handle_pdf = fopen($domaine.$url_pdf, 'r');
//$mettre_a_jour_cmde = true;//pour test
$calculerHt = false;
if ($mettre_a_jour_cmde && isset($order['lineItems'])) {
//print_r($order);
$output->writeln('ETAPE 10 ');
$total_poids = 0;
if ( ! empty($order['lineItems'])) {
$output->writeln('lines '.count($order['lineItems']));
}
$total_tva_de_la_commande = 0;
foreach ($order['lineItems'] as $item) {
$output->writeln('line ');
$ItemID = trim($item['legacyItemId']);
$OrderLineItemID = trim($item['lineItemId']);
/* RECHERCHE ANNONCE */
$article_market_place = $this->articleMarketPlaceService->getArticleMarketPlace(["idImport" => $ItemID, "compteMarketPlace" => $compte], $output);
if (is_object($article_market_place)) {
$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';
$query = $repo_article_market_place->createQueryBuilder('p')
->select($select)
->leftJoin('p.article', 'a')
->leftJoin('a.regleTaxe', 'r')
->leftJoin('a.fournisseurDefaut', 'fd')
->where("p.id = :id")
->setParameters(["id" => $article_market_place->getId()])
->setMaxResults(1)
->orderBy('p.id', 'ASC');
$article_market_place_bdd = $query->getQuery()->getOneOrNullResult();
}
if ($article_market_place_bdd['id'] != "") {
/*
if($article_market_place_bdd['fournisseur_defaut_id'] == 2) {
$commande_vega = true;
}
if($article_market_place_bdd['fournisseur_defaut_id'] == 95) {
$commande_sifam = true;
}
*/
//$output->writeln('ARTICLE TROUVE ');
//$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"]);
$parametersArticleCommandeEbay = [];
$where = "p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace";
//$where = "p.commande = :commande AND p.article = :article";
$parametersArticleCommandeEbay["commande"] = $commande_bdd['id'];
$parametersArticleCommandeEbay["article"] = $article_market_place_bdd["article_id"];
$parametersArticleCommandeEbay["articleMarketPlace"] = $article_market_place_bdd["id"];
//test;
/*
$query = $repo_article_commande->createQueryBuilder('p')
->select('p.id')
->where('p.commande = :commande AND p.article = :article and p.articleMarketPlace = :articleMarketPlace')
->setParameters(array('commande' => $commande_bdd['id'],"article"=>$article_market_place_bdd["article_id"]))
->setMaxResults(1)
->orderBy('p.id', 'ASC');
*/
$compteur_variation = 0;
$tabVariationEbay = [];
//if(!empty($item['legacyVariationId'])) $tabVariationEbay[] = $item['legacyVariationId'];
/*
if(isset($item->Variation)) {
if(isset($item->Variation->VariationSpecifics)) {
if(isset($item->Variation->VariationSpecifics)) {
if(isset($item->Variation->VariationSpecifics->NameValueList)) {
if(isset($item->Variation->VariationSpecifics->NameValueList)) {
foreach($item->Variation->VariationSpecifics->NameValueList as $variationArticle) {
$compteur_variation++;
if($compteur_variation<4) {
$parametersArticleCommandeEbay["declinaison".$compteur_variation]=$variationArticle->Name.":".$variationArticle->Value;
$where .= " AND p.declinaison".$compteur_variation." = :declinaison".$compteur_variation;
$tabVariationEbay[]=$variationArticle->Name.":".$variationArticle->Value;
}
}
}
}
}
}
}
*/
$query = $repo_article_commande->createQueryBuilder('p')
->select('p.id,p.ralClient,p.quantite')
->where($where)
->setParameters($parametersArticleCommandeEbay)
->setMaxResults(1)
->orderBy('p.id', 'ASC');
$article_commande_bdd = $query->getQuery()->getOneOrNullResult();
$quantite = floatval(trim($item['quantity']));
$total_poids += $quantite * $article_market_place->getArticle()->getPoids();
//$total_ttc = floatval(trim($item['total']['value']));
//$total_ttc = floatval(trim($item['lineItemCost']['value']));
//$montantTransport = floatval(trim($item['deliveryCost']['shippingCost']['value']));
$devise = $this->deviseService->getDevise(trim($item['lineItemCost']['currency']), $output);
if (count($item['taxes'])) {
$montantTva = 0;
foreach ($item['taxes'] as $tax) {
$montantTva += floatval(trim($tax['amount']['value']));
}
//$total_ht = $total_ttc - $montantTva;
$total_ht = floatval(trim($item['lineItemCost']['value']));
if (array_key_exists('discountedLineItemCost', $item)) {
$total_ht = floatval(trim($item['discountedLineItemCost']['value']));
}
$total_ttc = $montantTva + $total_ht;
$tauxTva = $montantTva / $total_ht * 100;
$tauxTva = round($tauxTva, 1);
$taxe = $repo_taxe->findOneBy(['taux' => $tauxTva]);
$output->writeln('taxe taux calculé :'.$tauxTva);
if (is_object($taxe)) {
$output->writeln('taxe calculée ID :'.$taxe->getId());
}
} else {
$calculerHt = true;
$total_ttc = floatval(trim($item['lineItemCost']['value']));
if (array_key_exists('discountedLineItemCost', $item)) {
$total_ttc = floatval(trim($item['discountedLineItemCost']['value']));
}
if ($tauxChange) {
$total_ttc = $total_ttc * $tauxChange;
$total_ttc = round($total_ttc, 3);
}
$total_ht = floatval($total_ttc) * (100 / (100 + $tauxTva));
//$totalHt -= $montantTransport;
//$total_ht = round($total_ht, 2);
$total_ht = round($total_ht, 3);
//$total_ht = round($total_ht, 2,PHP_ROUND_HALF_DOWN);
$montantTva = $total_ttc - $total_ht;
}
/*
$total_ht = floatval($total_ttc) * (100 / (100 + $tauxTva));
$total_ht = round($total_ht, 2);
$montantTva = $total_ttc - $total_ht;
*/
$prix_ht = $total_ht;
if ( ! empty($quantite)) {
$prix_ht = $prix_ht / $quantite;
}
/*
$prix_ht = $TransactionPrice_value;
$total_ht = $prix_ht * $QuantityPurchased;
$total_ht = round($total_ht, 2);
$prix_ttc = $TransactionPrice_value + $TotalTaxAmount_value;
$total_with_tax = $prix_ttc * $QuantityPurchased;
$total_with_tax = round($total_with_tax, 2);
$tva = $total_with_tax - $total_ht;
*/
$tableau_donnee = [];
for ($v = 0; $v < count($tabVariationEbay); $v++) {
$tableau_donnee["declinaison_".($v + 1)] = $tabVariationEbay[$v];
}
//$output->writeln('ETAPE 12 '.$order->OrderID);
//On passe l'article en mouvemente
$conn->update('article__article', ["mouvemente" => 1], ["id" => $article_market_place_bdd["article_id"]]);
$tableau_donnee["libelle"] = trim($item['title']);
$tableau_donnee["article_id"] = $article_market_place_bdd["article_id"];
$tableau_donnee["article_market_place_id"] = $article_market_place_bdd["id"];
$tableau_donnee["commande_id"] = $commande_bdd['id'];
$tableau_donnee["date_maj"] = (new \Datetime)->format("Y-m-d H:i:s");
$tableau_donnee["position"] = "0";
$tableau_donnee["reference"] = $ItemID;
$tableau_donnee["quantite"] = $quantite;
$tableau_donnee["profondeur"] = "0";
$tableau_donnee["hauteur"] = "0";
$tableau_donnee["poids"] = "0";
$tableau_donnee["remise"] = "0";
$tableau_donnee["remise_supplementaire"] = "0";
$tableau_donnee["prix_base"] = $prix_ht;
$tableau_donnee["total_ht"] = $total_ht;
$tableau_donnee["total_with_tax"] = $total_ttc;
$tableau_donnee["tva_vente"] = $montantTva;
$tableau_donnee["tva"] = $tauxTva;
if (is_object($taxe)) {
$tableau_donnee["taxe_id"] = $taxe->getId();
} else {
$tableau_donnee["taxe_id"] = null;
}
$tableau_donnee["taux_change"] = $tauxChange;
$tableau_donnee["total_ttc_devise"] = floatval(trim($item['lineItemCost']['value']));
if (array_key_exists('discountedLineItemCost', $item)) {
$tableau_donnee["total_ttc_devise"] = floatval(trim($item['discountedLineItemCost']['value']));
}
$output->writeln('total_ht : '.$total_ht);
$output->writeln('total_with_tax : '.$total_ttc);
$output->writeln('tva_vente : '.$tableau_donnee["tva_vente"]);
$output->writeln('tva : '.$tauxTva);
$output->writeln('taxe_id : '.$tableau_donnee["taxe_id"]);
$total_tva_de_la_commande += $tableau_donnee["tva_vente"];
/*
$total_frais_port_ttc = $ShippingServiceCost_value;
$tableau_donnee["total_frais_port"]=$total_frais_port_ttc;
$tableau_donnee["total_frais_port_ttc"]=$total_frais_port_ttc;
$tableau_donnee["total_tva_frais_port"]=0;
*/
//print_r($tableau_donnee);
$tableau_donnee['id_import'] = $OrderLineItemID;
if ($article_commande_bdd['id'] == "") {
$tableau_donnee['ral_client'] = $tableau_donnee['quantite'];
if ($est_une_nouvelle_commande && ($donnees_commande['statut_commande_id'] == "37" or $donnees_commande['statut_commande_id'] == "29")) {
$tableau_donnee['ral_client'] = 0;
} else {
$article = $repo_article->find($article_market_place_bdd["article_id"]);
$stock_reserve = floatval($article->getStockReserve()) + floatval($tableau_donnee['quantite']);
$stock_reserve = max(0, $stock_reserve);
$conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article->getId()]);
}
$tableau_donnee['date'] = (new \Datetime)->format("Y-m-d H:i:s");
if ($donnee == "Oui") {
$conn->insert('commerciale__article_commande', $tableau_donnee);
}
$article_commande_bdd['id'] = $conn->lastInsertId();
$output->writeln('publierAnnonce 1');
$this->publierAnnonce($article_market_place_bdd["article_id"], '', $output);
//$output->writeln('<info>TABLE ARTICLE COMMANDE Action : INSERT : '.$commande_bdd['id'].'</info>');
} else {
$param_update_ac_ebay = [];
//Cas d'une commande acceptée puis annulée entre temps par le client ou expédié depuis le marketplace
if ( ! $est_une_nouvelle_commande
&&
(
$commande_bdd["statut_commande_id"] == 9 //Acceptée
or
$commande_bdd["statut_commande_id"] == 2 //En attente
or
$commande_bdd["statut_commande_id"] == 38 //Non identifié
)
&&
($donnees_commande['statut_commande_id'] == "7" or $donnees_commande['statut_commande_id'] == "37" or $donnees_commande['statut_commande_id'] == "29")
) {
$article = $repo_article->find($article_market_place_bdd["article_id"]);
$param_update_ac_ebay['ral_client'] = 0;
//$conn->update('commerciale__article_commande',$donnees_ac, array('id'=>$article_commande_bdd['id']));
//$variation = floatval($ac_bdd['quantite']) - floatval($QuantityOrdered);
$stock_reserve = floatval($article->getStockReserve()) - $tableau_donnee['quantite'];
$stock_reserve = max(0, $stock_reserve);
$conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article->getId()]);
$output->writeln('publierAnnonce 2');
$this->publierAnnonce($article_market_place_bdd["article_id"], '', $output);
} else {
$variation = floatval($article_commande_bdd['quantite']) - floatval($tableau_donnee['quantite']);
if ($variation != 0) {
$article = $repo_article->find($article_market_place_bdd["article_id"]);
//modification du ral client
//$donnees_ac = array();
$param_update_ac_ebay['ral_client'] = floatval($article_commande_bdd['ralClient']) + $variation;
//modification de la reservation de stock
$stock_reserve = floatval($article->getStockReserve()) + $variation;
$stock_reserve = max(0, $stock_reserve);
$conn->update('article__article', ['stock_reserve' => $stock_reserve], ['id' => $article->getId()]);
$output->writeln('publierAnnonce 3');
$this->publierAnnonce($article_market_place_bdd["article_id"], '', $output);
}
//$conn->update('commerciale__article_commande',$donnees_ac, array('id'=>$ac_bdd['id']));
}
$param_update_ac_ebay['id_import'] = $OrderLineItemID;
$param_update_ac_ebay["article_id"] = $article_market_place_bdd["article_id"];
$param_update_ac_ebay["commande_id"] = $commande_bdd["id"];
$param_update_ac_ebay["article_market_place_id"] = $article_market_place_bdd["id"];
for ($v = 0; $v < count($tabVariationEbay); $v++) {
$param_update_ac_ebay["declinaison_".($v + 1)] = $tabVariationEbay[$v];
}
if ($donnee == "Oui") {
$conn->update('commerciale__article_commande', $tableau_donnee, $param_update_ac_ebay);
}
//if($donnee == "Oui") $conn->update('commerciale__article_commande', $tableau_donnee, array('article_id' => $article_market_place_bdd["article_id"],'commande_id'=>$commande_bdd['id']));
//$output->writeln('<info>TABLE ARTICLE COMMANDE Action : UPDATE : '.$commande_bdd['id'].'</info>');
}
//$output->writeln('ETAPE 13 '.$order->OrderID);
} else {
$tab_introuvable[] = "MarketPlace ".$compte->getMarketPlace()->getLibelle()." : ".$compte->getLibelle(
)." Commande : ".$SellingManagerSalesRecordNumber." Produit : ".$ItemID;
$output->writeln('<error>ARTICLE INTROUVABLE '.$ItemID.'</error>');
}
//$this->calculerTotalCommande($commande_bdd['id']);
//if($nouvelle_commande_ebay) $this->calculerTotalCommande($output,$container,$commande_bdd['id'],$tableau_donnee_commande);
}
$output->writeln('total_poids:'.$total_poids);
//exit;
$repo_mode_expedition_poids_transporteur = $this->em->getRepository(ModeExpeditionPoidsTransporteur::class);
$tableau_donnee = [];
$tableau_donnee["total_poids"] = $total_poids;
if ( ! empty($donnees_commande['mode_expedition_id']) and $total_poids > 0) {
$output->writeln('mode_expedition_id:'.$donnees_commande['mode_expedition_id']);
$mode_expedition_poids_transporteur = $repo_mode_expedition_poids_transporteur->getTransporteurParPoids($total_poids * 1000, $donnees_commande['mode_expedition_id']);
if (is_object($mode_expedition_poids_transporteur) && is_object($mode_expedition_poids_transporteur->getTransporteur())) {
$tableau_donnee["transporteur_id"] = $mode_expedition_poids_transporteur->getTransporteur()->getId();
}
}
//taxes
$devise = $this->deviseService->getDevise(trim($order['pricingSummary']['total']['currency']), $output);
if (is_object($devise)) {
$tableau_donnee["devise_id"] = $devise->getId();
}
$tableau_donnee["total_frais_port_ttc"] = floatval($order['pricingSummary']['deliveryCost']['value']);
if ( ! empty($order['pricingSummary']['deliveryDiscount'])) {
$tableau_donnee["total_frais_port_ttc"] += floatval($order['pricingSummary']['deliveryDiscount']['value']);
}
if ($tauxChange != 0) {
$tableau_donnee["total_frais_port_ttc"] = $tableau_donnee["total_frais_port_ttc"] * $tauxChange;
$tableau_donnee["total_frais_port_ttc"] = round($tableau_donnee["total_frais_port_ttc"], 2);
}
$tableau_donnee["total_frais_port"] = $tableau_donnee["total_frais_port_ttc"] * (100 / (100 + floatval($tauxTva)));
$tableau_donnee["total_frais_port"] = round($tableau_donnee["total_frais_port"], 2);
$tableau_donnee["total_tva_frais_port"] = $tableau_donnee["total_frais_port_ttc"] - $tableau_donnee["total_frais_port"];
$tableau_donnee["total_ttc"] = floatval($order['pricingSummary']['total']['value']);
$tableau_donnee["total_ttc_devise"] = floatval($order['pricingSummary']['total']['value']);
$tableau_donnee["total"] = floatval($order['pricingSummary']['priceSubtotal']['value']);
if (array_key_exists('priceDiscount', $order['pricingSummary'])) {
$tableau_donnee["total"] += floatval($order['pricingSummary']['priceDiscount']['value']);
}
/*
if(array_key_exists('deliveryCost', $order['pricingSummary'])){
$tableau_donnee["total"] -= floatval($order['pricingSummary']['deliveryCost']['value']);
}
*/
if ($tauxChange != 0) {
$tableau_donnee["taux_change"] = $tauxChange;
$tableau_donnee["total_ttc"] = $tableau_donnee["total_ttc"] * $tauxChange;
$tableau_donnee["total_ttc"] = round($tableau_donnee["total_ttc"], 3);
$tableau_donnee["total"] = $tableau_donnee["total"] * $tauxChange;
$tableau_donnee["total"] = round($tableau_donnee["total"], 3);
$total_tva_de_la_commande = $total_tva_de_la_commande * $tauxChange;
}
if ($calculerHt) {
$tableau_donnee["total"] -= $total_tva_de_la_commande;
}
print_r($tableau_donnee);
$conn->update('commerciale__commande', $tableau_donnee, ['id' => $commande_bdd['id']]);
}
if ( ! empty($commande_bdd['id']) && ! empty($tableau_donnee_commande["statut_commande_id"]) && $tableau_donnee_commande["statut_commande_id"] != 7) {
$acompte = $repo_acompte->findOneBy(["commande" => $commande_bdd['id']]);
if (1 == 1 && ! is_object($acompte) && $order['orderPaymentStatus'] == 'PAID' && ! empty($tableau_donnee["total_ttc"])) {
switch ($compte->getId()) {
case 11:
$mode_reglement_id = 19;
break;
case 12:
$mode_reglement_id = 20;
break;
case 13:
$mode_reglement_id = 21;
break;
default:
$mode_reglement_id = null;
break;
}
$acompte = [
//'id_import' =>
'date' => $CreatedTime->format('Y-m-d H:i:s'),
'dateReglement' => $CreatedTime->format('Y-m-d H:i:s'),
'commande_id' => $commande_bdd['id'],
'mode_reglement_id' => $mode_reglement_id,
'nomClient' => $fullName,
//'montant' => floatval($order['pricingSummary']['total']['value']),
'montant' => $tableau_donnee["total_ttc"],
'solde' => 0,
'est_parent' => 0,
'operation_diverse' => 0,
'transfert_compta' => 0,
'type_reglement_id' => 1,
'commentaire' => 'Paiement de la commande '.$OrderID,
];
if (is_object($client)) {
$acompte['client_id'] = $client->getId();
$solde = $this->acompteService->getSoldeClient($client);
$acompte['solde'] = $solde;
}
$acompteObj = new Acompte;
$acompteObj->setModeReglement($repo_mode_reglement->find($mode_reglement_id));
$numerotation = $this->numerotationDocumentService->generer($acompteObj);
$acompte['numTraite'] = $numerotation;
$conn->insert('commerciale__acompte', $acompte);
}
}
//echo "LLLLLLL";
//historique
//priorisation?
//pdf?
}
public function getCategories($compteMarketPlace, $category = 0, $output = '')
{
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
//https://developer.ebay.com/api-docs/commerce/taxonomy/resources/methods
//https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategoryTree#_samples
$url = 'https://api.ebay.com/commerce/taxonomy/v1/category_tree/'.$category;
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
'Accept-Encoding: application/gzip',
'Accept-Language: fr-FR',
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
$retour = curl_exec($ch);
return json_decode($retour);
}
public function getDefaultCategoryTreeId($compteMarketPlace, $marketplace_id = 'EBAY_FR', $output = '')
{
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
//https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getDefaultCategoryTreeId#uri.marketplace_id
$url = 'https://api.ebay.com/commerce/taxonomy/v1/get_default_category_tree_id?marketplace_id='.$marketplace_id;
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
'Accept-Encoding: application/gzip',
'Accept-Language: fr-FR',
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
$retour = curl_exec($ch);
return json_decode($retour);
}
public function getCategorySubtree($compteMarketPlace, $category, $output = '')
{
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$cat = $this->getDefaultCategoryTreeId($compteMarketPlace, 'EBAY_FR', $output);
if ( ! is_object($cat)) {
return;
}
//https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategorySubtree
$url = 'https://api.ebay.com/commerce/taxonomy/v1/category_tree/'.$cat->categoryTreeId.'/get_category_subtree?category_id='.$category;
return $this->boucleCategories($compteMarketPlace, $url, $output);
/*
if(is_object($output)) $output->writeln($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
'Accept-Encoding: application/gzip',
'Accept-Language: fr-FR',
));
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
$retour = curl_exec($ch);
return json_decode($retour);
*/
}
private function boucleCategories($compteMarketPlace, $url, $output = '', $tree = [])
{
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
'Accept-Encoding: application/gzip',
'Accept-Language: fr-FR',
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
$retour = curl_exec($ch);
$retour = json_decode($retour);
if (is_object($retour) && ! empty($retour->categorySubtreeNode) && is_object($retour->categorySubtreeNode)) {
if ( ! empty($retour->categorySubtreeNode->category) && is_object(
$retour->categorySubtreeNode->category
) && ! empty($retour->categorySubtreeNode->category->categoryId) && ! empty($retour->categorySubtreeNode->category->categoryName)) {
$tree[] = ['categoryId' => $retour->categorySubtreeNode->category->categoryId, 'categoryName' => $retour->categorySubtreeNode->category->categoryName];
}
if ( ! empty($retour->categorySubtreeNode->parentCategoryTreeNodeHref)) {
$tree = $this->boucleCategories($compteMarketPlace, $retour->categorySubtreeNode->parentCategoryTreeNodeHref, $output, $tree);
}
}
return array_reverse($tree);
}
public function majCategoriesEbay($compte, $output = "")
{
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$marketPlace = $compte->getMarketPlace();
$repo_categorie = $this->em->getRepository(Categorie::class);
$cat = $this->getDefaultCategoryTreeId($compte, 'EBAY_FR', $output);
if (is_object($output)) {
$output->writeln('t1');
}
if (is_object($cat)) {
$categorieRoot = $this->getCategories($compte, $cat->categoryTreeId, $output);
//print_r($categorieRoot);
if (is_object($output)) {
$output->writeln('t2');
}
$parent = null;
if ( ! empty($categorieRoot) && is_object($categorieRoot) && ! empty($categorieRoot->rootCategoryNode) && is_object($categorieRoot->rootCategoryNode)) {
if (is_object($output)) {
$output->writeln('t3');
}
$this->verifierCategorieExiste($conn, $marketPlace, $output, $repo_categorie, $categorieRoot->rootCategoryNode, $parent);
/*
if(is_object($categorieRoot->category)) {
$idImport = $categorieRoot->category->categoryId;
$categoryName = $categorieRoot->category->categoryId;
$categorie = $repo_categorie->findOneBy(array(
'dateSuppression' => NULL,
'idImport' => $idImport,
'marketPlace' => $marketPlace
));
$conn->insert('article__categorie',array(
'date' => (new \Datetime)->format('Y-m-d h:i:s'),
'id_import' => $idImport,
'market_place_id' => $marketPlace->getId(),
'libelle' => $categoryName,
'reference' => $idImport
));
$parent = $conn->lastInsertId();
}
*/
}
}
}
private function verifierCategorieExiste($conn, $marketPlace, $output, $repo_categorie, $category, $parent)
{
//print_r($category);
if (is_object($category->category)) {
$idImport = $category->category->categoryId;
$categoryName = $category->category->categoryName;
$categorie = $repo_categorie->findOneBy([
'dateSuppression' => null,
'idImport' => $idImport,
'marketPlace' => $marketPlace,
]);
if (is_object($categorie)) {
$parent = $categorie->getId();
if (is_object($output)) {
$output->writeln('La catégorie "'.$categoryName.'" existe.');
}
} else {
$conn->insert('article__categorie', [
'date' => (new \Datetime)->format('Y-m-d H:i:s'),
'id_import' => $idImport,
'market_place_id' => $marketPlace->getId(),
'libelle' => $categoryName,
'reference' => $idImport,
'categorie_parent_id' => $parent,
]);
$parent = $conn->lastInsertId();
if (is_object($output)) {
$output->writeln('Création de la catégorie : '.$categoryName);
}
}
}
if ( ! empty($category->childCategoryTreeNodes) && count($category->childCategoryTreeNodes)) {
foreach ($category->childCategoryTreeNodes as $catTmp) {
$this->verifierCategorieExiste($conn, $marketPlace, $output, $repo_categorie, $catTmp, $parent);
}
}
}
public function CreateShippingFulfillment($commande, $ShippingFulfillmentDetails, $output = '')
{
$compteMarketPlace = $commande->getCompteMarketPlace();
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
#https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/shipping_fulfillment/methods/createShippingFulfillment#request.lineItems.lineItemId
//$url = 'https://api.ebay.com/sell/fulfillment/v1/order/'.$commande->getIdImport().'/shipping_fulfillment';
$url = 'https://api.ebay.com/sell/fulfillment/v1/order/'.$commande->getIdImport().'/shipping_fulfillment';
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'Content-Language: fr-FR',
//'Accept-Language: fr-FR',
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($ShippingFulfillmentDetails != '') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ShippingFulfillmentDetails);
}
$retour = curl_exec($ch);
print_r(json_decode($retour));
//return 202;
return curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
public function getOffer($articleMarketPlace, $output = '')
{
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
#https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getOffer
$url = 'https://api.ebay.com/sell/inventory/v1/offer/'.$articleMarketPlace->getIdImport();
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'Content-Language: fr-FR',
//'Accept-Language: fr-FR',
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
print_r($retour);
$output->writeln('getOffer CURLINFO_HTTP_CODE : '.curl_getinfo($ch, CURLINFO_HTTP_CODE));
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
return false;
}
return json_decode($retour);
}
public function getOffers($articleMarketPlace, $output = '')
{
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
#https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getOffer
$url = 'https://api.ebay.com/sell/inventory/v1/offer?';
$url .= 'sku='.$articleMarketPlace->getSku();
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
//'Content-Language: fr-FR',
//'Accept-Language: fr-FR',
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
print_r($retour);
$output->writeln('getOffer CURLINFO_HTTP_CODE : '.curl_getinfo($ch, CURLINFO_HTTP_CODE));
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
return false;
}
return json_decode($retour);
}
public function updateOffer($articleMarketPlace, $output = '')
{
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$post_data = $this->getOffer($articleMarketPlace, $output);
if ( ! $post_data) {
return false;
}
#https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/updateOffer
$url = 'https://api.ebay.com/sell/inventory/v1/offer/'.$articleMarketPlace->getIdImport();
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'Authorization: Bearer '.$authToken,
'Content-Language: fr-FR',
//'Accept-Language: fr-FR',
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//qte 30
//prix 28.9
print_r($post_data);
$post_data['availableQuantity'] = 29;
$post_data['pricingSummary']['price']['value'] = 28.9;
$post_data = json_encode($post_data);
print_r($post_data);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
print_r(json_decode($retour));
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 204) {
return true;
}
return false;
/*
return 202;
return curl_getinfo($ch, CURLINFO_HTTP_CODE);
*/
}
public function GetSellerList($articleMarketPlace = '', $compteMarketPlace = '', $nbHeures = 5, $output)
{
if (empty($compteMarketPlace) && ! empty($articleMarketPlace)) {
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
}
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$request = new Types\GetSellerListRequestType();
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $authToken;
if ( ! empty($articleMarketPlace)) {
$SKUArray = new Types\SKUArrayType();
$SKUArray->SKU[] = $articleMarketPlace->getSku();
$request->SKUArray = $SKUArray;
}
$request->StartTimeFrom = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"))->modify('- '.$nbHeures.' hours');
$request->StartTimeTo = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"));
$response = @$this->getTradingService($compteMarketPlace, $output)->getSellerList($request);
//print_r($response);
return $response;
}
public function reviseFixedPriceItem($articleMarketPlace, $donnees, $output, $authToken = '', $count = 0)
{
//limit api calls
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
if (($compteMarketPlace->getAppelApiHeure() / $compteMarketPlace->getAppelApiHeureLimit() * 100) > 80) {
return;
}
if (($compteMarketPlace->getAppelApiJour() / $compteMarketPlace->getAppelApiJourLimit() * 100) > 80) {
return;
}
if (empty($articleMarketPlace->getIdImport())) {
return;
}
//verifier erreur
$erreurExiste = $this->em->getRepository(ErreurPublicationArticleMarketPlace::class)->findOneBy(['articleMarketPlace' => $articleMarketPlace, 'verifie' => false]);
if ($erreurExiste) {
return;
}
if (empty($authToken)) {
$authToken = $this->getAuthToken($compteMarketPlace, $output);
}
if (empty($authToken)) {
return $authToken;
}
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$output->writeln('t1.2');
$date = (new \Datetime)->setTimezone(new \DateTimeZone("UTC"));
$endTime = $articleMarketPlace->getEndTime();
$mettreAjour = false;
$seuilMiseAjour = 5000;
if ((array_key_exists('quantite', $donnees) && floatval($donnees['quantite']) === $articleMarketPlace->getStockMarketPlace()) || (floatval(
$articleMarketPlace->getStockMarketPlace()
) > $seuilMiseAjour && array_key_exists(
'quantite',
$donnees
) && floatval(
$donnees['quantite']
) > $seuilMiseAjour)) {
$output->writeln('quantite identique sur le market place ou stock > '.$seuilMiseAjour);
$tableau_donnee["statut_article_market_place_id"] = 2;//publié
$tableau_donnee["date_publication_market_place"] = $date->format("Y-m-d H:i:s");
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlace->getId()]);
return;
} elseif ( ! is_object($endTime) || (is_object($endTime) && $date < $endTime)) {
$mettreAjour = true;
} else {
$response = $this->getItem($articleMarketPlace, 'ReturnAll', $authToken);
if ($response->Ack === 'Failure' && $count < 3) {
$count++;
$this->reviseFixedPriceItem($articleMarketPlace, $donnees, $output, '', $count);
}
if ($response->Ack !== 'Failure') {
$output->writeln('t2');
$endTime = $response->Item->ListingDetails->EndTime;
$itemOriginel = $response->Item;
//print_r($endTime);
if (is_object($endTime) && $date > $endTime) {
$output->writeln('Annonce terminée');
$tableau_donnee["statut_article_market_place_id"] = 2;//publié
//$tableau_donnee["statut"]=0;
//$tableau_donnee["visible"]=0;
$tableau_donnee["date_publication_market_place"] = (new \Datetime)->format("Y-m-d H:i:s");
$tableau_donnee["end_time"] = $endTime->format("Y-m-d H:i:s");
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlace->getId()]);
return;
}
if (array_key_exists('quantite', $donnees)) {
$output->writeln('qte bdd '.floatval($donnees['quantite']).' == qte ebay'.$response->Item->Quantity);
}
if (array_key_exists('prix', $donnees)) {
$output->writeln('prix bdd '.floatval($donnees['prix'])).'==? prix ebay'.$response->Item->StartPrice->value;
}
if (array_key_exists('quantite', $donnees) && floatval($donnees['quantite']) == $response->Item->Quantity && array_key_exists(
'prix',
$donnees
) && $response->Item->StartPrice->value == floatval($donnees['prix'])) {
$output->writeln('Pas de modification');
$tableau_donnee["statut_article_market_place_id"] = 2;//publié
$tableau_donnee["date_publication_market_place"] = (new \Datetime)->format("Y-m-d H:i:s");
$tableau_donnee["end_time"] = $endTime->format("Y-m-d H:i:s");
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlace->getId()]);
return;
}
$mettreAjour = true;
}
}
if ($mettreAjour) {
$output->writeln('t3');
$item = new Types\ItemType();
if (array_key_exists('prix', $donnees)) {
//$item->BuyItNowPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
//$item->FloorPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
//$item->CeilingPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
//decommenter celui ci-dessous
//$item->StartPrice = new Types\AmountType(array('value'=>floatval($donnees['prix'])));
if ( ! empty($itemOriginel)) {
$output->writeln("Modification du prix ".$itemOriginel->StartPrice->value.' -> '.floatval($donnees['prix']));
}
}
if (array_key_exists('quantite', $donnees)) {
$item->Quantity = intval($donnees['quantite']);
}
//identifier l'annonce
$item->ItemID = $articleMarketPlace->getIdImport();
//$item->SKU = $articleMarketPlace->getSku();
//Revise item
$request = new Types\ReviseFixedPriceItemRequestType();
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $authToken;
$request->Item = $item;
$response = @$this->getTradingService($compteMarketPlace, $output)->reviseFixedPriceItem($request);
$output->writeln('t4');
if ($response->Ack !== 'Failure') {
$output->writeln('t5');
$output->writeln("The item was successfully revised on eBay.");
$tableau_donnee = [];
$date = new \Datetime();
$tableau_donnee["statut_article_market_place_id"] = 2;//publié
$tableau_donnee["statut"] = 1;
$tableau_donnee["date_publication_market_place"] = $date->format("Y-m-d H:i:s");
if (array_key_exists('quantite', $donnees)) {
$tableau_donnee['stock_market_place'] = intval($donnees['quantite']);
}
$tableau_donnee["end_time"] = $response->EndTime->format("Y-m-d H:i:s");
//$article_market_place->setEndTime($response->EndTime);
//print_r($tableau_donnee);
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlace->getId()]);
$this->supprimerErreur($response->ItemID);
$this->articleMarketPlaceService->creerHistorique($articleMarketPlace, 8, []);
return;
} else {
foreach ($response->Errors as $error) {
if (in_array($error->ErrorCode, [10007, '10007']) && $count < 3) {
$count++;
sleep(1);
$this->reviseFixedPriceItem($articleMarketPlace, $donnees, $output, '', $count);
} elseif (in_array($error->ErrorCode, [291, '291'])) {
$output->writeln('Annonce terminée');
$tableau_donnee["statut_article_market_place_id"] = 2;//publié
//$tableau_donnee["statut"]=0;
//$tableau_donnee["visible"]=0;
$tableau_donnee["date_publication_market_place"] = (new \Datetime)->format("Y-m-d H:i:s");
if ( ! empty($response->EndTime)) {
$tableau_donnee["end_time"] = $response->EndTime->format("Y-m-d H:i:s");
} else {
$tableau_donnee["end_time"] = (new \Datetime)->format("Y-m-d H:i:s");
}
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlace->getId()]);
return;
}
}
$this->creerErreur($response, $item->ItemID, '', 'MarketPlaceEnvoiArticle reviseFixedPriceItem');
$this->articleMarketPlaceService->creerHistorique($articleMarketPlace, 15, []);
}
}
}
public function publierAnnonce($articleId = '', $articleMarketPlaceId = '', $output = '')
{
if (is_object($output)) {
$output->writeln('publierAnnonce');
}
$conn = $this->em->getConnection();
$conn->getConfiguration()->setSQLLogger(null);
$em = $this->em;
$tableau_donnee = [];
$date = new \Datetime();
$tableau_donnee["statut_article_market_place_id"] = 1;// à publier
$tableau_donnee["date_publication_market_place"] = $date->format("Y-m-d H:i:s");
if ( ! empty($articleId)) {
$conn->update('article__article', ['maj_dispo' => 1], ['id' => $articleId]);
$conn->update('market_place__article', $tableau_donnee, ['article_id' => $articleId]);
//getComposantsComposeVirtuel
$repo_article_composant = $em->getRepository(ArticleComposant::class);
$composants = $repo_article_composant->getComposantsComposeVirtuel($articleId)->getQuery()->getResult();
if (count($composants) > 0) {
foreach ($composants as $cp) {
if (is_object($cp->getArticleCompose())) {
$this->publierAnnonce($cp->getArticleCompose()->getId());
}
}
}
} elseif ( ! empty($articleMarketPlaceId)) {
/*
$historique = $service_article_market_place->creerHistorique($articleMarketPlaceId, 3);
if(!empty($historique->getTitre())){
$donneesHisto = array(
'article_market_place_id' => $articleMarketPlaceId
'titre' => $historique->getTitre(),
'message' => $historique->getMessage(),
);
if(is_object($historique->getUtilisateur())) $donneesHisto['utilisateur_id'] = $historique->getUtilisateur()->getId();
$conn->insert('market_place__historique_article_market_place', );
}
*/
$conn->update('market_place__article', $tableau_donnee, ['id' => $articleMarketPlaceId]);
}
}
private function supprimerErreur($idImportArticleMaketPlace, $idArticleMaketPlace = '')
{
$em = $this->em;
$repo_article_market_place = $this->em->getRepository(ArticleMarketPlace::class);
if ($idArticleMaketPlace != '') {
$articleMarketPlace = $repo_article_market_place->find($idArticleMaketPlace);
} else {
$articleMarketPlace = $repo_article_market_place->findOneBy(['idImport' => $idImportArticleMaketPlace]);
}
$erreur = '';
if (is_object($articleMarketPlace)) {
$erreur = $this->em->getRepository(ErreurPublicationArticleMarketPlace::class)->findOneBy(['articleMarketPlace' => $articleMarketPlace, 'verifie' => false]);
}
if (is_object($erreur)) {
echo 'supprimer erreur : id -> '.$erreur->getId().'<br>';
$erreur->setVerifie(true);
$em->persist($erreur);
$em->flush();
}
}
private function creerErreur($response, $idImportArticleMaketPlace, $idArticleMaketPlace = '', $origine = 'MarketPlaceEnvoiArticle')
{
$log = '';
$em = $this->em;
$repo_article_market_place = $this->em->getRepository(ArticleMarketPlace::class);
if ($idArticleMaketPlace != '') {
$articleMarketPlace = $repo_article_market_place->find($idArticleMaketPlace);
} else {
$articleMarketPlace = $repo_article_market_place->findOneBy(['idImport' => $idImportArticleMaketPlace]);
}
$log = '<?xml version="1.0" encoding="UTF-8"?>';
$log .= '<messages>';
foreach ($response->Errors as $error) {
printf(
"%s: %s\n%s\n\n",
$error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning',
$error->ShortMessage,
$error->LongMessage
);
$log .= '<message>';
$error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? $log .= '<type>Error</type>' : $log .= '<type>Warning</type>';
$log .= '<ErrorCode>'.$error->ErrorCode.'</ErrorCode>';
$log .= '<Origine>'.$origine.'</Origine>';
$log .= '<ShortMessage>"'.$error->ShortMessage.'"</ShortMessage>';
$log .= '<LongMessage>"'.str_replace(['<', '>'], '', $error->LongMessage).'"</LongMessage>';
$log .= '</message>';
}
$log .= '</messages>';
$erreur = '';
if (is_object($articleMarketPlace)) {
echo 'erreur articleMarketPlace : '.$articleMarketPlace->getId().'<br>';
$erreur = $this->em->getRepository(ErreurPublicationArticleMarketPlace::class)->findOneBy(['articleMarketPlace' => $articleMarketPlace, 'verifie' => false]);
}
if ( ! is_object($erreur)) {
$erreur = new ErreurPublicationArticleMarketPlace;
$erreur->setVerifie(false);
echo 'creerErreur : nouvelle erreur<br>';
} else {
echo 'creerErreur : id -> '.$erreur->getId().'<br>';
}
$erreur->setLogs($log);
if (is_object($articleMarketPlace)) {
$erreur->setArticleMarketPlace($articleMarketPlace);
$article = $articleMarketPlace->getArticle();
if (is_object($article)) {
$erreur->setArticle($article);
}
}
$em->persist($erreur);
$em->flush();
}
public function uploadFile()
{
/*
POST /FileTransferService HTTP/1.1
Content-type: multipart/related; boundary=
MIMEBoundaryurn_uuid_C0FC77A812E40EAE841226969745133;type="application/xop+xml";start="<0.
urn:uuid:883CA9C91CE9C469D912223894056542>";start-info="text/xml"
X-EBAY-SOA-SERVICE-NAME: FileTransferService
X-EBAY-SOA-OPERATION-NAME: uploadFile
X-EBAY-SOA-SECURITY-TOKEN: ABC...123
X-EBAY-SOA-REQUEST-DATA-FORMAT: XML
X-EBAY-SOA-RESPONSE-DATA-FORMAT: XML
User-Agent: Jakarta Commons-HttpClient/3.1
Host: beta.storage.sandbox.ebay.com:8082
Content-Length: 2680
--MIMEBoundaryurn_uuid_C0FC77A812E40EAE841226969745133
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml; charset=UTF-8"
Content-Transfer-Encoding: binary
Content-ID: <0.urn:uuid:883CA9C91CE9C469D912223894056542>
<?xml version='1.0' encoding='UTF-8'?><uploadFileRequest
xmlns:sct="http://www.ebay.com/soaframework/common/types"
xmlns="http://www.ebay.com/marketplace/services"><taskReferenceId>
5********19</taskReferenceId><fileReferenceId>5********69</fileReferenceId><fileFormat>
gzip</fileFormat><fileAttachment><Data><xop:Include
xmlns:xop="http://www.w3.org/2004/08/xop/include"
href="cid:urn:uuid:EE69C2F1D5C814ADF71222389408640" /></Data> </fileAttachment>
</uploadFileRequest>
--MIMEBoundaryurn_uuid_C0FC77A812E40EAE841226969745133
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <urn:uuid:EE69C2F1D5C814ADF71222389408640>
*/
$compteMarketPlace = $articleMarketPlace->getCompteMarketPlace();
$authToken = $this->getAuthToken($compteMarketPlace);
if (empty($authToken)) {
return $authToken;
}
$post_data = $this->getOffer($articleMarketPlace, $output);
if ( ! $post_data) {
return false;
}
#https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/updateOffer
$url = 'https://api.ebay.com/sell/inventory/v1/offer/'.$articleMarketPlace->getIdImport();
if (is_object($output)) {
$output->writeln($url);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
//'Content-Type: application/json',
//'Accept: application/json',
'X-EBAY-SOA-SECURITY-TOKEN: '.$authToken,
'X-EBAY-SOA-OPERATION-NAME: uploadFile',
//'Accept-Language: fr-FR',
//'X-EBAY-C-MARKETPLACE-ID: EBAY_FR',
//'X-EBAY-C-ENDUSERCTX: affiliateCampaignId=affiliate.trackingId'
]);
//qte 30
//prix 28.9
print_r($post_data);
$post_data['availableQuantity'] = 29;
$post_data['pricingSummary']['price']['value'] = 28.9;
$post_data = json_encode($post_data);
print_r($post_data);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$retour = curl_exec($ch);
print_r(json_decode($retour));
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 204) {
return true;
}
return false;
}
}