/**
  * Links the items (similar/accessory)
  */
 public function link()
 {
     $Request_AddLinkedItems = new PlentySoapRequest_AddLinkedItems();
     $Request_AddLinkedItems->CrosssellingList = array();
     foreach ($this->SHOPWARE_Article->getSimilar() as $Similar) {
         $Object_AddLinkedItems = new PlentySoapObject_AddLinkedItems();
         $Object_AddLinkedItems->Relationship = 'Similar';
         // string
         $Object_AddLinkedItems->CrossItemSKU = PlentymarketsMappingController::getItemByShopwareID($Similar->getId());
         // string
         $Request_AddLinkedItems->CrosssellingList[] = $Object_AddLinkedItems;
     }
     foreach ($this->SHOPWARE_Article->getRelated() as $Related) {
         $Object_AddLinkedItems = new PlentySoapObject_AddLinkedItems();
         $Object_AddLinkedItems->Relationship = 'Accessory';
         // string
         $Object_AddLinkedItems->CrossItemSKU = PlentymarketsMappingController::getItemByShopwareID($Related->getId());
         $Request_AddLinkedItems->CrosssellingList[] = $Object_AddLinkedItems;
     }
     if (!count($Request_AddLinkedItems->CrosssellingList)) {
         return;
     }
     $Request_AddLinkedItems->MainItemSKU = PlentymarketsMappingController::getItemByShopwareID($this->SHOPWARE_Article->getId());
     // string
     // Do the request
     PlentymarketsSoapClient::getInstance()->AddLinkedItems($Request_AddLinkedItems);
 }
 /**
  * Performs the actual import
  *
  * @param integer $lastUpdateTimestamp
  */
 public function run($lastUpdateTimestamp)
 {
     $Request_GetProducers = new PlentySoapRequest_GetProducers();
     $Request_GetProducers->LastUpdateFrom = $lastUpdateTimestamp;
     /** @var PlentySoapResponse_GetProducers $Response_GetProducers */
     $Response_GetProducers = PlentymarketsSoapClient::getInstance()->GetProducers($Request_GetProducers);
     if (!$Response_GetProducers->Success) {
         return;
     }
     foreach ($Response_GetProducers->Producers->item as $Producer) {
         $PlentymarketsImportEntityItemProducer = new PlentymarketsImportEntityItemProducer($Producer);
         $PlentymarketsImportEntityItemProducer->import();
     }
 }
 /**
  * Performs the actual import
  *
  * @param integer $lastUpdateTimestamp
  */
 public function run($lastUpdateTimestamp)
 {
     $Request_GetItemAttributes = new PlentySoapRequest_GetItemAttributes();
     $Request_GetItemAttributes->GetValues = true;
     $Request_GetItemAttributes->LastUpdateFrom = $lastUpdateTimestamp;
     /** @var PlentySoapResponse_GetItemAttributes $Response_GetItemAttributes */
     $Response_GetItemAttributes = PlentymarketsSoapClient::getInstance()->GetItemAttributes($Request_GetItemAttributes);
     if (!$Response_GetItemAttributes->Success) {
         return;
     }
     foreach ($Response_GetItemAttributes->Attributes->item as $Attribute) {
         $PlentymarketsImportEntityItemAttribute = new PlentymarketsImportEntityItemAttribute($Attribute);
         $PlentymarketsImportEntityItemAttribute->import();
     }
     // run import of attributes and attributes value translations
     $mainShops = PlentymarketsUtils::getShopwareMainShops();
     /** @var $mainShop Shopware\Models\Shop\Shop */
     foreach ($mainShops as $mainShop) {
         // get all active languages of the main shop
         $activeLanguages = PlentymarketsTranslation::getShopActiveLanguages($mainShop->getId());
         foreach ($activeLanguages as $key => $language) {
             $Request_GetItemAttributes = new PlentySoapRequest_GetItemAttributes();
             $Request_GetItemAttributes->GetValues = true;
             $Request_GetItemAttributes->LastUpdateFrom = $lastUpdateTimestamp;
             $Request_GetItemAttributes->Lang = PlentymarketsTranslation::getPlentyLocaleFormat($language['locale']);
             /** @var PlentySoapResponse_GetItemAttributes $Response_GetItemAttributes */
             $Response_GetItemAttributes = PlentymarketsSoapClient::getInstance()->GetItemAttributes($Request_GetItemAttributes);
             if ($Response_GetItemAttributes->Success) {
                 foreach ($Response_GetItemAttributes->Attributes->item as $Attribute) {
                     $PlentymarketsImportEntityItemAttribute = new PlentymarketsImportEntityItemAttribute($Attribute);
                     // set the atrribute translations from plenty for the language shops
                     if (!is_null($language['mainShopId'])) {
                         $languageShopID = PlentymarketsTranslation::getLanguageShopID($key, $language['mainShopId']);
                         $PlentymarketsImportEntityItemAttribute->importTranslation($languageShopID);
                     } else {
                         // import translations for the main shop languages
                         $PlentymarketsImportEntityItemAttribute->importTranslation($mainShop->getId());
                     }
                 }
             }
         }
     }
 }
 /**
  * Performs the actual import
  *
  * @param integer $lastUpdateTimestamp
  */
 public function run($lastUpdateTimestamp)
 {
     $Request_GetItemCategoryCatalog = new PlentySoapRequest_GetItemCategoryCatalog();
     $Request_GetItemCategoryCatalog->Lang = 'de';
     $Request_GetItemCategoryCatalog->LastUpdateFrom = $lastUpdateTimestamp;
     $Request_GetItemCategoryCatalog->Page = 0;
     do {
         /** @var PlentySoapResponse_GetItemCategoryCatalog $Response_GetItemCategoryCatalog */
         $Response_GetItemCategoryCatalog = PlentymarketsSoapClient::getInstance()->GetItemCategoryCatalog($Request_GetItemCategoryCatalog);
         foreach ($Response_GetItemCategoryCatalog->Categories->item as $Category) {
             $PlentymarketsImportEntityItemCategory = new PlentymarketsImportEntityItemCategory($Category);
             $PlentymarketsImportEntityItemCategory->import();
         }
     } while (++$Request_GetItemCategoryCatalog->Page < $Response_GetItemCategoryCatalog->Pages);
     $importControllerItemCategoryTree = new PlentymarketsImportControllerItemCategoryTree();
     $importControllerItemCategoryTree->run();
     /** @var \Shopware\Components\Model\CategoryDenormalization $component */
     $component = Shopware()->CategoryDenormalization();
     $component->rebuildCategoryPath();
     $component->removeAllAssignments();
     $component->rebuildAllAssignments();
 }
 /**
  * Does the actual import work
  */
 public function import()
 {
     PlentymarketsLogger::getInstance()->message('Sync:Item:Bundle', 'LastUpdate: ' . date('r', PlentymarketsConfig::getInstance()->getImportItemBundleLastUpdateTimestamp(time())));
     $numberOfBundlesUpdated = 0;
     $timestamp = PlentymarketsConfig::getInstance()->getImportItemBundleLastUpdateTimestamp(1);
     $now = time();
     // Get all bundles
     $Request_GetItemBundles = new PlentySoapRequest_GetItemBundles();
     $Request_GetItemBundles->LastUpdate = $timestamp;
     $Request_GetItemBundles->Page = 0;
     do {
         /** @var PlentySoapResponse_GetItemBundles $Response_GetItemBundles */
         $Response_GetItemBundles = PlentymarketsSoapClient::getInstance()->GetItemBundles($Request_GetItemBundles);
         $pages = max($Response_GetItemBundles->Pages, 1);
         PlentymarketsLogger::getInstance()->message('Sync:Item:Bundle', 'Page: ' . ($Request_GetItemBundles->Page + 1) . '/' . $pages);
         foreach ($Response_GetItemBundles->ItemBundles->item as $PlentySoapObject_Bundle) {
             $PlentymarketsImportEntityItemBundle = new PlentymarketsImportEntityItemBundle($PlentySoapObject_Bundle);
             try {
                 $PlentymarketsImportEntityItemBundle->import();
                 ++$numberOfBundlesUpdated;
             } catch (PlentymarketsImportException $e) {
                 PyLog()->error('Sync:Item:Bundle', $e->getMessage(), $e->getCode());
             }
         }
     } while (++$Request_GetItemBundles->Page < $Response_GetItemBundles->Pages);
     PlentymarketsConfig::getInstance()->setImportItemBundleLastUpdateTimestamp($now);
     // Log
     if ($numberOfBundlesUpdated == 0) {
         PlentymarketsLogger::getInstance()->message('Sync:Item:Bundle', 'No item bundle has been updated or created.');
     } else {
         if ($numberOfBundlesUpdated == 1) {
             PlentymarketsLogger::getInstance()->message('Sync:Item:Bundle', '1 item bundle has been updated or created.');
         } else {
             PlentymarketsLogger::getInstance()->message('Sync:Item:Bundle', $numberOfBundlesUpdated . ' item bundles have been updated or created.');
         }
     }
 }
 /**
  * Imports the linked items
  *
  */
 public function run()
 {
     foreach (array_chunk($this->itemIds, 100) as $chunk) {
         $Request_GetLinkedItems = new PlentySoapRequest_GetLinkedItems();
         $Request_GetLinkedItems->ItemsList = array();
         //
         foreach ($chunk as $itemId) {
             $Object_GetLinkedItems = new PlentySoapObject_GetLinkedItems();
             $Object_GetLinkedItems->ItemID = $itemId;
             $Request_GetLinkedItems->ItemsList[] = $Object_GetLinkedItems;
         }
         /** @var PlentySoapResponse_GetLinkedItems $Response_GetLinkedItems */
         $Response_GetLinkedItems = PlentymarketsSoapClient::getInstance()->GetLinkedItems($Request_GetLinkedItems);
         /** @var PlentySoapResponseObject_GetLinkedItems $Item */
         foreach ($Response_GetLinkedItems->Items->item as $Item) {
             try {
                 $SHOPWARE_itemId = PlentymarketsMappingController::getItemByPlentyID($Item->ItemID);
             } catch (PlentymarketsMappingExceptionNotExistant $E) {
                 continue;
             }
             $PlentymarketsImportEntityItemLinked = new PlentymarketsImportEntityItemLinked($SHOPWARE_itemId, $Item->LinkedItems);
             $PlentymarketsImportEntityItemLinked->link();
         }
     }
 }
 /**
  * Public import handler method
  *
  */
 public function import()
 {
     $this->prepare();
     // Helper
     $numberOfOrdersUpdated = 0;
     do {
         // Force Update
         //$this->Request_SearchOrders->LastUpdateFrom = ($this->Request_SearchOrders->LastUpdateFrom - (3600*1));
         $Response_SearchOrders = PlentymarketsSoapClient::getInstance()->SearchOrders($this->Request_SearchOrders);
         $pages = max($Response_SearchOrders->Pages, 1);
         $this->log('Page: ' . ($this->Request_SearchOrders->Page + 1) . '/' . $pages);
         if ($Response_SearchOrders->Success == false) {
             $this->log('Failed', 'error');
             break;
         }
         $this->log('Received ' . count($Response_SearchOrders->Orders->item) . ' items');
         foreach ($Response_SearchOrders->Orders->item as $Order) {
             /** @var PlentySoapObject_OrderHead $Order */
             $Order = $Order->OrderHead;
             try {
                 $orderId = $Order->ExternalOrderID;
                 if (strstr($orderId, 'Swag/') === false) {
                     $this->log('The sales order with the external order id ' . $Order->ExternalOrderID . ' could not be updated because it isn\'t a shopware order.', 'error');
                     continue;
                 }
                 $SHOPWARE_orderId = PlentymarketsUtils::getShopwareIDFromExternalOrderID($orderId);
                 if ($SHOPWARE_orderId <= 0) {
                     $this->log('The sales order with the external order id ' . $Order->ExternalOrderID . ' could not be updated.', 'error');
                     continue;
                 }
                 $this->handle($SHOPWARE_orderId, $Order);
                 $this->log('The sales order with the id ' . $orderId . ' has been updated.');
                 $db = Shopware()->Db();
                 $r = $db->executeUpdate("UPDATE `s_order` SET trackingcode = '" . $Order->PackageNumber . "' WHERE `id` = " . $SHOPWARE_orderId);
                 $this->log('Setting the package number ' . $Order->PackageNumber . ' for the order ' . $SHOPWARE_orderId);
                 ++$numberOfOrdersUpdated;
             } catch (Exception $E) {
                 $this->log('The sales order with the external order id ' . $Order->ExternalOrderID . ' could not be updated.', 'error');
                 $this->log($E->getMessage(), 'error');
             }
         }
     } while (++$this->Request_SearchOrders->Page < $Response_SearchOrders->Pages);
     //
     $this->log($numberOfOrdersUpdated . ' sales orders have been updated.');
 }
 /**
  * Export the missing producers
  */
 protected function doExport()
 {
     $producers = array();
     $producerNameMappingShopware = array();
     $supplierRepository = Shopware()->Models()->getRepository('Shopware\\Models\\Article\\Supplier');
     $Request_SetProducers = new PlentySoapRequest_SetProducers();
     /** @var Shopware\Models\Article\Supplier $Supplier */
     foreach ($supplierRepository->findAll() as $Supplier) {
         $Object_SetProducer = new PlentySoapObject_Producer();
         if (array_key_exists($Supplier->getName(), $this->PLENTY_name2ID)) {
             PlentymarketsMappingController::addProducer($Supplier->getId(), $this->PLENTY_name2ID[$Supplier->getName()]);
         } else {
             // Request object
             $Object_SetProducer->ProducerExternalName = $Supplier->getName();
             $Object_SetProducer->ProducerName = $Supplier->getName();
             $Object_SetProducer->ProducerHomepage = $Supplier->getLink();
             // Export-array
             $producers[] = $Object_SetProducer;
             // Save name and id for the mapping
             $producerNameMappingShopware[$Supplier->getName()] = $Supplier->getId();
         }
     }
     // Chunkify since the call can only handly 50 producers at a time
     $chunks = array_chunk($producers, 50);
     foreach ($chunks as $chunk) {
         // Set the request
         $Request_SetProducers->Producers = $chunk;
         // Do the call
         $Response_SetProducers = PlentymarketsSoapClient::getInstance()->SetProducers($Request_SetProducers);
         //
         if (!$Response_SetProducers->Success) {
             throw new PlentymarketsExportException('The item producers could not be created', 2931);
         }
         // Create mapping
         foreach ($Response_SetProducers->ResponseMessages->item as $ResponseMessage) {
             PlentymarketsMappingController::addProducer($producerNameMappingShopware[$ResponseMessage->IdentificationValue], $ResponseMessage->SuccessMessages->item[0]->Value);
         }
     }
 }
コード例 #9
0
 /**
  * Checks the entered credentials data
  */
 public function testApiCredentialsAction()
 {
     try {
         $wsdl = $this->Request()->ApiWsdl . '/plenty/api/soap/version110/?xml';
         $Client = PlentymarketsSoapClient::getTestInstance($wsdl, $this->Request()->ApiUsername, $this->Request()->ApiPassword);
     } catch (Exception $E) {
         $this->View()->assign(array('success' => false, 'message' => $E->getMessage()));
         return;
     }
     $this->View()->assign(array('success' => true, 'data' => $Client->GetServerTime()));
 }
 /**
  * Imports the item bundle
  *
  * @throws Exception
  */
 protected function importBundle()
 {
     // Get the bundle head
     $Request_GetItemsBase = new PlentySoapRequest_GetItemsBase();
     $Request_GetItemsBase->GetAttributeValueSets = false;
     $Request_GetItemsBase->GetCategories = false;
     $Request_GetItemsBase->GetCategoryNames = false;
     $Request_GetItemsBase->GetItemAttributeMarkup = false;
     $Request_GetItemsBase->GetItemOthers = false;
     $Request_GetItemsBase->GetItemProperties = false;
     $Request_GetItemsBase->GetItemSuppliers = false;
     $Request_GetItemsBase->GetItemURL = 0;
     $Request_GetItemsBase->GetLongDescription = false;
     $Request_GetItemsBase->GetMetaDescription = false;
     $Request_GetItemsBase->GetShortDescription = false;
     $Request_GetItemsBase->GetTechnicalData = false;
     $Request_GetItemsBase->ItemID = $this->PLENTY_bundleHeadId;
     $Request_GetItemsBase->Page = 0;
     /** @var PlentySoapResponse_GetItemsBase $Response_GetItemsBase */
     $Response_GetItemsBase = PlentymarketsSoapClient::getInstance()->GetItemsBase($Request_GetItemsBase);
     if ($Response_GetItemsBase->Success == false || !isset($Response_GetItemsBase->ItemsBase->item[0])) {
         throw new PlentymarketsImportException('The item bundle with SKU »' . $this->PLENTY_bundle->SKU . '« can not be imported (SOAP call failed).', 3701);
     }
     /** @var PlentySoapObject_ItemBase $ItemBase */
     $ItemBase = $Response_GetItemsBase->ItemsBase->item[0];
     try {
         // Get the existing bundle
         $shopwareBundleId = PlentymarketsMappingController::getItemBundleByPlentyID($this->PLENTY_bundleHeadId);
         /** @var Shopware\CustomModels\Bundle\Bundle $Bundle */
         $Bundle = Shopware()->Models()->find('Shopware\\CustomModels\\Bundle\\Bundle', $shopwareBundleId);
         $currentShopwareBundleHeadItemDetailId = $Bundle->getArticle()->getMainDetail()->getId();
         if (!isset($this->SHOPWARE_bundleItemDetailList[$currentShopwareBundleHeadItemDetailId])) {
             // If the item which is the bundle head in shopware
             // has been removed in plentymarkets, the bundle has to get a new
             // head item. If this is not possible, the bundle will be delete.
             try {
                 $mainDetail = $this->getShopwareBundleItemDetail();
                 /** @var Shopware\Models\Article\Article $Article */
                 $Article = $mainDetail->getArticle();
                 PyLog()->message('Sync:Item:Bundle', 'The item »' . $Article->getName() . '« with the number »' . $mainDetail->getNumber() . '« is now the master item of the item bundle with the number »' . $Bundle->getNumber() . '«.');
                 $Bundle->setArticle($Article);
             } catch (PlentymarketsImportException $e) {
                 PlentymarketsMappingController::deleteItemBundleByShopwareID($Bundle->getId());
                 PyLog()->message('Sync:Item:Bundle', 'The item bundle with the number »' . $Bundle->getNumber() . '« will be deleted because no item can be identified as the master item. The previous master item with the number »' . $Bundle->getArticle()->getMainDetail()->getNumber() . '« is no longer part of the item bundle.');
                 // Delete the bundle
                 Shopware()->Models()->remove($Bundle);
                 Shopware()->Models()->flush();
                 throw $e;
             }
         }
         $action = 'update';
     } catch (PlentymarketsMappingExceptionNotExistant $E) {
         $action = 'create';
         // Create a new one
         $Bundle = new Shopware\CustomModels\Bundle\Bundle();
         $mainDetail = $this->getShopwareBundleItemDetail();
         /** @var Shopware\Models\Article\Article $Article */
         $Article = $mainDetail->getArticle();
         PyLog()->message('Sync:Item:Bundle', 'The item »' . $Article->getName() . '« with the number »' . $mainDetail->getNumber() . '« will be the master item of the item bundle with the number »' . $ItemBase->ItemNo . '«.');
         // Set the stuff which needs to be set just one
         $Bundle->setArticle($Article);
         $Bundle->setType(1);
         $Bundle->setDiscountType('abs');
         $Bundle->setQuantity(0);
         $Bundle->setCreated();
         $Bundle->setSells(0);
         if (method_exists($Bundle, 'setDisplayGlobal')) {
             $Bundle->setDisplayGlobal(true);
         }
     }
     //
     $Bundle->setName($ItemBase->Texts->Name);
     $Bundle->setShowName(0);
     $Bundle->setNumber($ItemBase->ItemNo);
     $isLimited = $ItemBase->Stock->Limitation == 1;
     $Bundle->setLimited($isLimited);
     $isActive = $ItemBase->Availability->Inactive == 0 && $ItemBase->Availability->Webshop == 1;
     $Bundle->setActive($isActive);
     /**@var Shopware\Models\Customer\Group $CG */
     $CG = $this->getCustomerGroup();
     $shopwareBundleHeadItemId = $Bundle->getArticle()->getId();
     $items = array();
     foreach ($Bundle->getArticles() as $item) {
         /** @var Shopware\CustomModels\Bundle\Article $item */
         $itemDetailId = $item->getArticleDetail()->getId();
         // Not in the bundle or already done
         if (!isset($this->SHOPWARE_bundleItemDetailList[$itemDetailId])) {
             continue;
         }
         $quantity = $this->SHOPWARE_bundleItemDetailList[$itemDetailId]['quantity'];
         // If it is also the main item, the quantity needs to be reduced by one
         if ($item->getArticleDetail()->getArticle()->getId() == $shopwareBundleHeadItemId) {
             // If there is just one, the item is skipped since it is the HEAD - it will not be added as an item
             if ($quantity == 1) {
                 unset($this->SHOPWARE_bundleItemDetailList[$itemDetailId]);
                 continue;
             }
             // If the amount is higher - reduce item - the item is the HEAD and inside the bundle
             // in plenty it is just inside the bundle
             $quantity -= 1;
         }
         // Unset the detail - the rest of this array will be added as new items to the bundle
         unset($this->SHOPWARE_bundleItemDetailList[$itemDetailId]);
         // Update the quantity if changed
         if ($item->getQuantity() != $quantity) {
             $item->setQuantity($quantity);
         }
         $items[] = $item;
     }
     // Add all items, which aren't yet in the bundle
     foreach ($this->SHOPWARE_bundleItemDetailList as $config) {
         /** @var Shopware\Models\Article\Detail $detail */
         $detail = $config['detail'];
         // If the head is inside the bundle too, the amount needs to be reduced
         if ($detail->getArticle()->getId() == $shopwareBundleHeadItemId) {
             if ($config['quantity'] > 1) {
                 $config['quantity'] -= 1;
             } else {
                 if ($config['quantity'] == 1) {
                     continue;
                 }
             }
         }
         $ArticleNew = new Shopware\CustomModels\Bundle\Article();
         $ItemDetail = $detail;
         $quantity = $config['quantity'];
         $ArticleNew->setArticleDetail($ItemDetail);
         $ArticleNew->setQuantity($quantity);
         $items[] = $ArticleNew;
     }
     // Set the bundle items
     $Bundle->setArticles($items);
     $newPrice = $ItemBase->PriceSet->Price;
     $newPrice /= (100 + $ItemBase->PriceSet->VAT) / 100;
     $isPriceFound = false;
     $prices = array();
     foreach ($Bundle->getPrices() as $price) {
         /** @var Shopware\CustomModels\Bundle\Price $price */
         if ($price->getCustomerGroup()->getKey() == $CG->getKey()) {
             $price->setPrice($newPrice);
             $isPriceFound = true;
         }
         $prices[] = $price;
     }
     if (!$isPriceFound) {
         $Price = new Shopware\CustomModels\Bundle\Price();
         $Price->setBundle($Bundle);
         $Price->setCustomerGroup($CG);
         $Price->setPrice($newPrice);
         $prices[] = $Price;
         $Bundle->setPrices($prices);
     }
     $Bundle->setCustomerGroups(array($CG));
     Shopware()->Models()->persist($Bundle);
     Shopware()->Models()->flush();
     if ($action == 'create') {
         PlentymarketsMappingController::addItemBundle($Bundle->getId(), $this->PLENTY_bundleHeadId);
         PyLog()->message('Sync:Item:Bundle', 'The item bundle »' . $ItemBase->Texts->Name . '« with the number »' . $ItemBase->ItemNo . '« has been created');
     } else {
         PyLog()->message('Sync:Item:Bundle', 'The item bundle »' . $ItemBase->Texts->Name . '« with the number »' . $ItemBase->ItemNo . '« has been updated');
     }
 }
 /**
  * Export the missing attribtues to plentymarkets and save the mapping
  */
 protected function doExport()
 {
     // Repository
     $Repository = Shopware()->Models()->getRepository('Shopware\\Models\\Article\\Configurator\\Group');
     // Chunk configuration
     $chunk = 0;
     $size = PlentymarketsConfig::getInstance()->getInitialExportChunkSize(PlentymarketsExportController::DEFAULT_CHUNK_SIZE);
     do {
         PlentymarketsLogger::getInstance()->message('Export:Initial:Attribute', 'Chunk: ' . ($chunk + 1));
         $Groups = $Repository->findBy(array(), null, $size, $chunk * $size);
         /** @var Shopware\Models\Article\Configurator\Group $Attribute */
         foreach ($Groups as $Attribute) {
             $Request_SetItemAttributes = new PlentySoapRequest_SetItemAttributes();
             $Object_SetItemAttribute = new PlentySoapObject_SetItemAttribute();
             $Object_SetItemAttribute->BackendName = sprintf('%s (Sw %d)', $Attribute->getName(), $Attribute->getId());
             $Object_SetItemAttribute->FrontendLang = 'de';
             $Object_SetItemAttribute->FrontendName = $Attribute->getName();
             $Object_SetItemAttribute->Position = $Attribute->getPosition();
             try {
                 $attributeIdAdded = PlentymarketsMappingController::getAttributeGroupByShopwareID($Attribute->getId());
             } catch (PlentymarketsMappingExceptionNotExistant $E) {
                 if (isset($this->PLENTY_name2ID[strtolower($Object_SetItemAttribute->BackendName)])) {
                     $attributeIdAdded = $this->PLENTY_name2ID[strtolower($Object_SetItemAttribute->BackendName)];
                 } else {
                     $Request_SetItemAttributes->Attributes[] = $Object_SetItemAttribute;
                     $Response = PlentymarketsSoapClient::getInstance()->SetItemAttributes($Request_SetItemAttributes);
                     if (!$Response->Success) {
                         throw new PlentymarketsExportException('The item attribute »' . $Object_SetItemAttribute->BackendName . '« could not be created', 2911);
                     }
                     $attributeIdAdded = (int) $Response->ResponseMessages->item[0]->SuccessMessages->item[0]->Value;
                 }
                 // Add the mapping
                 PlentymarketsMappingController::addAttributeGroup($Attribute->getId(), $attributeIdAdded);
                 $this->exportAttributeTranslations($Attribute->getId(), $attributeIdAdded);
             }
             // Values
             /** @var Shopware\Models\Article\Configurator\Option $AttributeValue */
             foreach ($Attribute->getOptions() as $AttributeValue) {
                 $Request_SetItemAttributes = new PlentySoapRequest_SetItemAttributes();
                 $Object_SetItemAttribute = new PlentySoapObject_SetItemAttribute();
                 $Object_SetItemAttribute->Id = $attributeIdAdded;
                 $Object_SetItemAttributeValue = new PlentySoapObject_SetItemAttributeValue();
                 $Object_SetItemAttributeValue->BackendName = sprintf('%s (Sw %d)', $AttributeValue->getName(), $AttributeValue->getId());
                 $Object_SetItemAttributeValue->FrontendName = $AttributeValue->getName();
                 $Object_SetItemAttributeValue->Position = $AttributeValue->getPosition();
                 $Object_SetItemAttribute->Values[] = $Object_SetItemAttributeValue;
                 $Request_SetItemAttributes->Attributes[] = $Object_SetItemAttribute;
                 try {
                     PlentymarketsMappingController::getAttributeOptionByShopwareID($AttributeValue->getId());
                 } catch (PlentymarketsMappingExceptionNotExistant $E) {
                     // Workaround
                     $checknameValue = strtolower(str_replace(',', '.', $Object_SetItemAttributeValue->BackendName));
                     if (isset($this->PLENTY_idAndValueName2ID[$attributeIdAdded][$checknameValue])) {
                         PlentymarketsMappingController::addAttributeOption($AttributeValue->getId(), $this->PLENTY_idAndValueName2ID[$attributeIdAdded][$checknameValue]);
                     } else {
                         $Response = PlentymarketsSoapClient::getInstance()->SetItemAttributes($Request_SetItemAttributes);
                         if (!$Response->Success) {
                             throw new PlentymarketsExportException('The item attribute option »' . $Object_SetItemAttributeValue->BackendName . '« could not be created', 2912);
                         }
                         foreach ($Response->ResponseMessages->item[0]->SuccessMessages->item as $MessageItem) {
                             if ($MessageItem->Key == 'AttributeValueID') {
                                 PlentymarketsMappingController::addAttributeOption($AttributeValue->getId(), $MessageItem->Value);
                                 $this->exportAttributeValuesTranslations($attributeIdAdded, $AttributeValue->getId(), $MessageItem->Value);
                             }
                         }
                     }
                 }
             }
         }
         ++$chunk;
     } while (!empty($Groups) && count($Groups) == $size);
 }
 /**
  * Exports the items of the bundle
  *
  * todo: max 50
  * todo: analyse response
  */
 protected function exportItems()
 {
     $Request_AddItemsToBundle = new PlentySoapRequest_AddItemsToBundle();
     $Request_AddItemsToBundle->Bundles = array();
     $Object_AddBundle = new PlentySoapObject_AddBundle();
     $Object_AddBundle->BundleItems = array();
     foreach ($this->PLENTY_bundleSkuList as $sku => $quantity) {
         $Object_AddBundleItem = new PlentySoapObject_AddBundleItem();
         $Object_AddBundleItem->ItemSKU = $sku;
         $Object_AddBundleItem->Quantity = $quantity;
         $Object_AddBundle->BundleItems[] = $Object_AddBundleItem;
     }
     $Object_AddBundle->BundleSKU = $this->PLENTY_bundleHeadId;
     // string
     $Request_AddItemsToBundle->Bundles[] = $Object_AddBundle;
     PlentymarketsSoapClient::getInstance()->AddItemsToBundle($Request_AddItemsToBundle);
     $numberAdded = count($Object_AddBundle->BundleItems);
     PlentymarketsLogger::getInstance()->message('Export:Initial:Item:Bundle', $numberAdded . ' items have been added to the item bundle with the number »' . $this->SHOPWARE_bundle->getNumber() . '«.');
 }
 /**
  * Returns an instance
  * @return PlentymarketsSoapClient
  */
 public static function getInstance()
 {
     if (!self::$Instance instanceof self) {
         // Config
         $PlentymarketsConfig = PlentymarketsConfig::getInstance();
         // WSDL
         $wsdl = $PlentymarketsConfig->getApiWsdl() . '/plenty/api/soap/version114/?xml';
         //
         self::$Instance = new self($wsdl, $PlentymarketsConfig->getApiUsername(), $PlentymarketsConfig->getApiPassword());
     }
     return self::$Instance;
 }
 /**
  * Export the order
  */
 protected function exportOrder()
 {
     $VariantResource = self::getVariantApi();
     // Build the Request
     $Request_AddOrders = new PlentySoapRequest_AddOrders();
     $Request_AddOrders->Orders = array();
     //
     $Object_Order = new PlentySoapObject_Order();
     //
     $methodOfPayment = $this->getMethodOfPaymentId();
     if ($methodOfPayment == MOP_AMAZON_PAYMENT) {
         $externalOrderID = sprintf('Swag/%d/%s/%s', $this->Order->getId(), $this->Order->getNumber(), $this->Order->getTransactionId());
     } else {
         $externalOrderID = sprintf('Swag/%d/%s', $this->Order->getId(), $this->Order->getNumber());
     }
     $isOrderNet = (bool) $this->Order->getNet() || (bool) $this->Order->getTaxFree();
     // Order head
     $Object_OrderHead = new PlentySoapObject_OrderHead();
     $Object_OrderHead->Currency = PlentymarketsMappingController::getCurrencyByShopwareID($this->Order->getCurrency());
     $Object_OrderHead->CustomerID = $this->PLENTY_customerID;
     $Object_OrderHead->DeliveryAddressID = $this->PLENTY_addressDispatchID;
     $Object_OrderHead->ExternalOrderID = $externalOrderID;
     $Object_OrderHead->IsNetto = $isOrderNet;
     $Object_OrderHead->Marking1ID = PlentymarketsConfig::getInstance()->getOrderMarking1(null);
     $Object_OrderHead->MethodOfPaymentID = $this->getMethodOfPaymentId();
     $Object_OrderHead->OrderTimestamp = $this->getOrderTimestamp();
     $Object_OrderHead->OrderType = 'order';
     $Object_OrderHead->ResponsibleID = PlentymarketsConfig::getInstance()->getOrderUserID(null);
     $Object_OrderHead->ShippingCosts = $this->getShippingCosts();
     $Object_OrderHead->ShippingProfileID = $this->getParcelServicePresetId();
     $Object_OrderHead->StoreID = $this->getShopId();
     $Object_OrderHead->ReferrerID = $this->getReferrerId();
     $Object_Order->OrderHead = $Object_OrderHead;
     // Order infos
     $Object_OrderHead->OrderInfos = array();
     if ($Object_OrderHead->MethodOfPaymentID == MOP_DEBIT) {
         $Customer = $this->Order->getCustomer();
         if ($Customer) {
             $Debit = $Customer->getDebit();
             if ($Debit && $Debit->getAccountHolder()) {
                 $info = 'Account holder: ' . $Debit->getAccountHolder() . chr(10);
                 $info .= 'Bank name: ' . $Debit->getBankName() . chr(10);
                 $info .= 'Bank code: ' . $Debit->getBankCode() . chr(10);
                 $info .= 'Account number: ' . $Debit->getAccount() . chr(10);
                 $Object_OrderInfo = new PlentySoapObject_OrderInfo();
                 $Object_OrderInfo->Info = $info;
                 $Object_OrderInfo->InfoCustomer = 0;
                 $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
                 $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
             }
             $PaymentInstances = $Customer->getPaymentInstances();
             if ($PaymentInstances) {
                 foreach ($PaymentInstances as $PaymentInstance) {
                     if ($this->Order->getId() === $PaymentInstance->getOrder()->getId()) {
                         $Object_BankData = new PlentySoapObject_BankData();
                         $Object_BankData->OwnerFirstname = $PaymentInstance->getFirstName();
                         $Object_BankData->OwnerLastname = $PaymentInstance->getLastName();
                         $Object_BankData->BankName = $PaymentInstance->getBankName();
                         $Object_BankData->IBAN = $PaymentInstance->getIban();
                         $Object_BankData->BIC = $PaymentInstance->getBic();
                         $Object_SetBankCreditCardData = new PlentySoapObject_SetBankCreditCardData();
                         $Object_SetBankCreditCardData->CustomerID = $this->PLENTY_customerID;
                         $Object_SetBankCreditCardData->BankData = $Object_BankData;
                         $Request_SetBankCreditCardData = new PlentySoapRequest_SetBankCreditCardData();
                         $Request_SetBankCreditCardData->CustomerData[] = $Object_SetBankCreditCardData;
                         $Response_SetBankCreditCardData = PlentymarketsSoapClient::getInstance()->SetBankCreditCardData($Request_SetBankCreditCardData);
                         if (!$Response_SetBankCreditCardData->Success) {
                             // Set the error end quit
                             $this->setError(self::CODE_ERROR_SOAP);
                             throw new PlentymarketsExportEntityException('The order with the number »' . $this->Order->getNumber() . '« could not be exported');
                         }
                     }
                 }
             }
         }
     }
     if ($this->Order->getInternalComment()) {
         $Object_OrderInfo = new PlentySoapObject_OrderInfo();
         $Object_OrderInfo->Info = $this->Order->getInternalComment();
         $Object_OrderInfo->InfoCustomer = 0;
         $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
         $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
     }
     if ($this->Order->getCustomerComment()) {
         $Object_OrderInfo = new PlentySoapObject_OrderInfo();
         $Object_OrderInfo->Info = $this->Order->getCustomerComment();
         $Object_OrderInfo->InfoCustomer = 1;
         $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
         $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
     }
     if ($this->Order->getComment()) {
         $Object_OrderInfo = new PlentySoapObject_OrderInfo();
         $Object_OrderInfo->Info = $this->Order->getComment();
         $Object_OrderInfo->InfoCustomer = 1;
         $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
         $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
     }
     $Object_Order->OrderItems = array();
     /** @var Shopware\Models\Order\Detail $Item */
     foreach ($this->Order->getDetails() as $Item) {
         $number = $Item->getArticleNumber();
         $itemText = '';
         // Variant
         try {
             $itemId = null;
             try {
                 // get the detail id by the order number
                 $articleDetailID = $VariantResource->getIdFromNumber($Item->getArticleNumber());
             } catch (Exception $E) {
                 $articleDetailID = -1;
             }
             // get the sku from the detail id
             $sku = PlentymarketsMappingController::getItemVariantByShopwareID($articleDetailID);
         } catch (PlentymarketsMappingExceptionNotExistant $E) {
             // Base item
             try {
                 $itemId = PlentymarketsMappingController::getItemByShopwareID($Item->getArticleId());
                 $sku = null;
             } catch (PlentymarketsMappingExceptionNotExistant $E) {
                 $itemId = -2;
                 $sku = null;
                 // Mandatory because there will be no mapping to any item
                 $itemText = $Item->getArticleName();
             }
         }
         //
         if ($itemId > 0 || !empty($sku)) {
             if (PlentymarketsConfig::getInstance()->getOrderItemTextSyncActionID(EXPORT_ORDER_ITEM_TEXT_SYNC) == EXPORT_ORDER_ITEM_TEXT_SYNC) {
                 $itemText = $Item->getArticleName();
             } else {
                 $itemText = null;
             }
         }
         // Coupon
         if ($Item->getMode() == 2) {
             $itemId = -1;
             $rowType = 'Coupon';
         }
         // Additional coupon identifiers für 3rd party plugins
         $couponIdentifiers = PyConf()->get('OrderAdditionalCouponIdentifiers', '');
         $couponIdentifiers = explode('|', $couponIdentifiers);
         if (in_array($number, $couponIdentifiers)) {
             $itemId = -1;
             $rowType = 'Coupon';
         } else {
             // PAYONE fix
             if ($number == 'SHIPPING' && !$Object_OrderHead->ShippingCosts) {
                 $Object_OrderHead->ShippingCosts = $Item->getPrice();
                 continue;
             }
             $discountNumber = Shopware()->Config()->get('discountnumber');
             $surchargeNumber = Shopware()->Config()->get('surchargenumber');
             $paymentSurchargeNumber = Shopware()->Config()->get('paymentsurchargenumber');
             $paymentSurchargeAbsoluteNumber = Shopware()->Config()->get('paymentSurchargeAbsoluteNumber');
             $shippingDiscountNumber = Shopware()->Config()->get('shippingdiscountnumber');
             switch ($number) {
                 case $paymentSurchargeNumber:
                 case $paymentSurchargeAbsoluteNumber:
                     $rowType = 'SurchargeForPaymentMethod';
                     break;
                 case $discountNumber:
                     $rowType = 'Discount';
                     break;
                 case $surchargeNumber:
                     $rowType = 'Surcharge';
                     break;
                 case $shippingDiscountNumber:
                     $rowType = 'SurchargeForShippingMethod';
                     break;
                 default:
                     $rowType = 'Default';
                     break;
             }
         }
         if ($isOrderNet) {
             // Calculate the gross amount (needed by plentymakets even though it is a net sales order)
             $itemPrice = $Item->getPrice() * ((100 + (double) $Item->getTaxRate()) / 100);
         } else {
             $itemPrice = $Item->getPrice();
         }
         $Object_OrderItem = new PlentySoapObject_OrderItem();
         $Object_OrderItem->ExternalOrderItemID = $number;
         $Object_OrderItem->ItemID = $itemId;
         $Object_OrderItem->ReferrerID = $Object_OrderHead->ReferrerID;
         $Object_OrderItem->ItemText = $itemText;
         $Object_OrderItem->Price = $itemPrice;
         $Object_OrderItem->Quantity = $Item->getQuantity();
         $Object_OrderItem->SKU = $sku;
         $Object_OrderItem->VAT = $Item->getTaxRate();
         $Object_OrderItem->RowType = $rowType;
         $Object_Order->OrderItems[] = $Object_OrderItem;
     }
     $Request_AddOrders->Orders[] = $Object_Order;
     // Do the request
     $Response_AddOrders = PlentymarketsSoapClient::getInstance()->AddOrders($Request_AddOrders);
     if (!$Response_AddOrders->Success) {
         // Set the error end quit
         $this->setError(self::CODE_ERROR_SOAP);
         throw new PlentymarketsExportEntityException('The order with the number »' . $this->Order->getNumber() . '« could not be exported', 4010);
     }
     //
     $plentyOrderID = null;
     $plentyOrderStatus = 0.0;
     foreach ($Response_AddOrders->ResponseMessages->item[0]->SuccessMessages->item as $SuccessMessage) {
         switch ($SuccessMessage->Key) {
             case 'OrderID':
                 $plentyOrderID = (int) $SuccessMessage->Value;
                 break;
             case 'Status':
                 $plentyOrderStatus = (double) $SuccessMessage->Value;
                 break;
         }
     }
     if ($plentyOrderID && $plentyOrderStatus) {
         $this->setSuccess($plentyOrderID, $plentyOrderStatus);
     } else {
         // Set the error end quit
         $this->setError(self::CODE_ERROR_SOAP);
         throw new PlentymarketsExportEntityException('The order with the number »' . $this->Order->getNumber() . '« could not be exported (no order id or order status respectively)', 4020);
     }
     $paymentStatusPaid = explode('|', PlentymarketsConfig::getInstance()->getOrderPaidStatusID(12));
     // Directly book the incoming payment
     if ($this->Order->getPaymentStatus() && in_array($this->Order->getPaymentStatus()->getId(), $paymentStatusPaid)) {
         // May throw an exception
         $IncomingPayment = new PlentymarketsExportEntityOrderIncomingPayment($this->Order->getId());
         $IncomingPayment->book();
     }
 }
 /**
  * Retrieves the stocks for the stack
  */
 public function import()
 {
     // Unify
     $this->stack = array_unique($this->stack);
     if (empty($this->stack)) {
         return;
     }
     // Chunkify
     $stacks = array_chunk($this->stack, 100);
     // Reset
     $this->stack = array();
     // Warehouse
     $warehouseId = PlentymarketsConfig::getInstance()->getItemWarehouseID(0);
     // Build the request
     $Request_GetCurrentStocks = new PlentySoapRequest_GetCurrentStocks();
     $Request_GetCurrentStocks->Page = 0;
     //
     $ImportEntityItemStock = PlentymarketsImportEntityItemStock::getInstance();
     foreach ($stacks as $stack) {
         // Reset
         $Request_GetCurrentStocks->Items = array();
         // Add the SKUs
         foreach ($stack as $sku) {
             $RequestObject_GetCurrentStocks = new PlentySoapRequestObject_GetCurrentStocks();
             $RequestObject_GetCurrentStocks->SKU = $sku;
             $Request_GetCurrentStocks->Items[] = $RequestObject_GetCurrentStocks;
         }
         // Log
         PlentymarketsLogger::getInstance()->message('Sync:Item:Stock', 'Fetching ' . count($Request_GetCurrentStocks->Items) . ' stocks');
         // Do the request
         $Response_GetCurrentStocks = PlentymarketsSoapClient::getInstance()->GetCurrentStocks($Request_GetCurrentStocks);
         // Process
         /** @var PlentySoapObject_GetCurrentStocks $CurrentStock */
         foreach ($Response_GetCurrentStocks->CurrentStocks->item as $CurrentStock) {
             // Skip wrong warehouses
             if ($CurrentStock->WarehouseID != $warehouseId) {
                 continue;
             }
             $ImportEntityItemStock->update($CurrentStock);
         }
     }
 }
 /**
  * Updates the stack
  */
 public function update()
 {
     PlentymarketsLogger::getInstance()->message('Sync:Stack:Item', 'Starting update');
     $ShopRepository = Shopware()->Models()->getRepository('Shopware\\Models\\Shop\\Shop');
     $Shops = $ShopRepository->findBy(array('active' => 1), array('default' => 'DESC'));
     // Remember the time
     $timestamp = time();
     // Is this the first run?
     $firstBlood = (int) PlentymarketsConfig::getInstance()->getImportItemStackFirstRunTimestamp() == 0;
     $Request_GetItemsUpdated = new PlentySoapRequest_GetItemsUpdated();
     $Request_GetItemsUpdated->LastUpdateFrom = (int) PlentymarketsConfig::getInstance()->getImportItemStackLastUpdateTimestamp();
     // Cache to avoid duplicate inserts of the same id with multiple shops
     $itemIdsStacked = array();
     /** @var Shopware\Models\Shop\Shop $Shop */
     foreach ($Shops as $Shop) {
         $Request_GetItemsUpdated->Page = 0;
         $Request_GetItemsUpdated->StoreID = PlentymarketsMappingController::getShopByShopwareID($Shop->getId());
         do {
             // Do the request
             $Response_GetItemsUpdated = PlentymarketsSoapClient::getInstance()->GetItemsUpdated($Request_GetItemsUpdated);
             foreach ((array) $Response_GetItemsUpdated->Items->item as $Object_Integer) {
                 $itemId = $Object_Integer->intValue;
                 // Skip existing items on the first run
                 if ($Request_GetItemsUpdated->LastUpdateFrom == 0 && $firstBlood) {
                     try {
                         PlentymarketsMappingController::getItemByPlentyID($itemId);
                         continue;
                     } catch (PlentymarketsMappingExceptionNotExistant $E) {
                     }
                 }
                 $this->addItem($itemId, $Request_GetItemsUpdated->StoreID);
                 $itemIdsStacked[$itemId] = true;
             }
         } while (++$Request_GetItemsUpdated->Page < $Response_GetItemsUpdated->Pages);
     }
     // Upcomming last update timestamp
     PlentymarketsConfig::getInstance()->setImportItemStackLastUpdateTimestamp($timestamp);
     if ($firstBlood) {
         // Remember your very first time :)
         PlentymarketsConfig::getInstance()->setImportItemStackFirstRunTimestamp(time());
     }
     // Log
     $numberOfItemsStacked = count($itemIdsStacked);
     if (!$numberOfItemsStacked) {
         PlentymarketsLogger::getInstance()->message('Sync:Stack:Item', 'No item has been added to the stack');
     } else {
         if ($numberOfItemsStacked == 1) {
             PlentymarketsLogger::getInstance()->message('Sync:Stack:Item', '1 item has been added to the stack');
         } else {
             PlentymarketsLogger::getInstance()->message('Sync:Stack:Item', count($itemIdsStacked) . ' items have been added to the stack');
         }
     }
     PlentymarketsLogger::getInstance()->message('Sync:Stack:Item', 'Update finished');
 }
コード例 #17
0
 /**
  * Logs the usage data
  */
 public function usage()
 {
     // Quit if the usage may not be logged
     if (!PlentymarketsConfig::getInstance()->getMayLogUsageData(false)) {
         return;
     }
     // Collect data
     $memoryUsage = PlentymarketsUtils::convertBytes(memory_get_usage());
     $memoryUsageReal = PlentymarketsUtils::convertBytes(memory_get_usage(true));
     $memoryLimit = ini_get('memory_limit');
     $numberOfCalls = PlentymarketsSoapClient::getInstance()->getNumberOfCalls();
     // Generate message
     $message = sprintf('Memory: %s (%s) / (%s) – Calls: %s', $memoryUsageReal, $memoryUsage, $memoryLimit, $numberOfCalls);
     // And save to the log
     $this->message('Usage data', $message);
 }
 /**
  * Starts the actual pending export.
  *
  * @throws PlentymarketsExportException
  */
 public function export()
 {
     if ($this->isRunning == true) {
         throw new PlentymarketsExportException('Another export is running at this very moment', 2510);
     }
     // Check whether settings and mapping is complete
     if ($this->mayRun == false) {
         throw new PlentymarketsExportException('Either the mapping or the settings is not finished or the data integrity is not valid', 2520);
     }
     // Get the pending entity
     $entity = $this->Config->getExportEntityPending(false);
     // No exception.. or the log will ne spammed
     if ($entity == false) {
         return;
     }
     // Set the running flag and delete the last call timestmap and the pending entity
     $this->Config->setIsExportRunning(1);
     $this->Config->eraseExportEntityPending();
     $this->Config->eraseInitialExportLastCallTimestamp();
     // Configure the SOAP client to log the timestamp of the calls from now on
     PlentymarketsSoapClient::getInstance()->setTimestampConfigKey('InitialExportLastCallTimestamp');
     // Log the start
     PlentymarketsLogger::getInstance()->message('Export:Initial:' . $entity, 'Starting');
     // Get the entity status object
     $Status = $this->StatusController->getEntity($entity);
     // Set running
     $Status->setStatus(PlentymarketsExportStatus::STATUS_RUNNING);
     // Set the start timestamp if that hasn't already been done
     if ((int) $Status->getStart() <= 0) {
         $Status->setStart(time());
     }
     try {
         // Get the controller
         $class = sprintf('PlentymarketsExportController%s', $entity);
         // and run it
         $Instance = new $class();
         $Instance->run();
         // Log that we are done
         PlentymarketsLogger::getInstance()->message('Export:Initial:' . $entity, 'Done!');
         // If the export is finished
         if ($Instance->isFinished()) {
             // set the success status and the finished timestamp
             $Status->setStatus(PlentymarketsExportStatus::STATUS_SUCCESS);
             $Status->setFinished(time());
         } else {
             // otherwise re-announce the entity for the next run
             $this->Config->setExportEntityPending($Status->getName());
             $Status->setStatus(PlentymarketsExportStatus::STATUS_PENDING);
         }
     } catch (PlentymarketsExportException $E) {
         // Log and save the error
         PlentymarketsLogger::getInstance()->error('Export:Initial:' . $entity, $E->getMessage(), $E->getCode());
         $Status->setError($E->getMessage());
     }
     // Reconfigure the soap client
     PlentymarketsSoapClient::getInstance()->setTimestampConfigKey(null);
     // Erase the timestamp of the latest export call
     $this->Config->eraseInitialExportLastCallTimestamp();
     // Reset the running flag
     $this->Config->setIsExportRunning(0);
 }
 /**
  * Rolls back the item (delete all mappings and the item in plentymarkets)
  */
 protected function rollback()
 {
     // Delete the item in plentymarktes
     $Request_DeleteItems = new PlentySoapRequest_DeleteItems();
     $Request_DeleteItems->DeleteItems = array();
     $Object_DeleteItems = new PlentySoapObject_DeleteItems();
     $Object_DeleteItems->ItemID = $this->PLENTY_itemID;
     $Request_DeleteItems->DeleteItems[] = $Object_DeleteItems;
     PlentymarketsSoapClient::getInstance()->DeleteItems($Request_DeleteItems);
     PlentymarketsLogger::getInstance()->message('Export:Initial:Item', 'The item with the id »' . $this->PLENTY_itemID . '« has been deleted in plentymarkets');
     // Delete the mapping for the main item
     PlentymarketsMappingController::deleteItemByShopwareID($this->SHOPWARE_Article->getId());
     // And for the details
     foreach ($this->SHOPWARE_Article->getDetails() as $ItemVariation) {
         PlentymarketsMappingController::deleteItemVariantByShopwareID($ItemVariation->getId());
     }
 }
 /**
  * Exports the delivery address
  */
 protected function exportDeliveryAddress()
 {
     if ($this->ShippingAddress === null) {
         return;
     }
     if ($this->PLENTY_customerID === null) {
         return;
     }
     $city = trim($this->ShippingAddress->getCity());
     $street_arr = PlentymarketsUtils::extractStreetAndHouseNo($this->ShippingAddress->getStreet());
     if (isset($street_arr['street']) && strlen($street_arr['street']) > 0) {
         $streetName = $street_arr['street'];
     } else {
         $streetName = trim($this->ShippingAddress->getStreet());
     }
     if (isset($street_arr['houseNo']) && strlen($street_arr['houseNo']) > 0) {
         $streetHouseNumber = $street_arr['houseNo'];
     } else {
         $streetHouseNumber = '';
     }
     $zip = trim($this->ShippingAddress->getZipCode());
     if (empty($city)) {
         $city = PlentymarketsConfig::getInstance()->get('CustomerDefaultCity');
     }
     if (!isset($streetHouseNumber) || $streetHouseNumber == '') {
         $streetHouseNumber = PlentymarketsConfig::getInstance()->get('CustomerDefaultHouseNumber');
     }
     if (!isset($streetName) || $streetName == '') {
         $streetName = PlentymarketsConfig::getInstance()->get('CustomerDefaultStreet');
     }
     if ($zip == '') {
         $zip = PlentymarketsConfig::getInstance()->get('CustomerDefaultZipcode');
     }
     $Request_SetCustomerDeliveryAddresses = new PlentySoapRequest_SetCustomerDeliveryAddresses();
     $Request_SetCustomerDeliveryAddresses->DeliveryAddresses = array();
     $Object_SetCustomerDeliveryAddressesCustomer = new PlentySoapRequest_ObjectSetCustomerDeliveryAddresses();
     $Object_SetCustomerDeliveryAddressesCustomer->AdditionalName = null;
     // string
     $Object_SetCustomerDeliveryAddressesCustomer->City = $city;
     $Object_SetCustomerDeliveryAddressesCustomer->Company = $this->ShippingAddress->getCompany();
     $Object_SetCustomerDeliveryAddressesCustomer->CountryID = $this->getDeliveryCountryID();
     // int
     $Object_SetCustomerDeliveryAddressesCustomer->CustomerID = $this->PLENTY_customerID;
     // int
     $Object_SetCustomerDeliveryAddressesCustomer->ExternalDeliveryAddressID = PlentymarketsUtils::getExternalCustomerID($this->ShippingAddress->getId());
     // string
     $Object_SetCustomerDeliveryAddressesCustomer->FirstName = $this->ShippingAddress->getFirstName();
     $Object_SetCustomerDeliveryAddressesCustomer->FormOfAddress = $this->getDeliveryFormOfAddress();
     // int
     $Object_SetCustomerDeliveryAddressesCustomer->HouseNumber = $streetHouseNumber;
     $Object_SetCustomerDeliveryAddressesCustomer->Street = $streetName;
     $Object_SetCustomerDeliveryAddressesCustomer->Surname = $this->ShippingAddress->getLastName();
     $Object_SetCustomerDeliveryAddressesCustomer->ZIP = $zip;
     $Request_SetCustomerDeliveryAddresses->DeliveryAddresses[] = $Object_SetCustomerDeliveryAddressesCustomer;
     $Response_SetCustomerDeliveryAddresses = PlentymarketsSoapClient::getInstance()->SetCustomerDeliveryAddresses($Request_SetCustomerDeliveryAddresses);
     if (!$Response_SetCustomerDeliveryAddresses->Success) {
         throw new PlentymarketsExportEntityException('The delivery address of the customer with the number »' . $this->getCustomerNumber() . '« could not be exported', 2120);
     }
     $this->PLENTY_addressDispatchID = (int) $Response_SetCustomerDeliveryAddresses->ResponseMessages->item[0]->SuccessMessages->item[0]->Value;
 }
 /**
  * imports the item for the given shop
  *
  * @param integer $itemId
  * @param integer $storeId
  * @throws PlentymarketsImportException
  */
 public function importItem($itemId, $storeId)
 {
     // Check whether the item has already been imported
     $full = !isset($this->itemIdsDone[$itemId]);
     // Build the request
     $Request_GetItemsBase = new PlentySoapRequest_GetItemsBase();
     $Request_GetItemsBase->GetAttributeValueSets = $full;
     $Request_GetItemsBase->GetCategories = true;
     $Request_GetItemsBase->GetCategoryNames = true;
     $Request_GetItemsBase->GetItemAttributeMarkup = $full;
     $Request_GetItemsBase->GetItemOthers = $full;
     //$Request_GetItemsBase->GetItemProperties = $full;
     $Request_GetItemsBase->GetItemProperties = true;
     $Request_GetItemsBase->GetItemSuppliers = false;
     $Request_GetItemsBase->GetItemURL = 0;
     $Request_GetItemsBase->GetLongDescription = $full;
     $Request_GetItemsBase->GetMetaDescription = false;
     $Request_GetItemsBase->GetShortDescription = $full;
     $Request_GetItemsBase->GetTechnicalData = false;
     $Request_GetItemsBase->StoreID = $storeId;
     $Request_GetItemsBase->ItemID = $itemId;
     // get the main language of the shop
     //$mainLang = array_values(PlentymarketsTranslation::getInstance()->getShopMainLanguage(PlentymarketsMappingController::getShopByPlentyID($storeId)));
     // set the main language of the shop in soap request
     //$Request_GetItemsBase->Lang = PlentymarketsTranslation::getInstance()->getPlentyLocaleFormat($mainLang[0]['locale']);
     $Request_GetItemsBase->Lang = 'de';
     // Do the request
     $Response_GetItemsBase = PlentymarketsSoapClient::getInstance()->GetItemsBase($Request_GetItemsBase);
     // On error
     if ($Response_GetItemsBase->Success == false) {
         // Re-add the item to the stack and quit
         PlentymarketsImportStackItem::getInstance()->addItem($itemId, $storeId);
         return;
     }
     // Item not found
     if (!isset($Response_GetItemsBase->ItemsBase->item[0])) {
         return;
     }
     //
     $ItemBase = $Response_GetItemsBase->ItemsBase->item[0];
     // Skip bundles
     if ($ItemBase->BundleType == 'bundle' && PlentymarketsConfig::getInstance()->getItemBundleHeadActionID(IMPORT_ITEM_BUNDLE_HEAD_NO) == IMPORT_ITEM_BUNDLE_HEAD_NO) {
         PlentymarketsLogger::getInstance()->message('Sync:Item', 'The item »' . $ItemBase->Texts->Name . '« will be skipped (bundle)');
         return;
     }
     // get the item texts in all active languages
     $itemTexts = array();
     $shopId = PlentymarketsMappingController::getShopByPlentyID($storeId);
     //if this is a main shop , get the item texts translation for its main language and its shop languages
     if (PlentymarketsTranslation::isMainShop($shopId)) {
         // get all active languages of the shop (from shopware)
         $activeLanguages = PlentymarketsTranslation::getShopActiveLanguages($shopId);
         foreach ($activeLanguages as $localeId => $language) {
             $Request_GetItemsTexts = new PlentySoapRequest_GetItemsTexts();
             $Request_GetItemsTexts->ItemsList = array();
             $Object_RequestItems = new PlentySoapObject_RequestItems();
             $Object_RequestItems->ExternalItemNumer = null;
             // string
             $Object_RequestItems->ItemId = $itemId;
             // string
             $Object_RequestItems->ItemNumber = null;
             // string
             $Object_RequestItems->Lang = PlentymarketsTranslation::getPlentyLocaleFormat($language['locale']);
             // string
             $Request_GetItemsTexts->ItemsList[] = $Object_RequestItems;
             $Response_GetItemsTexts = PlentymarketsSoapClient::getInstance()->GetItemsTexts($Request_GetItemsTexts);
             if (isset($Response_GetItemsTexts->ItemTexts->item[0])) {
                 $itemText = array();
                 // save the language infos for the item texts
                 $itemText['locale'] = $language['locale'];
                 // if mainShopId == null, then it is the main shop and no language shop
                 // each language shop has a mainShopId
                 if (!is_null($language['mainShopId'])) {
                     $itemText['languageShopId'] = PlentymarketsTranslation::getLanguageShopID($localeId, $language['mainShopId']);
                 } elseif (PlentymarketsTranslation::getPlentyLocaleFormat($language['locale']) != 'de') {
                     // set the language for the main shop if the main language is not German
                     $itemText['languageShopId'] = $shopId;
                 }
                 $itemText['texts'] = $Response_GetItemsTexts->ItemTexts->item[0];
                 $itemTexts[] = $itemText;
             }
         }
     }
     try {
         $shopId = PlentymarketsMappingController::getShopByPlentyID($storeId);
         $Shop = Shopware()->Models()->find('Shopware\\Models\\Shop\\Shop', $shopId);
         $Importuer = new PlentymarketsImportEntityItem($ItemBase, $Shop);
         // The item has already been updated
         if (!$full) {
             // so we just need to do the categories
             $Importuer->importCategories();
             //if this is a main shop , import the translation for its main language and its shop languages
             if (PlentymarketsTranslation::isMainShop($shopId)) {
                 if (!empty($itemTexts)) {
                     // Do the import for item texts translation
                     $Importuer->saveItemTextsTranslation($itemTexts);
                 }
                 // Do the import for the property value translations
                 $Importuer->importItemPropertyValueTranslations();
             }
         } else {
             // Do a full import
             $Importuer->import();
             //if this is a main shop , import the translation for its main language and its shop languages
             if (PlentymarketsTranslation::isMainShop($shopId)) {
                 if (!empty($itemTexts)) {
                     // Do the import for item texts translation
                     $Importuer->saveItemTextsTranslation($itemTexts);
                 }
                 // Do the import for the property value translations
                 $Importuer->importItemPropertyValueTranslations();
             }
             // Add it to the link controller
             PlentymarketsImportControllerItemLinked::getInstance()->addItem($ItemBase->ItemID);
             // Mark this item as done
             $this->itemIdsDone[$ItemBase->ItemID] = true;
         }
         // Log the usage data
         PyLog()->usage();
     } catch (Shopware\Components\Api\Exception\ValidationException $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Validation', 'The item »' . $ItemBase->Texts->Name . '« with the id »' . $ItemBase->ItemID . '« could not be imported', 3010);
         foreach ($E->getViolations() as $ConstraintViolation) {
             PlentymarketsLogger::getInstance()->error('Sync:Item:Validation', $ConstraintViolation->getMessage());
             PlentymarketsLogger::getInstance()->error('Sync:Item:Validation', $ConstraintViolation->getPropertyPath() . ': ' . $ConstraintViolation->getInvalidValue());
         }
     } catch (Shopware\Components\Api\Exception\OrmException $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Orm', 'The item »' . $ItemBase->Texts->Name . '« with the id »' . $ItemBase->ItemID . '« could not be imported (' . $E->getMessage() . ')', 3020);
         PlentymarketsLogger::getInstance()->error('Sync:Item:Orm', $E->getTraceAsString(), 1000);
         throw new PlentymarketsImportException('The item import will be stopped (internal database error)', 3021);
     } catch (PlentymarketsImportItemNumberException $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Number', $E->getMessage(), $E->getCode());
     } catch (PlentymarketsImportItemException $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item:Number', $E->getMessage(), $E->getCode());
     } catch (Exception $E) {
         PlentymarketsLogger::getInstance()->error('Sync:Item', 'The item »' . $ItemBase->Texts->Name . '« with the id »' . $ItemBase->ItemID . '« could not be imported', 3000);
         PlentymarketsLogger::getInstance()->error('Sync:Item', $E->getTraceAsString(), 1000);
         PlentymarketsLogger::getInstance()->error('Sync:Item', get_class($E));
         PlentymarketsLogger::getInstance()->error('Sync:Item', $E->getMessage());
     }
 }
 /**
  * Run import of property groups and property translations
  * @param int $lastUpdateTimestamp
  */
 private function runImportTranslations($lastUpdateTimestamp)
 {
     $mainShops = PlentymarketsUtils::getShopwareMainShops();
     /** @var $mainShop Shopware\Models\Shop\Shop */
     foreach ($mainShops as $mainShop) {
         // get all active languages of the main shop
         $activeLanguages = PlentymarketsTranslation::getShopActiveLanguages($mainShop->getId());
         foreach ($activeLanguages as $key => $language) {
             // import tanslation for property group
             $Request_GetPropertyGroups = new PlentySoapRequest_GetPropertyGroups();
             $Request_GetPropertyGroups->Lang = PlentymarketsTranslation::getPlentyLocaleFormat($language['locale']);
             $Request_GetPropertyGroups->LastUpdateFrom = $lastUpdateTimestamp;
             $Request_GetPropertyGroups->Page = 0;
             do {
                 /** @var PlentySoapResponse_GetPropertyGroups $Response_GetPropertyGroups */
                 $Response_GetPropertyGroups = PlentymarketsSoapClient::getInstance()->GetPropertyGroups($Request_GetPropertyGroups);
                 foreach ($Response_GetPropertyGroups->PropertyGroups->item as $group) {
                     $PlentymarketsImportEntityItemPropertyGroup = new PlentymarketsImportEntityItemPropertyGroup($group);
                     // set the property group translations from plenty for the language shops
                     if (!is_null($language['mainShopId'])) {
                         $languageShopID = PlentymarketsTranslation::getLanguageShopID($key, $language['mainShopId']);
                         $PlentymarketsImportEntityItemPropertyGroup->importPropertyGroupTranslation($languageShopID);
                     } else {
                         $PlentymarketsImportEntityItemPropertyGroup->importPropertyGroupTranslation($mainShop->getId());
                     }
                 }
             } while (++$Request_GetPropertyGroups->Page < $Response_GetPropertyGroups->Pages);
             // import translation for properties
             $Request_GetProperties = new PlentySoapRequest_GetProperties();
             $Request_GetProperties->Lang = PlentymarketsTranslation::getPlentyLocaleFormat($language['locale']);
             $Request_GetProperties->LastUpdateFrom = $lastUpdateTimestamp;
             $Request_GetProperties->Page = 0;
             do {
                 /** @var PlentySoapResponse_GetProperties $Response_GetProperties */
                 $Response_GetProperties = PlentymarketsSoapClient::getInstance()->GetProperties($Request_GetProperties);
                 foreach ($Response_GetProperties->Properties->item as $Option) {
                     $PlentymarketsImportEntityItemPropertyOption = new PlentymarketsImportEntityItemPropertyOption($Option);
                     // set the property translations from plenty for the language shops
                     if (!is_null($language['mainShopId'])) {
                         $languageShopID = PlentymarketsTranslation::getLanguageShopID($key, $language['mainShopId']);
                         $PlentymarketsImportEntityItemPropertyOption->importPropertyTranslation($languageShopID);
                     } else {
                         // set the property translation for the main shop
                         $PlentymarketsImportEntityItemPropertyOption->importPropertyTranslation($mainShop->getId());
                     }
                 }
             } while (++$Request_GetProperties->Page < $Response_GetProperties->Pages);
         }
     }
 }
コード例 #23
0
 /**
  * Checks whether the connection to plentymarkets can be established
  *
  * @return boolean
  */
 public function isConnected()
 {
     // The connection is only checked every 10 seconds
     if ($this->isConnected && $this->connectionTimestamp > time() - 10) {
         return true;
     }
     $this->isConnected = false;
     if (!PlentymarketsConfig::getInstance()->getApiWsdl()) {
         PlentymarketsConfig::getInstance()->erasePlentymarketsVersion();
         PlentymarketsConfig::getInstance()->setApiLastStatusTimestamp(time());
         PlentymarketsConfig::getInstance()->setApiStatus(1);
         return false;
     }
     try {
         $Response = PlentymarketsSoapClient::getInstance()->GetServerTime();
         //
         PlentymarketsConfig::getInstance()->setApiTimestampDeviation(time() - $Response->Timestamp);
         PlentymarketsConfig::getInstance()->setApiLastStatusTimestamp(time());
         PlentymarketsConfig::getInstance()->setApiStatus(2);
         $this->isConnected = true;
         $this->connectionTimestamp = time();
         // plenty version
         PlentymarketsUtils::checkPlentymarketsVersion();
         return true;
     } catch (Exception $E) {
         PlentymarketsConfig::getInstance()->setApiTimestampDeviation(0);
         PlentymarketsConfig::getInstance()->setApiLastStatusTimestamp(time());
         PlentymarketsConfig::getInstance()->setApiStatus(1);
         return false;
     }
 }
    /**
     * Performs the actual import
     *
     * @throws PlentymarketsExportException
     */
    public function run()
    {
        // Get the data from plentymarkets (for every mapped shop)
        $shopIds = Shopware()->Db()->fetchAll('
			SELECT * FROM plenty_mapping_shop
		');
        foreach ($shopIds as $shopId) {
            $mainShopId = PlentymarketsMappingController::getShopByPlentyID($shopId['plentyID']);
            $mainLang = array_values(PlentymarketsTranslation::getShopMainLanguage($mainShopId));
            $Request_GetItemCategoryTree = new PlentySoapRequest_GetItemCategoryTree();
            $Request_GetItemCategoryTree->Lang = PlentymarketsTranslation::getPlentyLocaleFormat($mainLang[0]['locale']);
            $Request_GetItemCategoryTree->GetCategoryNames = true;
            $Request_GetItemCategoryTree->StoreID = $shopId['plentyID'];
            $Request_GetItemCategoryTree->GetAktivCategories = true;
            /** @var PlentySoapResponse_GetItemCategoryTree $Response_GetItemCategoryTree */
            $Response_GetItemCategoryTree = PlentymarketsSoapClient::getInstance()->GetItemCategoryTree($Request_GetItemCategoryTree);
            if (!$Response_GetItemCategoryTree->Success) {
                Shopware()->Db()->query('INSERT plenty_mapping_category SELECT * FROM plenty_mapping_category_old');
                throw new PlentymarketsImportException('The item category tree could not be retrieved', 2920);
            }
            /** @var PlentySoapObject_ItemCategoryTreeNode $Category */
            foreach ($Response_GetItemCategoryTree->MultishopTree->item[0]->CategoryTree->item as $Category) {
                $importEntityItemCategoryTree = new PlentymarketsImportEntityItemCategoryTree($Category, $shopId['plentyID'], $Request_GetItemCategoryTree->Lang);
                $importEntityItemCategoryTree->import();
            }
        }
        $this->rebuild();
    }
 /**
  * Export the missing properties
  */
 protected function doExport()
 {
     $propertyGroupRepository = Shopware()->Models()->getRepository('Shopware\\Models\\Property\\Group');
     /** @var Shopware\Models\Property\Group $PropertyGroup */
     foreach ($propertyGroupRepository->findAll() as $PropertyGroup) {
         try {
             $groupIdAdded = PlentymarketsMappingController::getPropertyGroupByShopwareID($PropertyGroup->getId());
         } catch (PlentymarketsMappingExceptionNotExistant $E) {
             if (array_key_exists($PropertyGroup->getName(), $this->PLENTY_groupName2ID)) {
                 $groupIdAdded = $this->PLENTY_groupName2ID[$PropertyGroup->getName()];
             } else {
                 $Request_SetPropertyGroups = new PlentySoapRequest_SetPropertyGroups();
                 $Request_SetPropertyGroups->Properties = array();
                 $Object_SetPropertyGroup = new PlentySoapObject_SetPropertyGroup();
                 $Object_SetPropertyGroup->BackendName = $PropertyGroup->getName();
                 $Object_SetPropertyGroup->FrontendName = $PropertyGroup->getName();
                 $Object_SetPropertyGroup->Lang = 'de';
                 $Object_SetPropertyGroup->PropertyGroupID = null;
                 $Request_SetPropertyGroups->PropertyGroups[] = $Object_SetPropertyGroup;
                 $Response = PlentymarketsSoapClient::getInstance()->SetPropertyGroups($Request_SetPropertyGroups);
                 if (!$Response->Success) {
                     throw new PlentymarketsExportException('The item property group »' . $Object_SetPropertyGroup->BackendName . '« could not be exported', 2941);
                 }
                 $groupIdAdded = (int) $Response->ResponseMessages->item[0]->SuccessMessages->item[0]->Value;
             }
             PlentymarketsMappingController::addPropertyGroup($PropertyGroup->getId(), $groupIdAdded);
             // do export for property group translation
             $this->exportPropertyGroupTranslations($PropertyGroup->getId(), $groupIdAdded);
         }
         if (!isset($this->PLENTY_groupIDValueName2ID[$groupIdAdded])) {
             $this->PLENTY_groupIDValueName2ID[$groupIdAdded] = array();
         }
         /** @var Shopware\Models\Property\Option $Property */
         foreach ($PropertyGroup->getOptions() as $Property) {
             $Request_SetProperties = new PlentySoapRequest_SetProperties();
             $Request_SetProperties->Properties = array();
             $Object_SetProperty = new PlentySoapObject_SetProperty();
             $Object_SetProperty->PropertyGroupID = $groupIdAdded;
             $Object_SetProperty->PropertyID = null;
             $Object_SetProperty->Lang = 'de';
             $shopwareID = $PropertyGroup->getId() . ';' . $Property->getId();
             try {
                 PlentymarketsMappingController::getPropertyByShopwareID($shopwareID);
             } catch (PlentymarketsMappingExceptionNotExistant $E) {
                 if (array_key_exists($Property->getName(), $this->PLENTY_groupIDValueName2ID[$groupIdAdded])) {
                     $propertyIdAdded = $this->PLENTY_groupIDValueName2ID[$groupIdAdded][$Property->getName()];
                 } else {
                     $Object_SetProperty->PropertyFrontendName = $Property->getName();
                     $Object_SetProperty->PropertyBackendName = $Property->getName();
                     $Object_SetProperty->ShowOnItemPage = 1;
                     $Object_SetProperty->ShowInItemList = 1;
                     $Object_SetProperty->PropertyType = 'text';
                     $Request_SetProperties->Properties[] = $Object_SetProperty;
                     $Response_SetProperties = PlentymarketsSoapClient::getInstance()->SetProperties($Request_SetProperties);
                     if (!$Response_SetProperties->Success) {
                         throw new PlentymarketsExportException('The item property »' . $Object_SetProperty->PropertyBackendName . '« could not be created', 2942);
                     }
                     $propertyIdAdded = (int) $Response_SetProperties->ResponseMessages->item[0]->SuccessMessages->item[0]->Value;
                 }
                 PlentymarketsMappingController::addProperty($shopwareID, $propertyIdAdded);
                 $this->exportPropertyTranslations($groupIdAdded, $Property->getId(), $propertyIdAdded);
             }
         }
     }
 }
 /**
  * Retrieves the plentymarkets version
  */
 public static function checkPlentymarketsVersion()
 {
     $timestamp = PlentymarketsConfig::getInstance()->getPlentymarketsVersionTimestamp(0);
     if ($timestamp < strtotime('- 12 hours')) {
         $Response = PlentymarketsSoapClient::getInstance()->GetPlentymarketsVersion();
         PlentymarketsConfig::getInstance()->setPlentymarketsVersion($Response->PlentyVersion);
         PlentymarketsConfig::getInstance()->setPlentymarketsVersionTimestamp(time());
     }
 }
    /**
     * Retrieves the images from plentymarkets and adds them to the item.
     *
     * @return number
     */
    public function image()
    {
        $plentyId2ShopwareId = array();
        $shopwareId2PlentyPosition = array();
        $Request_GetItemsImages = new PlentySoapRequest_GetItemsImages();
        $Request_GetItemsImages->Page = 0;
        $Request_GetItemsImages->SKU = $this->PLENTY_itemId;
        // Cleanup
        $this->purge();
        /**
         * @var Media $mediaResource
         */
        $mediaResource = \Shopware\Components\Api\Manager::getResource('Media');
        do {
            /**
             * @var PlentySoapResponse_GetItemsImages $Response_GetItemsImages
             */
            $Response_GetItemsImages = PlentymarketsSoapClient::getInstance()->GetItemsImages($Request_GetItemsImages);
            if ($Response_GetItemsImages->Success == false) {
                PlentymarketsLogger::getInstance()->error('Sync:Item:Image', 'The images for the plentymarkets item id »' . $this->PLENTY_itemId . '« could not be retrieved', 3200);
                continue;
            }
            /**
             * @var $Image PlentySoapResponse_ObjectItemImage
             */
            foreach ($Response_GetItemsImages->ItemsImages->item as $Image) {
                $shopwareStoreIds = array();
                /**
                 * @var $reference PlentySoapResponse_ObjectGetItemImageReference
                 */
                foreach ($Image->References->item as $reference) {
                    if ($reference->ReferenceType == 'Mandant') {
                        try {
                            if (PlentymarketsMappingController::getShopByPlentyID($reference->ReferenceValue) > 0) {
                                $shopwareStoreId = PlentymarketsMappingController::getShopByPlentyID($reference->ReferenceValue);
                            }
                        } catch (PlentymarketsMappingExceptionNotExistant $E) {
                            continue;
                        }
                        if (isset($shopwareStoreId)) {
                            $shopwareStoreIds[] = $shopwareStoreId;
                        }
                    }
                }
                // Skip the image if it should not be shown
                if (empty($shopwareStoreIds)) {
                    continue;
                } else {
                    try {
                        $media = $this->updateMedia($Image, $mediaResource);
                    } catch (PlentymarketsMappingExceptionNotExistant $e) {
                        $media = $this->createMedia($Image, $mediaResource);
                    } catch (NotFoundException $e) {
                        $media = $this->createMedia($Image, $mediaResource);
                    } catch (Exception $e) {
                        PlentymarketsLogger::getInstance()->error('Sync:Item:Image', $e->getMessage(), 3200);
                        continue;
                    }
                    $image = new Image();
                    $image->setMain(2);
                    $image->setMedia($media);
                    $image->setPath($media->getName());
                    $image->setExtension($media->getExtension());
                    // get the main language of the shop
                    //$mainLangData = array_values(PlentymarketsTranslation::getInstance()->getShopMainLanguage($shopwareStoreId));
                    //$mainLang = PlentymarketsTranslation::getInstance()->getPlentyLocaleFormat($mainLangData[0]['locale']);
                    foreach ($Image->Names->item as $imageName) {
                        if ($imageName->Lang == 'de') {
                            // set the image title in German
                            $image->setDescription($imageName->Name);
                        }
                    }
                    if (!is_null(PlentymarketsConfig::getInstance()->getItemImageAltAttributeID()) && PlentymarketsConfig::getInstance()->getItemImageAltAttributeID() > 0 && PlentymarketsConfig::getInstance()->getItemImageAltAttributeID() <= 3) {
                        // get the attribute number for alternative text from connector's settings
                        $plenty_attributeID = PlentymarketsConfig::getInstance()->getItemImageAltAttributeID();
                        // set the value for the attribute number
                        $attribute = new \Shopware\Models\Attribute\ArticleImage();
                        call_user_func(array($attribute, 'setAttribute' . $plenty_attributeID), $Image->Names->item[0]->AlternativeText);
                        $image->setAttribute($attribute);
                    }
                    $image->setPosition($Image->Position);
                    // Generate the thumbnails
                    if (version_compare(Shopware::VERSION, '4.2') != 1) {
                        PlentymarketsImportItemImageThumbnailController::getInstance()->addMediaResource($media);
                    }
                    Shopware()->Models()->persist($image);
                    Shopware()->Models()->flush();
                    $imageId = $image->getId();
                    foreach ($shopwareStoreIds as $shopwareStoreId) {
                        // import the image title translations for all active shops of the image
                        $this->importImageTitleTranslation($imageId, $Image->Names->item, $shopwareStoreId);
                    }
                    $plentyId2ShopwareId[$Image->ImageID] = $imageId;
                    $shopwareId2PlentyPosition[$Image->Position] = $imageId;
                    Shopware()->DB()->query('
											UPDATE s_articles_img
												SET articleID = ?
												WHERE id = ?
										', array($this->SHOPWARE_itemId, $imageId));
                }
            }
        } while (++$Request_GetItemsImages->Page < $Response_GetItemsImages->Pages);
        if (empty($shopwareId2PlentyPosition)) {
            return;
        }
        ksort($shopwareId2PlentyPosition);
        $mainImageId = reset($shopwareId2PlentyPosition);
        if (empty($mainImageId)) {
            return;
        }
        /**
         * @var Shopware\Models\Article\Image $mainImage
         */
        $mainImage = Shopware()->Models()->find('Shopware\\Models\\Article\\Image', $mainImageId);
        $mainImage->setMain(1);
        Shopware()->Models()->persist($mainImage);
        Shopware()->Models()->flush();
        // Get the variant images
        $Request_GetItemsVariantImages = new PlentySoapRequest_GetItemsVariantImages();
        $Request_GetItemsVariantImages->Items = array();
        $RequestObject_GetItemsVariantImages = new PlentySoapRequestObject_GetItemsVariantImages();
        $RequestObject_GetItemsVariantImages->ItemID = $this->PLENTY_itemId;
        $Request_GetItemsVariantImages->Items[] = $RequestObject_GetItemsVariantImages;
        /**
         * @var PlentySoapResponse_GetItemsVariantImages $Response_GetItemsVariantImages
         */
        $Response_GetItemsVariantImages = PlentymarketsSoapClient::getInstance()->GetItemsVariantImages($Request_GetItemsVariantImages);
        foreach ($Response_GetItemsVariantImages->Images->item as $GetItemsVariantImagesImage) {
            try {
                $shopwareOptionId = PlentymarketsMappingController::getAttributeOptionByPlentyID($GetItemsVariantImagesImage->AttributeValueID);
                /**
                 * @var \Shopware\Models\Article\Configurator\Option $shopwareOption
                 */
                $shopwareOption = Shopware()->Models()->find('Shopware\\Models\\Article\\Configurator\\Option', $shopwareOptionId);
            } catch (PlentymarketsMappingExceptionNotExistant $e) {
                continue;
            }
            if (!isset($plentyId2ShopwareId[$GetItemsVariantImagesImage->ImageID])) {
                continue;
            }
            /** @var Shopware\Models\Article\Image $shopwareImage */
            $shopwareImageId = $plentyId2ShopwareId[$GetItemsVariantImagesImage->ImageID];
            /**
             * @var Image $shopwareImage
             */
            $shopwareImage = Shopware()->Models()->find('Shopware\\Models\\Article\\Image', $shopwareImageId);
            $mapping = new Shopware\Models\Article\Image\Mapping();
            $mapping->setImage($shopwareImage);
            $rule = new Shopware\Models\Article\Image\Rule();
            $rule->setMapping($mapping);
            $rule->setOption($shopwareOption);
            $mapping->getRules()->add($rule);
            $shopwareImage->setMappings($mapping);
            Shopware()->Models()->persist($mapping);
            $details = Shopware()->Db()->fetchCol('
				SELECT
						d.id
					FROM s_articles_details d
						INNER JOIN s_article_configurator_option_relations alias16 ON alias16.option_id = ' . $shopwareOptionId . ' AND alias16.article_id = d.id
					WHERE d.articleID = ' . $this->SHOPWARE_itemId . '
			');
            foreach ($details as $detailId) {
                /**
                 * Get the detail object
                 *
                 * @var Shopware\Models\Article\Detail $detail
                 */
                $detail = Shopware()->Models()->getReference('Shopware\\Models\\Article\\Detail', $detailId);
                // Create the variant image
                $variantImage = new Shopware\Models\Article\Image();
                $variantImage->setExtension($shopwareImage->getExtension());
                $variantImage->setMain($shopwareImage->getMain());
                $variantImage->setParent($shopwareImage);
                $variantImage->setArticleDetail($detail);
                // And persist it
                Shopware()->Models()->persist($variantImage);
            }
        }
        Shopware()->Db()->update('s_articles', array('changetime' => date('c', time())), 'id=' . $this->SHOPWARE_itemId);
        Shopware()->Models()->flush();
    }
 /**
  * Constructor method
  *
  * @param PlentySoapObject_ItemBase $ItemBase
  */
 public function __construct($ItemBase)
 {
     $this->ItemBase = $ItemBase;
     foreach ($this->ItemBase->ItemAttributeMarkup->item as $ItemAttributeMarkup) {
         // May be percentage or flat rate surcharge
         $this->valueId2markup[$ItemAttributeMarkup->ValueID] = (double) $ItemAttributeMarkup->Markup;
     }
     //
     $Request_GetAttributeValueSets = new PlentySoapRequest_GetAttributeValueSets();
     $valueIds = array();
     $chunks = array_chunk($this->ItemBase->AttributeValueSets->item, 50);
     foreach ($chunks as $chunk) {
         $Request_GetAttributeValueSets->AttributeValueSets = array();
         // Attribute Value Sets abfragen
         foreach ($chunk as $AttributeValueSet) {
             //
             $this->variants[$AttributeValueSet->AttributeValueSetID] = array();
             //
             $RequestObject_GetAttributeValueSets = new PlentySoapRequestObject_GetAttributeValueSets();
             $RequestObject_GetAttributeValueSets->AttributeValueSetID = $AttributeValueSet->AttributeValueSetID;
             $RequestObject_GetAttributeValueSets->Lang = 'de';
             $Request_GetAttributeValueSets->AttributeValueSets[] = $RequestObject_GetAttributeValueSets;
         }
         $Response_GetAttributeValueSets = PlentymarketsSoapClient::getInstance()->GetAttributeValueSets($Request_GetAttributeValueSets);
         /**
          * @var PlentySoapObject_AttributeValueSet $AttributeValueSet
          * @var PlentySoapObject_Attribute $Attribute
          */
         foreach ($Response_GetAttributeValueSets->AttributeValueSets->item as $AttributeValueSet) {
             $this->variant2markup[$AttributeValueSet->AttributeValueSetID] = 0;
             foreach ($AttributeValueSet->Attribute->item as $Attribute) {
                 //
                 if (!array_key_exists($Attribute->AttributeFrontendName, $this->groups)) {
                     try {
                         $attributeId = PlentymarketsMappingController::getAttributeGroupByPlentyID($Attribute->AttributeID);
                         $group = array('id' => $attributeId, 'options' => array());
                     } catch (Exception $e) {
                         $group = array('name' => $Attribute->AttributeFrontendName, 'options' => array());
                     }
                     $this->groups[$Attribute->AttributeFrontendName] = $group;
                     $this->groupId2optionName2plentyId[$Attribute->AttributeID] = array();
                     $this->groupName2plentyId[$Attribute->AttributeFrontendName] = $Attribute->AttributeID;
                 }
                 //
                 $this->configuratorOptions[$AttributeValueSet->AttributeValueSetID][] = array('group' => $Attribute->AttributeFrontendName, 'option' => $Attribute->AttributeValue->ValueFrontendName);
                 //
                 if (!in_array($Attribute->AttributeValue->ValueID, $valueIds)) {
                     try {
                         $valueId = PlentymarketsMappingController::getAttributeOptionByPlentyID($Attribute->AttributeValue->ValueID);
                         $option = array('id' => $valueId);
                     } catch (Exception $e) {
                         $option = array('name' => $Attribute->AttributeValue->ValueFrontendName);
                     }
                     $this->groups[$Attribute->AttributeFrontendName]['options'][] = $option;
                     $this->groupId2optionName2plentyId[$Attribute->AttributeID][$Attribute->AttributeValue->ValueFrontendName] = $Attribute->AttributeValue->ValueID;
                     $valueIds[] = $Attribute->AttributeValue->ValueID;
                 }
                 if ($this->valueId2markup[$Attribute->AttributeValue->ValueID]) {
                     $markup = $this->valueId2markup[$Attribute->AttributeValue->ValueID];
                 } else {
                     $markup = (double) $Attribute->AttributeValue->Markup;
                 }
                 if ($markup) {
                     if ($Attribute->MarkupPercental == 1) {
                         $markup = $this->ItemBase->PriceSet->Price / 100 * $markup;
                     }
                     $this->variant2markup[$AttributeValueSet->AttributeValueSetID] += $markup;
                 }
             }
         }
     }
 }
    /**
     * Books the incoming payment
     */
    public function book()
    {
        $methodOfPaymentId = PlentymarketsMappingController::getMethodOfPaymentByShopwareID($this->order['paymentId']);
        if ($methodOfPaymentId == MOP_AMAZON_PAYMENT) {
            PlentymarketsLogger::getInstance()->message('Sync:Order:IncomingPayment', 'The incoming payment of the order with the number »' . $this->order['number'] . '« was ignored (Amazon Payment)');
            return;
        }
        $transactionId = '';
        if ($methodOfPaymentId == MOP_KLARNA || $methodOfPaymentId == MOP_KLARNACREDIT) {
            $transactionId = $this->getKlarnaTransactionId();
            $reasonForPayment = '';
        } else {
            $reasonForPayment = sprintf('Shopware (OrderId: %u, CustomerId: %u)', $this->order['id'], $this->order['customerId']);
        }
        $Request_AddIncomingPayments = new PlentySoapRequest_AddIncomingPayments();
        $Request_AddIncomingPayments->IncomingPayments = array();
        $Object_AddIncomingPayments = new PlentySoapObject_AddIncomingPayments();
        $Object_AddIncomingPayments->Amount = $this->order['invoiceAmount'];
        $Object_AddIncomingPayments->Currency = PlentymarketsMappingController::getCurrencyByShopwareID($this->order['currency']);
        $Object_AddIncomingPayments->CustomerEmail = $this->order['customer']['email'];
        $Object_AddIncomingPayments->CustomerID = $this->getCustomerId();
        $Object_AddIncomingPayments->CustomerName = $this->getCustomerName();
        $Object_AddIncomingPayments->MethodOfPaymentID = $methodOfPaymentId;
        $Object_AddIncomingPayments->OrderID = $this->plentyOrder->plentyOrderId;
        $Object_AddIncomingPayments->ReasonForPayment = $reasonForPayment;
        if ($transactionId) {
            $Object_AddIncomingPayments->TransactionID = $transactionId;
        } else {
            if (empty($this->order['transactionId'])) {
                $Object_AddIncomingPayments->TransactionID = $Object_AddIncomingPayments->ReasonForPayment;
            } else {
                $Object_AddIncomingPayments->TransactionID = $this->order['transactionId'];
            }
        }
        if ($this->object['clearedDate'] instanceof DateTime) {
            $Object_AddIncomingPayments->TransactionTime = $this->order['clearedDate']->getTimestamp();
        } else {
            $Object_AddIncomingPayments->TransactionTime = time();
        }
        $Request_AddIncomingPayments->IncomingPayments[] = $Object_AddIncomingPayments;
        $Response_AddIncomingPayments = PlentymarketsSoapClient::getInstance()->AddIncomingPayments($Request_AddIncomingPayments);
        // Check for success
        if ($Response_AddIncomingPayments->Success) {
            PlentymarketsLogger::getInstance()->message('Sync:Order:IncomingPayment', 'The incoming payment of the order with the number »' . $this->order['number'] . '« was booked');
            Shopware()->Db()->query('
					UPDATE plenty_order
						SET
							plentyOrderPaidStatus = 1,
							plentyOrderPaidTimestamp = NOW()
						WHERE shopwareId = ?
				', array($this->order['id']));
        } else {
            throw new PlentymarketsExportEntityException('The incoming payment of the order with the number »' . $this->order['number'] . '« could not be booked', 4140);
        }
    }
    /**
     * Prunes the item bundles
     */
    protected function pruneItemBundles()
    {
        // Register the modules
        PlentymarketsUtils::registerBundleModules();
        // Create a temporary table
        Shopware()->Db()->exec('
			CREATE TEMPORARY TABLE IF NOT EXISTS plenty_cleanup_item_bundle
				(bundleId INT UNSIGNED, INDEX (bundleId))
				ENGINE = MEMORY;
		');
        // Get all bundles - regardless of store ids
        $Request_GetItemBundles = new PlentySoapRequest_GetItemBundles();
        $Request_GetItemBundles->LastUpdate = 0;
        $Request_GetItemBundles->Page = 0;
        do {
            /** @var PlentySoapResponse_GetItemBundles $Response_GetItemsBase */
            $Response_GetItemBundles = PlentymarketsSoapClient::getInstance()->GetItemBundles($Request_GetItemBundles);
            // Call failed
            if (is_null($Response_GetItemBundles) || !property_exists($Response_GetItemBundles, 'ItemBundles')) {
                // Log
                PlentymarketsLogger::getInstance()->error('Cleanup:Item:Bundle', 'Aborting. GetItemBundles apparently failed');
                // Delete the temporary table
                Shopware()->Db()->exec('
					DROP TEMPORARY TABLE plenty_cleanup_item_bundle
				');
                return;
            }
            $bundleIds = array();
            // Collect the bundle head ids
            foreach ($Response_GetItemBundles->ItemBundles->item as $bundle) {
                /** @var PlentySoapObject_Bundle $bundle */
                $plentyBundleHeadSku = explode('-', $bundle->SKU);
                $plentyBundleHeadId = (int) $plentyBundleHeadSku[0];
                $bundleIds[] = $plentyBundleHeadId;
            }
            if (empty($bundleIds)) {
                break;
            }
            // Build the sql statement
            $bundleIdsSql = implode(', ', array_map(function ($itemId) {
                return sprintf('(%u)', $itemId);
            }, $bundleIds));
            // Fill the table
            Shopware()->Db()->exec('
				INSERT IGNORE INTO plenty_cleanup_item_bundle VALUES ' . $bundleIdsSql . '
			');
        } while (++$Request_GetItemBundles->Page < $Response_GetItemBundles->Pages);
        // Get all shopware bundles which are no longer in plentymarkets
        $bundles = Shopware()->Db()->fetchAll('
			SELECT
					id
				FROM s_articles_bundles
				WHERE
					id NOT IN (
						SELECT pmi.shopwareID
							FROM plenty_cleanup_item_bundle pci
							LEFT JOIN plenty_mapping_item_bundle pmi ON pmi.plentyID = pci.bundleId
							WHERE pmi.shopwareID IS NOT NULL
					)
		');
        // And delete them
        foreach ($bundles as $bundle) {
            /** @var Shopware\CustomModels\Bundle\Bundle $bundle */
            $bundle = Shopware()->Models()->find('Shopware\\CustomModels\\Bundle\\Bundle', $bundle['id']);
            Shopware()->Models()->remove($bundle);
            // Log
            PyLog()->message('Cleanup:Item:Bundle', 'The item bundle »' . $bundle->getName() . '« with the number »' . $bundle->getNumber() . '« has been deleted');
        }
        Shopware()->Models()->flush();
        Shopware()->Db()->delete('plenty_mapping_item_bundle', 'shopwareID NOT IN (SELECT id FROM s_articles_bundles)');
    }