diff --git a/Commands/ExportCategories.php b/Commands/ExportCategories.php index 7cea264..e1adc2f 100644 --- a/Commands/ExportCategories.php +++ b/Commands/ExportCategories.php @@ -43,18 +43,6 @@ protected function configure() $this ->setName('Afterbuy:Export:Categories') ->setDescription('Export Categories to Afterbuy') - /*->addArgument( - 'my-argument', - InputArgument::REQUIRED, - 'An required argument (positional)' - ) - ->addOption( - 'my-option', - null, - InputOption::VALUE_OPTIONAL, - 'An optional *option*', - 'My-Default-Value' - )*/ ->setHelp(<<%command.name% implements a command. EOF diff --git a/Commands/ExportOrders.php b/Commands/ExportOrders.php index e6c2696..8048802 100755 --- a/Commands/ExportOrders.php +++ b/Commands/ExportOrders.php @@ -41,18 +41,6 @@ protected function configure() $this ->setName('Afterbuy:Export:Orders') ->setDescription('Submit orders to Afterbuy') - /*->addArgument( - 'my-argument', - InputArgument::REQUIRED, - 'An required argument (positional)' - ) - ->addOption( - 'my-option', - null, - InputOption::VALUE_OPTIONAL, - 'An optional *option*', - 'My-Default-Value' - )*/ ->setHelp(<<%command.name% implements a command. EOF diff --git a/Commands/ImportCategories.php b/Commands/ImportCategories.php index 231c90b..9075cd8 100755 --- a/Commands/ImportCategories.php +++ b/Commands/ImportCategories.php @@ -42,18 +42,6 @@ protected function configure() $this ->setName('Afterbuy:Import:Categories') ->setDescription('Import Categories from Afterbuy') - /*->addArgument( - 'my-argument', - InputArgument::REQUIRED, - 'An required argument (positional)' - ) - ->addOption( - 'my-option', - null, - InputOption::VALUE_OPTIONAL, - 'An optional *option*', - 'My-Default-Value' - )*/ ->setHelp(<<%command.name% implements a command. EOF diff --git a/Commands/ImportProducts.php b/Commands/ImportProducts.php index f6074d4..87111a2 100755 --- a/Commands/ImportProducts.php +++ b/Commands/ImportProducts.php @@ -3,6 +3,7 @@ namespace viaebShopwareAfterbuy\Commands; +use Doctrine\ORM\ORMException; use viaebShopwareAfterbuy\Services\ReadData\ReadDataInterface; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; use viaebShopwareAfterbuy\Services\WriteData\Internal\WriteProductsService; @@ -65,6 +66,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $data = $this->readDataService->get($filter); $output->writeln('Got ' . count($data) . ' Products'); + $this->writeDataService->put($data); } } diff --git a/Commands/ImportStatus.php b/Commands/ImportStatus.php index 13dd5db..d7c00c4 100755 --- a/Commands/ImportStatus.php +++ b/Commands/ImportStatus.php @@ -3,6 +3,7 @@ namespace viaebShopwareAfterbuy\Commands; +use Doctrine\ORM\ORMException; use viaebShopwareAfterbuy\Services\ReadData\ReadDataInterface; use viaebShopwareAfterbuy\Services\WriteData\Internal\WriteStatusService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; @@ -63,6 +64,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $filter = $this->writeDataService->getOrdersForRequestingStatusUpdate(); $data = $this->readDataService->get($filter); + $this->writeDataService->put($data); } } diff --git a/Components/Helper.php b/Components/Helper.php index bf959ca..8770b72 100644 --- a/Components/Helper.php +++ b/Components/Helper.php @@ -13,6 +13,10 @@ public static function getSetterByField(string $field) { return 'set' . strtoupper($field[0]) . substr($field, 1); } + /** + * @param string $value + * @return float + */ public static function convertDeString2Float(string $value) { $value = str_replace('.', '', $value); $value = str_replace(',', '.', $value); @@ -20,6 +24,10 @@ public static function convertDeString2Float(string $value) { return (float)$value; } + /** + * @param $value + * @return mixed|string + */ public static function convertNumberToABString($value) { $value = number_format((float)$value, 2); $value = str_replace(',', '', $value); @@ -28,6 +36,13 @@ public static function convertNumberToABString($value) { return $value; } + /** + * @param float $price + * @param float $tax + * @param bool $isNet + * @param bool $toNet + * @return float|int + */ public static function convertPrice(float $price, float $tax, $isNet = true, $toNet = false) { if($isNet === $toNet) { return $price; diff --git a/Controllers/Backend/AfterbuyConnector.php b/Controllers/Backend/AfterbuyConnector.php index a5060cf..9a799ed 100755 --- a/Controllers/Backend/AfterbuyConnector.php +++ b/Controllers/Backend/AfterbuyConnector.php @@ -1,6 +1,8 @@ configWriter->save('partnerId', $_REQUEST['partnerId'], $this->pluginName); $this->configWriter->save('partnerPassword', $_REQUEST['partnerPassword'], $this->pluginName); $this->configWriter->save('userName', $_REQUEST['userName'], $this->pluginName); diff --git a/Controllers/Backend/viaebResetShopConnection.php b/Controllers/Backend/viaebResetShopConnection.php index 5f58214..0f0691c 100644 --- a/Controllers/Backend/viaebResetShopConnection.php +++ b/Controllers/Backend/viaebResetShopConnection.php @@ -3,6 +3,7 @@ use viaebShopwareAfterbuy\Services\Helper\ShopwareResetHelper; +/** @noinspection PhpUnused */ class Shopware_Controllers_Backend_viaebResetShopConnection extends Shopware_Controllers_Backend_ExtJs { public function indexAction() diff --git a/Library/API b/Library/API index 0664dd0..2a3f453 160000 --- a/Library/API +++ b/Library/API @@ -1 +1 @@ -Subproject commit 0664dd0441eea4f94162812090b0ab9c4f3709e5 +Subproject commit 2a3f4538b406a094121ce19f0433093cdb862aee diff --git a/Resources/config.xml b/Resources/config.xml index 257901d..924a6c3 100755 --- a/Resources/config.xml +++ b/Resources/config.xml @@ -137,7 +137,7 @@ Shopware.apps.Base.store.CustomerGroup - + paymentINVOICE @@ -146,7 +146,7 @@ description - + paymentCREDIT_CARD @@ -155,7 +155,7 @@ description - + paymentDIRECT_DEBIT @@ -165,7 +165,7 @@ - + paymentTRANSFER @@ -175,7 +175,7 @@ - + paymentCASH_PAID @@ -185,7 +185,7 @@ - + paymentCASH_ON_DELIVERY @@ -195,7 +195,7 @@ - + paymentPAYPAL @@ -205,7 +205,7 @@ - + paymentINVOICE_TRANSFER @@ -215,7 +215,7 @@ - + paymentCLICKANDBUY @@ -225,7 +225,7 @@ - + paymentEXPRESS_CREDITWORTHINESS @@ -235,7 +235,7 @@ - + paymentPAYNET @@ -245,7 +245,7 @@ - + paymentCOD_CREDITWORTHINESS @@ -255,7 +255,7 @@ - + paymentEBAY_EXPRESS @@ -265,7 +265,7 @@ - + paymentMONEYBOOKERS @@ -275,7 +275,7 @@ - + paymentCREDIT_CARD_MB @@ -285,7 +285,7 @@ - + paymentDIRECT_DEBIT_MB @@ -295,7 +295,7 @@ - + paymentOTHERS diff --git a/Resources/services.xml b/Resources/services.xml index befd4d8..1dd89ea 100755 --- a/Resources/services.xml +++ b/Resources/services.xml @@ -204,7 +204,7 @@ - + number false @@ -313,6 +313,13 @@ + + + + + + + diff --git a/Resources/views/backend/_resources/css/grid-row.css b/Resources/views/backend/_resources/css/grid-row.css index 1384c70..19021c7 100644 --- a/Resources/views/backend/_resources/css/grid-row.css +++ b/Resources/views/backend/_resources/css/grid-row.css @@ -1,3 +1,4 @@ +/*noinspection CssUnusedSymbol*/ .afterbuy-grid-cell { background-image: radial-gradient(#f8e435, transparent); } diff --git a/Resources/views/backend/viaeb_config_form/view/config_window.js b/Resources/views/backend/viaeb_config_form/view/config_window.js index 4b0d82f..5bcffd5 100644 --- a/Resources/views/backend/viaeb_config_form/view/config_window.js +++ b/Resources/views/backend/viaeb_config_form/view/config_window.js @@ -240,7 +240,7 @@ Ext.define('Shopware.apps.viaebConfigForm.view.ConfigWindow', { childDefaults: { xtype: 'combo', forceSelection: true, - allowBlank: false, + allowBlank: true, displayField: 'description', valueField: 'id', store: me.createRemoteStore(Shopware.apps.Base.store.Payment), diff --git a/Services/Helper/AbstractHelper.php b/Services/Helper/AbstractHelper.php index ae3b43a..35f70a6 100644 --- a/Services/Helper/AbstractHelper.php +++ b/Services/Helper/AbstractHelper.php @@ -150,11 +150,9 @@ public function getEntity(string $identifier, string $field, $isAttribute = fals * @param float $rate * * @return Tax - * @throws ORMException */ public function getTax(float $rate) { - $rate_s = number_format($rate, 2); if ( ! $this->taxes) { @@ -173,7 +171,6 @@ public function getTax(float $rate) /** * @param float $rate - * @throws ORMException */ public function createTax(float $rate) { @@ -181,10 +178,11 @@ public function createTax(float $rate) $tax->setTax($rate); $tax->setName($rate); - $this->entityManager->persist($tax); + try { + $this->entityManager->persist($tax); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving tax rule', array($rate)); } } @@ -295,7 +293,6 @@ public function grab_image($url) curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); - /** * this enables self signed ssl certificates. * as long requests are possible via http, mitm-attacks will always be a problem @@ -337,7 +334,6 @@ public function initMediaService(MediaService $mediaService) * @param $albumName * * @return Media - * @throws ORMException */ public function createMediaImage($url, $albumName = 'Artikel') { @@ -397,10 +393,11 @@ public function createMediaImage($url, $albumName = 'Artikel') $media->setExtension($path_info['extension']); $media->setType(Media::TYPE_IMAGE); - $this->entityManager->persist($media); try { + $this->entityManager->persist($media); $this->entityManager->flush($media); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { + $this->logger->error($e->getMessage()); } if ($media->getType() === Media::TYPE_IMAGE && ! in_array($media->getExtension(), ['tif', 'tiff'], true) @@ -416,14 +413,20 @@ public function createMediaImage($url, $albumName = 'Artikel') * @return mixed|string */ public static function getShopwareVersion() { + /** @noinspection DuplicatedCode */ $currentVersion = ''; if(defined('\Shopware::VERSION')) { + /** @noinspection PhpFullyQualifiedNameUsageInspection */ + /** @noinspection PhpUndefinedClassConstantInspection */ $currentVersion = \Shopware::VERSION; } //get old composer versions if($currentVersion === '___VERSION___' && class_exists('ShopwareVersion') && class_exists('PackageVersions\Versions')) { + /** @noinspection PhpFullyQualifiedNameUsageInspection */ + /** @noinspection PhpUndefinedClassConstantInspection */ + /** @noinspection PhpUndefinedClassInspection */ $currentVersion = \ShopwareVersion::parseVersion( \PackageVersions\Versions::getVersion('shopware/shopware') )['version']; diff --git a/Services/Helper/AfterbuyOrderHelper.php b/Services/Helper/AfterbuyOrderHelper.php new file mode 100644 index 0000000..0b60045 --- /dev/null +++ b/Services/Helper/AfterbuyOrderHelper.php @@ -0,0 +1,176 @@ + 1) { + foreach($entity['SoldItems']['SoldItem'] as $position) { + $orderPosition = new OrderPosition(); + + $orderPosition->setName($position['ItemTitle']); + + if(array_key_exists('ShopProductDetails', $position) && array_key_exists('ProductID', $position['ShopProductDetails'])) { + $orderPosition->setExternalIdentifier($position['ShopProductDetails']['ProductID']); + $orderPosition->setInternalIdentifier($position['ShopProductDetails']['EAN']); + } else { + $orderPosition->setExternalIdentifier($position['ItemID']); + } + + $orderPosition->setQuantity($position['ItemQuantity']); + $orderPosition->setPrice(Helper::convertDeString2Float($position['ItemPrice'])); + $orderPosition->setTax(Helper::convertDeString2Float($position['TaxRate'])); + + $value->getPositions()->add($orderPosition); + + if(Helper::convertDeString2Float($position['TaxRate'])) { + $value->addNetAmount(Helper::convertDeString2Float($position['ItemPrice']) / (1 + Helper::convertDeString2Float($position['TaxRate']) / 100), $position['ItemQuantity']); + } + } + } else { + $orderPosition = new OrderPosition(); + + $orderPosition->setName($entity['SoldItems']['SoldItem']['ItemTitle']); + $orderPosition->setPrice(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['ItemPrice'])); + + if(array_key_exists('ShopProductDetails', $entity['SoldItems']['SoldItem']) && array_key_exists('ProductID', $entity['SoldItems']['SoldItem']['ShopProductDetails'])) { + $orderPosition->setExternalIdentifier($entity['SoldItems']['SoldItem']['ShopProductDetails']['ProductID']); + } else { + $orderPosition->setExternalIdentifier($entity['SoldItems']['SoldItem']['ItemID']); + } + + $orderPosition->setQuantity($entity['SoldItems']['SoldItem']['ItemQuantity']); + $orderPosition->setTax(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['TaxRate'])); + + $value->getPositions()->add($orderPosition); + + if(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['TaxRate'])) { + $value->addNetAmount(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['ItemPrice']) / (1 + Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['TaxRate']) / 100), + $entity['SoldItems']['SoldItem']['ItemQuantity']); + } + } + } + + /** + * @param Order $value + * @param array $entity + */ + public function setPaymentType(Order &$value, array $entity) { + if(array_key_exists('PaymentID', $entity['PaymentInfo'])) { + $value->setPaymentType($entity['PaymentInfo']['PaymentID']); + } + + if(array_key_exists('PaymentFunction', $entity['PaymentInfo'])) { + $value->setPaymentType($entity['PaymentInfo']['PaymentFunction']); + } + } + + /** + * @param Order $value + * @param array $entity + */ + public function setBillingAddress(Order &$value, array $entity) { + $billingAddress = new Address(); + + $billingAddress->setFirstname($entity['BuyerInfo']['BillingAddress']['FirstName']); + $billingAddress->setLastname($entity['BuyerInfo']['BillingAddress']['LastName']); + + if($entity['BuyerInfo']['BillingAddress']['Title'] === 'Frau') { + $billingAddress->setSalutation('mrs'); + } else { + $billingAddress->setSalutation('mr'); + } + + $billingAddress->setCompany($entity['BuyerInfo']['BillingAddress']['Company']); + $billingAddress->setStreet($entity['BuyerInfo']['BillingAddress']['Street']); + $billingAddress->setAdditionalAddressLine1($entity['BuyerInfo']['BillingAddress']['Street2']); + $billingAddress->setZipcode($entity['BuyerInfo']['BillingAddress']['PostalCode']); + $billingAddress->setCity($entity['BuyerInfo']['BillingAddress']['City']); + $billingAddress->setCountry($entity['BuyerInfo']['BillingAddress']['CountryISO']); + $billingAddress->setPhone($entity['BuyerInfo']['BillingAddress']['Phone']); + $billingAddress->setVatId($entity['BuyerInfo']['BillingAddress']['TaxIDNumber']); + $billingAddress->setEmail($entity['BuyerInfo']['BillingAddress']['Mail']); + + $value->setBillingAddress($billingAddress); + } + + /** + * @param Order $value + * @param array $entity + */ + public function setShippingAddress(Order &$value, array $entity) { + if(array_key_exists('ShippingAddress', $entity['BuyerInfo']) && $entity['BuyerInfo']['ShippingAddress']['FirstName'] && !$entity['BuyerInfo']['ShippingAddress']['LastName'] && + $entity['BuyerInfo']['ShippingAddress']['Street'] && $entity['BuyerInfo']['ShippingAddress']['CountryISO'] && $entity['BuyerInfo']['ShippingAddress']['PostalCode']) { + $shippingAddress = new Address(); + + $shippingAddress->setFirstname($entity['BuyerInfo']['ShippingAddress']['FirstName']); + $shippingAddress->setLastname($entity['BuyerInfo']['ShippingAddress']['LastName']); + + if(isset($entity['BuyerInfo']['ShippingAddress']['Title']) && $entity['BuyerInfo']['ShippingAddress']['Title'] === 'Frau') { + $shippingAddress->setSalutation('mrs'); + } else { + $shippingAddress->setSalutation('mr'); + } + + $shippingAddress->setCompany($entity['BuyerInfo']['ShippingAddress']['Company']); + $shippingAddress->setStreet($entity['BuyerInfo']['ShippingAddress']['Street']); + $shippingAddress->setAdditionalAddressLine1($entity['BuyerInfo']['ShippingAddress']['Street2']); + $shippingAddress->setZipcode($entity['BuyerInfo']['ShippingAddress']['PostalCode']); + $shippingAddress->setCity($entity['BuyerInfo']['ShippingAddress']['City']); + $shippingAddress->setCountry($entity['BuyerInfo']['ShippingAddress']['CountryISO']); + $shippingAddress->setPhone($entity['BuyerInfo']['ShippingAddress']['Phone']); + + $value->setShippingAddress($shippingAddress); + } + } + + /** + * @param Order $value + * @param array $entity + */ + public function setShippingCosts(Order &$value, array $entity) { + $shippingNet = Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTotalCost']) / (1 + Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTaxRate']) / 100); + + $value->setShippingNet($shippingNet); + $value->setShipping(Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTotalCost'])); + $value->setShippingTax(Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTaxRate'])); + + if($shippingNet) { + $value->addNetAmount($shippingNet, 1); + } + } + + /** + * @param Order $value + * @param array $entity + */ + public function setShipmentStatus(Order &$value, array $entity) { + if(array_key_exists('DeliveryDate', $entity['ShippingInfo'])) { + $value->setShipped(true); + } + } + + /** + * @param Order $value + * @param array $entity + */ + public function setTransactionDetails(Order &$value, array $entity) { + if(array_key_exists('PaymentTransactionID', $entity['PaymentInfo'])) { + $value->setTransactionId($entity['PaymentInfo']['PaymentTransactionID']); + } + } +} \ No newline at end of file diff --git a/Services/Helper/AfterbuyProductsHelper.php b/Services/Helper/AfterbuyProductsHelper.php index 0a9bdb7..189b6b2 100644 --- a/Services/Helper/AfterbuyProductsHelper.php +++ b/Services/Helper/AfterbuyProductsHelper.php @@ -6,16 +6,16 @@ use Exception; use Fatchip\Afterbuy\ApiClient; use viaebShopwareAfterbuy\ValueObjects\Article; +use viaebShopwareAfterbuy\ValueObjects\Article as ValueArticle; use viaebShopwareAfterbuy\ValueObjects\ProductPicture; use viaebShopwareAfterbuy\Components\Helper; -use viaebShopwareAfterbuy\ValueObjects\Article as ValueArticle; /** * Class ShopwareArticleHelper * @package viaebShopwareAfterbuy\Services\Helper */ -class AfterbuyProductsHelper extends ShopwareArticleHelper { - +class AfterbuyProductsHelper extends ShopwareArticleHelper +{ /** * @param array $images * @return array @@ -101,10 +101,12 @@ public function buildAfterbuyVariant(Article $variant, Article $value) 'ManufacturerPartNumber' => $variant->getSupplierNumber(), 'Description' => $variant->getDescription(), 'ShortDescription' => $variant->getShortDescription(), + 'Keywords' => $variant->getKeywords(), 'Weight' => Helper::convertNumberToABString($variant->getWeight()), 'Quantity' => $variant->getStock(), 'UnitOfQuantity' => 'Stk', 'MinimumStock' => $variant->getStockMin(), + 'BuyingPrice' => Helper::convertNumberToABString($variant->getBuyingPrice()), 'SellingPrice' => Helper::convertNumberToABString($variant->getPrice()), 'TaxRate' => Helper::convertNumberToABString($variant->getTax()), 'ProductBrand' => $value->getManufacturer(), @@ -168,6 +170,7 @@ public function buildAfterbuyVariantBaseProduct(Article $value, array $afterbuyP 'Name' => $value->getName(), 'Description' => $value->getDescription(), 'ShortDescription' => $value->getShortDescription(), + 'Keywords' => $value->getKeywords(), 'Weight' => Helper::convertNumberToABString($value->getWeight()), 'UnitOfQuantity' => 'Stk', 'TaxRate' => Helper::convertNumberToABString($value->getTax()), @@ -193,7 +196,6 @@ public function buildAfterbuyVariantBaseProduct(Article $value, array $afterbuyP */ public function buildAfterbuyVariantAssignment(Article $value, array $afterbuyProductIds) { - $variantArticles = []; foreach($value->getVariantArticles() as $variant) { @@ -279,7 +281,6 @@ public function submitAfterbuySimpleProducts(array $data, ApiClient $api, $after */ public function sendAfterbuyProducts(array $products, ApiClient $api, &$afterbuyProductIds = []) { - if(count($products['Products'])) { try { @@ -328,7 +329,9 @@ public function buildAfterbuySimpleProduct(Article $value) 'Quantity' => $value->getStock(), 'UnitOfQuantity' => 'Stk', 'MinimumStock' => $value->getStockMin(), + 'BuyingPrice' => Helper::convertNumberToABString($value->getBuyingPrice()), 'SellingPrice' => Helper::convertNumberToABString($value->getPrice()), + 'Keywords' => $value->getKeywords(), 'TaxRate' => Helper::convertNumberToABString($value->getTax()), 'ProductBrand' => $value->getManufacturer(), 'ImageLargeURL' => $value->getMainImageUrl(), @@ -428,4 +431,159 @@ public function readAttributes(ValueArticle $valueArticle, $product) $valueArticle->setArticleProperties($articleProperties); } + + /** + * @param ValueArticle $valueArticle + * @param array $product + * @return ValueArticle + */ + public function setDefaultArticleValues(ValueArticle $valueArticle, array $product) { + $valueArticle->setEan($product['EAN']); + $valueArticle->setName($product['Name']); + $valueArticle->setPrice(Helper::convertDeString2Float($product['SellingPrice'])); + $valueArticle->setManufacturer($product['ProductBrand']); + $valueArticle->setStock($product['Quantity']); + $valueArticle->setStockMin((int)$product['MinimumStock']); + $valueArticle->setTax(Helper::convertDeString2Float($product['TaxRate'])); + $valueArticle->setDescription($product['Description']); + $valueArticle->setShortDescription($product['ShortDescription']); + $valueArticle->setUnitOfQuantity($product['UnitOfQuantity']); + $valueArticle->setBasePriceFactor($product['BasepriceFactor']); + $valueArticle->setWeight($product['Weight']); + $valueArticle->setSupplierNumber($product['ManufacturerPartNumber']); + $valueArticle->setDiscontinued($product['Discontinued']); + $valueArticle->setBuyingPrice(Helper::convertDeString2Float($product['BuyingPrice'])); + $valueArticle->setKeywords($product['Keywords']); + + $valueArticle->setFree1(key_exists('FreeValue1', $product) ? $product['FreeValue1'] : ''); + $valueArticle->setFree2(key_exists('FreeValue2', $product) ? $product['FreeValue2'] : ''); + $valueArticle->setFree3(key_exists('FreeValue3', $product) ? $product['FreeValue3'] : ''); + $valueArticle->setFree4(key_exists('FreeValue4', $product) ? $product['FreeValue4'] : ''); + $valueArticle->setFree5(key_exists('FreeValue5', $product) ? $product['FreeValue5'] : ''); + $valueArticle->setFree6(key_exists('FreeValue6', $product) ? $product['FreeValue6'] : ''); + $valueArticle->setFree7(key_exists('FreeValue7', $product) ? $product['FreeValue7'] : ''); + $valueArticle->setFree8(key_exists('FreeValue8', $product) ? $product['FreeValue8'] : ''); + $valueArticle->setFree9(key_exists('FreeValue9', $product) ? $product['FreeValue9'] : ''); + $valueArticle->setFree10(key_exists('FreeValue10', $product) ? $product['FreeValue10'] : ''); + + if ((int)$product['Quantity'] > (int)$product['MinimumStock'] && Helper::convertDeString2Float($product['SellingPrice'] > 0)) { + $valueArticle->setActive(true); + } + + return $valueArticle; + } + + /** + * @param array $product + * @param string $targetEntity + * @return ValueArticle + */ + public function createValueArticle(array $product, string $targetEntity) { + /** @var ValueArticle $valueArticle */ + $valueArticle = new $targetEntity(); + + $valueArticle->setExternalIdentifier($product['ProductID']); + $valueArticle->setAnr($product['Anr']); + + if((int)$this->config['ordernumberMapping'] === 1) { + $valueArticle->setOrdernunmber($valueArticle->getAnr()); + } + else { + $valueArticle->setOrdernunmber($valueArticle->getExternalIdentifier()); + } + + return $valueArticle; + } + + /** + * @param ValueArticle $valueArticle + * @param array $product + * @return ValueArticle + */ + public function addCatalogs(ValueArticle $valueArticle, array $product) { + if (array_key_exists('Catalogs', $product) && array_key_exists('CatalogID', $product['Catalogs'])) { + $catalogIDs = $product['Catalogs']['CatalogID']; + if ( ! is_array($catalogIDs)) { + $catalogIDs = [$catalogIDs]; + } + + $valueArticle->setExternalCategoryIds($catalogIDs); + } + + return $valueArticle; + } + + /** + * @param ValueArticle $valueArticle + * @param array $product + * @return ValueArticle + */ + public function setVariants(ValueArticle $valueArticle, array $product) { + $variants = []; + + if (array_key_exists('BaseProductFlag', $product)) { + $valueArticle->setBaseProductFlag($product['BaseProductFlag']); + } + + // variants without attribute option association + if ( + !array_key_exists('Attributes', $product) + && array_key_exists('BaseProducts', $product) + && $valueArticle->getBaseProductFlag() !== ValueArticle::$BASE_PRODUCT_FLAG__VARIATION_SET + && array_key_exists('BaseProductID', $product['BaseProducts']['BaseProduct']) + ) { + $valueArticle->setMainArticleId($product['BaseProducts']['BaseProduct']['BaseProductID']); + + $variants[] = array( + 'option' => 'Variation', + 'value' => $product['Name'], + ); + } + + // variants assigned via after attribute options (e.g. color, size) + if ( + array_key_exists('Attributes', $product) + && array_key_exists('BaseProducts', $product) + && $valueArticle->getBaseProductFlag() !== ValueArticle::$BASE_PRODUCT_FLAG__VARIATION_SET + && array_key_exists('BaseProductID', $product['BaseProducts']['BaseProduct']) + ) { + $valueArticle->setMainArticleId($product['BaseProducts']['BaseProduct']['BaseProductID']); + + + if (array_key_exists('AttributName', $product['Attributes']['Attribut'])) { + $variants[] = array( + 'option' => $product['Attributes']['Attribut']['AttributName'], + 'value' => $product['Attributes']['Attribut']['AttributValue'], + ); + } else { + $variants = []; + + foreach ($product['Attributes']['Attribut'] as $option) { + $variant = array( + 'option' => $option['AttributName'], + 'value' => $option['AttributValue'], + ); + + $variants[] = $variant; + } + } + } + + if ( + key_exists('BaseProductFlag', $product) + and $valueArticle->getBaseProductFlag() !== ValueArticle::$BASE_PRODUCT_FLAG__VARIATION_SET + or !key_exists('BaseProductFlag', $product) + ) { + $this->readAttributes($valueArticle, $product); + } + + if ( + ! empty($variants) + && $valueArticle->getBaseProductFlag() !== ValueArticle::$BASE_PRODUCT_FLAG__VARIATION_SET + ) { + $valueArticle->setVariants($variants); + } + + return $valueArticle; + } } diff --git a/Services/Helper/ShopwareArticleHelper.php b/Services/Helper/ShopwareArticleHelper.php index 706c11b..faaafe3 100644 --- a/Services/Helper/ShopwareArticleHelper.php +++ b/Services/Helper/ShopwareArticleHelper.php @@ -62,6 +62,9 @@ class ShopwareArticleHelper extends AbstractHelper /** @var ConfiguratorGroup[] */ private $configuratorGroups; + /** + * @param ArticleDetail $detail + */ public function fixMissingAttribute(ArticleDetail $detail) { $attr = new ArticlesAttribute(); @@ -70,9 +73,7 @@ public function fixMissingAttribute(ArticleDetail $detail) try { $this->entityManager->persist($detail); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { - $this->logger->error('Error saving attribute'); - } catch (ORMException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving attribute'); } } @@ -141,13 +142,14 @@ public function setSimpleArticleValues(ShopwareArticle $entity, ValueArticle &$a $article->setLastStock(true); } + /** @var Price $price */ $price = $detail->getPrices()->filter(function (Price $price) { return $price->getCustomerGroup() === $this->customerGroup; })->first(); $price = Helper::convertPrice($price->getPrice(), $entity->getTax()->getTax(), $netInput); - $article->setPrice($price); + $article->setBuyingPrice($detail->getPurchasePrice()); $article->setExternalIdentifier($detail->getAttribute()->getAfterbuyId()); $article->setSupplierNumber($detail->getSupplierNumber()); @@ -219,6 +221,7 @@ public function setVariantValues( $price = Helper::convertPrice($price->getPrice(), $entity->getTax()->getTax(), $netInput); $variant->setPrice($price); + $variant->setBuyingPrice($detail->getPurchasePrice()); $variant->setExternalIdentifier($detail->getAttribute()->getAfterbuyId()); @@ -357,6 +360,7 @@ public function setArticleMainValues(ShopwareArticle $entity, string $targetEnti $article->setDescription($entity->getDescriptionLong()); $article->setShortDescription($entity->getDescription()); + $article->setKeywords($entity->getKeywords()); $article->setTax($entity->getTax()->getTax()); @@ -369,7 +373,6 @@ public function setArticleMainValues(ShopwareArticle $entity, string $targetEnti * @param ShopwareArticle $article * @param ArticleDetail $detail * @param array $variants - * @throws ORMException */ public function assignVariants(ShopwareArticle &$article, ArticleDetail $detail, array $variants) { @@ -397,7 +400,6 @@ public function assignVariants(ShopwareArticle &$article, ArticleDetail $detail, * @param array $variants * * @return array - * @throws ORMException */ public function getAssignableConfiguratorOptions(array $variants) { @@ -420,10 +422,10 @@ public function getAssignableConfiguratorOptions(array $variants) $attr = new ConfiguratorOption(); $option->setAttribute($attr); - $this->entityManager->persist($option); try { + $this->entityManager->persist($option); $this->entityManager->flush($option); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error assigning configurator options', array(json_encode($option))); } @@ -587,12 +589,10 @@ public function storePrices(ArticleDetail &$detail, Group $group, float $value, return $price; } - /** * @param string $supplierName * * @return Supplier|string - * @throws ORMException */ public function getSupplier(string $supplierName) { @@ -614,7 +614,6 @@ public function getSupplier(string $supplierName) * @param string $name * * @return Supplier - * @throws ORMException */ public function createSupplier(string $name) { @@ -624,12 +623,10 @@ public function createSupplier(string $name) $attribute = new ArticleSupplier(); $supplier->setAttribute($attribute); - $this->entityManager->persist($supplier); try { + $this->entityManager->persist($supplier); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { - $this->logger->error('Error saving supplier', array($name)); - } catch (ORMException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving supplier', array($name)); } @@ -652,12 +649,20 @@ public function getSuppliers() return $supplier; } + /** + * @param string $number + * @return object|null + */ public function getArticleByNumber(string $number) { $article = $this->entityManager->getRepository(ArticleDetail::class) ->findOneBy(array('number' => $number)); - return $article; + if($article !== null) { + return $article->getArticle(); + } + + return null; } /** @@ -706,6 +711,7 @@ public function getArticleFromAttribute(string $number) /** * returns article. if not available article is needs to be created + * TODO: we should use one identifier, which IS the external or the internal in respect to config * * @param string $number * @param string $name @@ -713,47 +719,39 @@ public function getArticleFromAttribute(string $number) * * @param string $externalIdentifyer * @return ShopwareArticle - * @throws ORMException */ public function getMainArticle(string $number, string $name, $parent = '', $externalIdentifyer = '') { $article = null; + //article variant if ($parent) { $article = $this->getArticleFromAttribute($parent); if(!$article) { $article = $this->getArticleByNumber($parent); } + } - } else { - /** - * @var ArticlesAttribute $article - */ - - if((int)$this->config['ordernumberMapping'] == 1) { - $article = $this->getArticleFromAttribute($externalIdentifyer); - } - else { - $article = $this->getArticleFromAttribute($number); - } + //main article + if(!$parent) { + $article = $this->getMainArticleByIdentifyer($number, $externalIdentifyer); - //TODO: fix here - if ( ! $article) { - $detail = $this->entityManager - ->getRepository(ArticleDetail::class) - ->findOneBy(array('number' => $number)); + //update main article name + if($article) { + $article->setName($name); - if(!empty($detail)) { - $article = $detail->getArticle(); + try { + $this->entityManager->persist($article); } + catch(ORMException $e) { + $this->logger->error($e->getMessage()); + } + } - } else { - //If Baseproduct we just will set the name - $article->setName($name); - $this->entityManager->persist($article); - - return null; + //fallback get article via number of detail + if (!$article) { + $article = $this->getMainArticleFromDetailNumber($number); } } @@ -761,7 +759,43 @@ public function getMainArticle(string $number, string $name, $parent = '', $exte return $article; } - return $this->createMainArticle(); + $article = $this->createMainArticle(); + + return $article; + } + + /** + * @param string $number + * @param string $externalIdentifyer + * @return ShopwareArticle|null + */ + public function getMainArticleByIdentifyer(string $number, string $externalIdentifyer) { + if((int)$this->config['ordernumberMapping'] == 1) { + $article = $this->getArticleFromAttribute($externalIdentifyer); + } + else { + $article = $this->getArticleFromAttribute($number); + } + + return $article; + } + + /** + * @param string $number + * @return ShopwareArticle|null + */ + public function getMainArticleFromDetailNumber(string $number) { + $article = null; + + $detail = $this->entityManager + ->getRepository(ArticleDetail::class) + ->findOneBy(array('number' => $number)); + + if(!empty($detail)) { + $article = $detail->getArticle(); + } + + return $article; } /** @@ -799,20 +833,16 @@ public function getDetail(string $number, ShopwareArticle &$article) * creates and returns the main article * * @return ShopwareArticle - * @throws ORMException */ public function createMainArticle() { $article = new ShopwareArticle(); - $article->setName(uniqid('', true)); - $this->entityManager->persist($article); try { + $this->entityManager->persist($article); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { - $this->logger->error('Error saving temporary main article'); - } catch (ORMException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving temporary main article'); } @@ -838,7 +868,6 @@ public function createDetail(string $number) * @param array $variants * * @return array - * @throws ORMException */ public function getAssignableConfiguratorGroups(array $variants) { @@ -865,7 +894,6 @@ public function getAssignableConfiguratorGroups(array $variants) * @param string $name * * @return ConfiguratorGroup - * @throws ORMException */ public function createConfiguratorGroup(string $name) { @@ -874,12 +902,10 @@ public function createConfiguratorGroup(string $name) $group->setDescription($name); $group->setPosition(1337); - $this->entityManager->persist($group); try { + $this->entityManager->persist($group); $this->entityManager->flush($group); - } catch (OptimisticLockException $e) { - $this->logger->error('Error saving configurator group', array($name)); - } catch (ORMException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving configurator group', array($name)); } @@ -1000,7 +1026,6 @@ public function setArticlesWithoutAnyActiveVariantToInactive() /** * @param $valueArticle ValueArticle * @param $shopwareArticle ShopwareArticle - * @throws ORMException */ public function assignArticleProperties($valueArticle, $shopwareArticle) { @@ -1020,11 +1045,59 @@ public function assignArticleProperties($valueArticle, $shopwareArticle) } } + /** + * @param ValueArticle $valueArticle + * @param ShopwareArticle $shopwareArticle + */ + public function setMainArticleValues(Article $valueArticle, ShopwareArticle &$shopwareArticle) { + if(!$valueArticle->getMainArticleId()) { + $shopwareArticle->setName($valueArticle->getName()); + $shopwareArticle->setDescriptionLong($valueArticle->getDescription()); + $shopwareArticle->setKeywords($valueArticle->getKeywords()); + $shopwareArticle->setDescription($valueArticle->getShortDescription()); + } + } + + /** + * @param ValueArticle $valueArticle + * @param ArticleDetail $articleDetail + */ + public function setDetailValues(Article $valueArticle, ArticleDetail &$articleDetail) { + $articleDetail->setLastStock($valueArticle->getStockMin()); + + $articleDetail->setInStock($valueArticle->getStock()); + $articleDetail->setEan($valueArticle->getEan()); + $articleDetail->setWeight($valueArticle->getWeight()); + $articleDetail->setPurchasePrice($valueArticle->getBuyingPrice()); + + /** @var ShopwareUnit $unit */ + $unit = $this->getUnitFromString($valueArticle->getUnitOfQuantity()); + $articleDetail->setUnit($unit); + $articleDetail->setPurchaseUnit($valueArticle->getBasePriceFactor()); + $articleDetail->setSupplierNumber($valueArticle->getSupplierNumber()); + $articleDetail->setLastStock((int)$valueArticle->getDiscontinued()); + $articleDetail->setReferenceUnit(1); + } + + /** + * @param ValueArticle $valueArticle + * @param ArticleDetail $articleDetail + * @param ShopwareArticle $shopwareArticle + */ + public function setArticleActiveState(Article $valueArticle, ArticleDetail &$articleDetail, ShopwareArticle &$shopwareArticle) { + /** @noinspection PhpDeprecationInspection */ + $shopwareArticle->setLastStock((int)$valueArticle->getDiscontinued()); + + if ($valueArticle->isActive()) { + $articleDetail->setActive(1); + $shopwareArticle->setActive(true); + } + } + /** * @param array $valueArticles * @param bool $netInput * @param Group $customerGroup - * @throws ORMException */ public function importArticle( array $valueArticles, @@ -1042,91 +1115,75 @@ public function importArticle( $valueArticle->getExternalIdentifier() ); - if ( ! $shopwareArticle) { - continue; - } + $this->setMainArticleValues($valueArticle, $shopwareArticle); + + if ($valueArticle->getBaseProductFlag() === Article::$BASE_PRODUCT_FLAG__VARIATION_SET) { - if(!$valueArticle->getMainArticleId()) { - $shopwareArticle->setName($valueArticle->getName()); - $shopwareArticle->setDescriptionLong($valueArticle->getDescription()); + try { + $this->entityManager->persist($shopwareArticle); + $this->entityManager->flush(); + } + catch(OptimisticLockException | ORMException $e) { + $this->logger->error('Error storing base article values!'); + } + continue; } $shopwareArticle->setSupplier($this->getSupplier($valueArticle->getManufacturer())); $shopwareArticle->setTax($this->getTax($valueArticle->getTax())); - /** @var ArticleDetail $articleDetail */ $articleDetail = $this->getDetail($valueArticle->getOrdernunmber(), $shopwareArticle); - - //set main values - $articleDetail->setLastStock($valueArticle->getStockMin()); - - $articleDetail->setInStock($valueArticle->getStock()); - $articleDetail->setEan($valueArticle->getEan()); - $articleDetail->setWeight($valueArticle->getWeight()); - - /** @var ShopwareUnit $unit */ - $unit = $this->getUnitFromString($valueArticle->getUnitOfQuantity()); - $articleDetail->setUnit($unit); - $articleDetail->setPurchaseUnit($valueArticle->getBasePriceFactor()); - $articleDetail->setSupplierNumber($valueArticle->getSupplierNumber()); - $articleDetail->setLastStock((int)$valueArticle->getDiscontinued()); - - - /** @noinspection PhpDeprecationInspection */ - $shopwareArticle->setLastStock((int)$valueArticle->getDiscontinued()); - $articleDetail->setReferenceUnit(1); - - if ($valueArticle->isActive()) { - $articleDetail->setActive(1); - $shopwareArticle->setActive(true); - } - $price = Helper::convertPrice($valueArticle->getPrice(), $valueArticle->getTax(), false, $netInput); + $this->setDetailValues($valueArticle, $articleDetail); + $this->setArticleActiveState($valueArticle, $articleDetail, $shopwareArticle); $this->storePrices($articleDetail, $customerGroup, $price); - - $this->getArticleAttributes($articleDetail, - $valueArticle->getMainArticleId()); - - //TODO: check if external number should be put in here + $this->getArticleAttributes($articleDetail, $valueArticle->getMainArticleId()); $articleDetail->getAttribute()->setAfterbuyInternalNumber($valueArticle->getAnr()); - - $articleDetail->getAttribute()->setAfterbuyFreeText_1($valueArticle->getFree1()); - $articleDetail->getAttribute()->setAfterbuyFreeText_2($valueArticle->getFree2()); - $articleDetail->getAttribute()->setAfterbuyFreeText_3($valueArticle->getFree3()); - $articleDetail->getAttribute()->setAfterbuyFreeText_4($valueArticle->getFree4()); - $articleDetail->getAttribute()->setAfterbuyFreeText_5($valueArticle->getFree5()); - $articleDetail->getAttribute()->setAfterbuyFreeText_6($valueArticle->getFree6()); - $articleDetail->getAttribute()->setAfterbuyFreeText_7($valueArticle->getFree7()); - $articleDetail->getAttribute()->setAfterbuyFreeText_8($valueArticle->getFree8()); - $articleDetail->getAttribute()->setAfterbuyFreeText_9($valueArticle->getFree9()); - $articleDetail->getAttribute()->setAfterbuyFreeText_10($valueArticle->getFree10()); + $this->storeAfterbuyAttributes($articleDetail, $valueArticle); // to make sure we store the 'Afterbuy ProductID' in case the user chooses to use Afterbuy artikelNr as // order number $articleDetail->getAttribute()->setAfterbuyId($valueArticle->getExternalIdentifier()); - $this->assignVariants($shopwareArticle, $articleDetail, $valueArticle->variants); - $this->assignArticleProperties($valueArticle, $shopwareArticle); - - $this->entityManager->persist($shopwareArticle); - //have to flush cuz parent is not getting found otherwise try { + $this->assignVariants($shopwareArticle, $articleDetail, $valueArticle->variants); + $this->assignArticleProperties($valueArticle, $shopwareArticle); + + $this->entityManager->persist($shopwareArticle); + $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { + $this->logger->error($e->getMessage()); } } } + /** + * @param ArticleDetail $articleDetail + * @param ValueArticle $valueArticle + */ + public function storeAfterbuyAttributes(ArticleDetail &$articleDetail, ValueArticle $valueArticle) { + $articleDetail->getAttribute()->setAfterbuyFreeText_1($valueArticle->getFree1()); + $articleDetail->getAttribute()->setAfterbuyFreeText_2($valueArticle->getFree2()); + $articleDetail->getAttribute()->setAfterbuyFreeText_3($valueArticle->getFree3()); + $articleDetail->getAttribute()->setAfterbuyFreeText_4($valueArticle->getFree4()); + $articleDetail->getAttribute()->setAfterbuyFreeText_5($valueArticle->getFree5()); + $articleDetail->getAttribute()->setAfterbuyFreeText_6($valueArticle->getFree6()); + $articleDetail->getAttribute()->setAfterbuyFreeText_7($valueArticle->getFree7()); + $articleDetail->getAttribute()->setAfterbuyFreeText_8($valueArticle->getFree8()); + $articleDetail->getAttribute()->setAfterbuyFreeText_9($valueArticle->getFree9()); + $articleDetail->getAttribute()->setAfterbuyFreeText_10($valueArticle->getFree10()); + } + /** * Returns the ShopwareUnit corresponding to the given unitString. If no unit exists with the given string, a new * one will be created * * @param string $unitString * @return ShopwareUnit - * @throws ORMException */ public function getUnitFromString(string $unitString) { @@ -1142,7 +1199,6 @@ public function getUnitFromString(string $unitString) /** * @param string $unitString * @return ShopwareUnit - * @throws ORMException */ public function createUnitFromString(string $unitString) { @@ -1150,10 +1206,10 @@ public function createUnitFromString(string $unitString) $unit->setUnit($unitString); $unit->setName($unitString); - $this->entityManager->persist($unit); try { + $this->entityManager->persist($unit); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving unit', array($unit)); } @@ -1191,7 +1247,6 @@ public function associateCategories(array $valueArticles) ); if ($articleDetail === null) { - //TODO: fix detail retrieval $detailAttribute = $this->entityManager->getRepository(ArticlesAttribute::class)->findOneBy( ['afterbuyParentId' => $mainArticleId] ); @@ -1216,7 +1271,6 @@ public function associateCategories(array $valueArticles) /** * @param ValueArticle[] $valueArticles - * @throws ORMException */ public function associateImages(array $valueArticles) { @@ -1251,7 +1305,6 @@ public function associateImages(array $valueArticles) * @param ValueArticle $valueArticle * @param ProductPicture $productPicture * @param ArticleDetail $mainDetail - * @throws ORMException */ private function associateImage( ValueArticle $valueArticle, @@ -1327,7 +1380,6 @@ private function associateImage( * @param ValueArticle $valueArticle * @param ImageMapping $imageMapping * @param ArticleImage $image - * @throws ORMException */ private function associateVariantImage( ValueArticle $valueArticle, @@ -1382,10 +1434,15 @@ private function associateVariantImage( } } - if ( ! $image->getMappings()->count()) { - $image->getMappings()->add($imageMapping); - } else { - $this->entityManager->persist($imageMapping); + try { + if (!$image->getMappings()->count()) { + $image->getMappings()->add($imageMapping); + } else { + $this->entityManager->persist($imageMapping); + } + } + catch (ORMException $e) { + $this->logger->error('Error storing variant image association'); } } @@ -1395,7 +1452,6 @@ private function associateVariantImage( * @param ShopwareArticle $article * * @return ArticleImage - * @throws ORMException */ public function createParentImage( Media $media, @@ -1411,11 +1467,11 @@ public function createParentImage( $image->setExtension($media->getExtension()); $image->setMedia($media); - $this->entityManager->persist($image); - try { + $this->entityManager->persist($image); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { + $this->logger->error($e->getMessage()); } return $image; @@ -1426,7 +1482,6 @@ public function createParentImage( * @param ArticleDetail $detail * * @return ArticleImage - * @throws ORMException */ public function createChildImage(ArticleImage $parent, ArticleDetail $detail) { @@ -1437,11 +1492,11 @@ public function createChildImage(ArticleImage $parent, ArticleDetail $detail) $image->setParent($parent); $image->setArticleDetail($detail); - $this->entityManager->persist($image); - try { + $this->entityManager->persist($image); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { + $this->logger->error($e->getMessage()); } return $image; @@ -1493,7 +1548,6 @@ public function manipulateArticleList(array $columnConfig, array $config) /** * @param string $groupName * @return FilterGroup - * @throws ORMException */ public function createFilterGroup(string $groupName) { @@ -1510,10 +1564,10 @@ public function createFilterGroup(string $groupName) $filterGroup->setComparable(0); $filterGroup->setSortMode(0); - $this->entityManager->persist($filterGroup); try { + $this->entityManager->persist($filterGroup); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving FilterGroup'); } } @@ -1525,7 +1579,6 @@ public function createFilterGroup(string $groupName) * @param FilterGroup $filterGroup * @param string $optionName * @return FilterOption - * @throws ORMException */ public function createFilterOption(FilterGroup $filterGroup, string $optionName) { @@ -1550,10 +1603,10 @@ public function createFilterOption(FilterGroup $filterGroup, string $optionName) $option->setName($optionName); $option->setFilterable(1); - $this->entityManager->persist($option); try { + $this->entityManager->persist($option); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving FilterOption'); } @@ -1567,7 +1620,6 @@ public function createFilterOption(FilterGroup $filterGroup, string $optionName) * @param FilterOption $option * @param string $valueName * @return FilterValue - * @throws ORMException */ public function createFilterValue(FilterOption $option, string $valueName) { @@ -1583,14 +1635,16 @@ public function createFilterValue(FilterOption $option, string $valueName) $filterValue = new FilterValue($option, $valueName); $filterValue->setPosition($position); - $this->entityManager->persist($filterValue); + try { + $this->entityManager->persist($filterValue); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error saving FilterValue'); } } return $filterValue; } + } diff --git a/Services/Helper/ShopwareCategoryHelper.php b/Services/Helper/ShopwareCategoryHelper.php index 1fd633c..a3ac781 100644 --- a/Services/Helper/ShopwareCategoryHelper.php +++ b/Services/Helper/ShopwareCategoryHelper.php @@ -3,7 +3,6 @@ namespace viaebShopwareAfterbuy\Services\Helper; -use Doctrine\ORM\ORMException; use Exception; use Shopware\Components\Model\QueryBuilder; use viaebShopwareAfterbuy\ValueObjects\CategoryTreeNode; @@ -206,7 +205,6 @@ public function createCategoryTrees(array $valueCategories) /** * @param CategoryTreeNode[] $valueCategoryTrees * @return ShopwareCategory[] - * @throws ORMException */ public function addCategoriesToShopware(array $valueCategoryTrees) { @@ -230,8 +228,8 @@ public function addCategoriesToShopware(array $valueCategoryTrees) $this->findParentCategory($current->getValueCategory(), 'afterbuyCatalogId') ); - $this->entityManager->persist($shopwareCategories[$externalIdentifier]); try { + $this->entityManager->persist($shopwareCategories[$externalIdentifier]); $this->entityManager->flush(); } catch (Exception $e) { $this->logger->error( @@ -272,21 +270,9 @@ private function createShopwareCategory(ValueCategory $valueCategory) $shopwareCategory->setName($valueCategory->getName()); $shopwareCategory->setMetaDescription($valueCategory->getDescription()); -// if($shopwareCategory->getParent() === null) { -// $shopwareCategory->setParent($this->findParentCategory($valueCategory, $this->identifier)); -// } - $shopwareCategory->setPosition($valueCategory->getPosition()); $shopwareCategory->setCmsText($valueCategory->getCmsText()); $shopwareCategory->setActive($valueCategory->getActive()); -// -// $this->entityManager->persist($shopwareCategory); -// -// try { -// $this->entityManager->flush($shopwareCategory); -// } catch (OptimisticLockException $e) { -// $this->logger->error('Error saving category', array(json_encode($valueCategory))); -// } return $shopwareCategory; } diff --git a/Services/Helper/ShopwareConfigHelper.php b/Services/Helper/ShopwareConfigHelper.php index d2b7bc3..11f9908 100644 --- a/Services/Helper/ShopwareConfigHelper.php +++ b/Services/Helper/ShopwareConfigHelper.php @@ -4,6 +4,7 @@ class ShopwareConfigHelper extends AbstractHelper { + public static $AB_UNI_PAYMENT = 'ab_uni'; public function getConfigValues($pluginName) { $query = $this->dbal->createQueryBuilder(); diff --git a/Services/Helper/ShopwareOrderHelper.php b/Services/Helper/ShopwareOrderHelper.php index b6933fd..9563d33 100644 --- a/Services/Helper/ShopwareOrderHelper.php +++ b/Services/Helper/ShopwareOrderHelper.php @@ -4,9 +4,11 @@ namespace viaebShopwareAfterbuy\Services\Helper; use DateTime; +use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; use Exception; +use Shopware\Components\Model\ModelEntity; use Shopware\Models\Article\Detail as ArticleDetail; use Shopware\Models\Attribute\Order as OrderAttributes; use viaebShopwareAfterbuy\ValueObjects\Address as ValueAddress; @@ -30,7 +32,6 @@ class ShopwareOrderHelper extends AbstractHelper { - protected $paymentStates; protected $shippingStates; @@ -49,11 +50,17 @@ class ShopwareOrderHelper extends AbstractHelper /** @var ShopwareArticleHelper */ protected $articleHelper; + /** + * @param ShopwareArticleHelper $articleHelper + */ public function init(ShopwareArticleHelper $articleHelper) { $this->articleHelper = $articleHelper; } + /** + * + */ public function preFetch() { $this->paymentStates = $this->getPaymentStates(); @@ -64,6 +71,9 @@ public function preFetch() $this->targetGroup = $this->getDefaultGroup(); } + /** + * @return array + */ public function getABCountryCodes() { return array( @@ -318,10 +328,8 @@ public function getABCountryCodes() ); } - /** * @param array $values - * @throws ORMException */ public function setAfterBuyIds(array $values) { @@ -339,12 +347,17 @@ public function setAfterBuyIds(array $values) */ $order->getAttribute()->setAfterbuyOrderId($values[$order->getNumber()]); - $this->entityManager->persist($order); + try { + $this->entityManager->persist($order); + } catch (ORMException $e) { + $this->logger->error('Error storing afterbuy ids'); + exit('Error storing afterbuy ids'); + } } try { $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error storing afterbuy ids'); } } @@ -379,9 +392,12 @@ public function getUnexportedOrders(array $config) ->getResult(); return $orders; - } + /** + * @param ShopwareOrder $order + * @return bool + */ public function isFullfilled(ShopwareOrder $order) { $completelyPaid = $order->getPaymentStatus()->getId() === 12; @@ -391,6 +407,9 @@ public function isFullfilled(ShopwareOrder $order) return $completelyPaid && ($completelyDelivered || $completed); } + /** + * @return mixed + */ public function getNewFullfilledOrders() { $lastExport = $this->entityManager->getRepository(Status::class)->find(1); @@ -420,6 +439,9 @@ public function getNewFullfilledOrders() return $orders; } + /** + * @return array + */ public function getUnfullfilledOrders() { $orders = $this->entityManager->createQueryBuilder() @@ -463,6 +485,10 @@ public function getShippingType(int $id) return $this->shippingType; } + /** + * @param Order $value + * @param ShopwareOrder $order + */ public function setPositions(ValueOrder $value, ShopwareOrder &$order) { $details = $order->getDetails(); @@ -500,11 +526,7 @@ public function setPositions(ValueOrder $value, ShopwareOrder &$order) $detail->setStatus($this->detailStates['1']); } $detail->setArticleName($position->getName()); - try { - $tax = $this->getTax($position->getTax()); - } catch (ORMException $e) { - } - + $tax = $this->getTax($position->getTax()); $detail->setTaxRate($position->getTax()); $detail->setTax($tax); @@ -514,6 +536,12 @@ public function setPositions(ValueOrder $value, ShopwareOrder &$order) } } + /** + * @param Order $value + * @param ShopwareOrder $order + * @param Customer $customer + * @param string $type + */ public function setAddress(ValueOrder $value, ShopwareOrder &$order, Customer $customer, $type = 'billing') { if ($type === 'billing') { @@ -571,10 +599,14 @@ public function setPaymentType(ValueOrder $value, ShopwareOrder &$order, array $ if ($config['payment' . $value->getPaymentType()]) { $order->setPayment($this->paymentTypes[$config['payment' . $value->getPaymentType()]]); } else { - $order->setPayment(array_values($this->paymentTypes)[0]); + $order->setPayment($this->paymentTypes["default"]); } } + /** + * @param Order $value + * @param ShopwareOrder $order + */ public function setOrderTaxValues(ValueOrder $value, ShopwareOrder &$order) { if ( ! $value->getAmountNet()) { @@ -588,6 +620,11 @@ public function setOrderTaxValues(ValueOrder $value, ShopwareOrder &$order) } } + /** + * @param Order $value + * @param ShopwareOrder $order + * @param Shop $shop + */ public function setOrderMainValues(ValueOrder $value, ShopwareOrder &$order, Shop $shop) { /** @@ -634,6 +671,10 @@ public function setShippingStatus(ValueOrder $value, ShopwareOrder &$order) } } + /** + * @param Order $value + * @param ShopwareOrder $order + */ public function setPaymentStatus(ValueOrder $value, ShopwareOrder &$order) { if ($value->getPaid() > 0) { @@ -647,11 +688,18 @@ public function setPaymentStatus(ValueOrder $value, ShopwareOrder &$order) } } + /** + * @param int $id + * @return object|null + */ public function getShop(int $id) { return $this->entityManager->getRepository(Shop::class)->find($id); } + /** + * @return mixed + */ public function getCountries() { $countries = $this->entityManager->createQueryBuilder() @@ -663,6 +711,9 @@ public function getCountries() return $countries; } + /** + * @return mixed + */ public function getPaymentStates() { $states = $this->entityManager->createQueryBuilder() @@ -692,6 +743,9 @@ public function getShippingStates() return $states; } + /** + * @return mixed + */ public function getDetailStates() { $states = $this->entityManager->createQueryBuilder() @@ -704,19 +758,39 @@ public function getDetailStates() } /** + * Returns an indexed array of Payments + * * @return array */ public function getPaymentTypes() { + $AB_UNI_PAYMENT = ShopwareConfigHelper::$AB_UNI_PAYMENT; + $default = $this->entityManager->createQueryBuilder() + ->select('types') + ->from(Payment::class, 'types', 'types.id') + ->where("types.name = '" . $AB_UNI_PAYMENT . "'" ) + ->getQuery() + ->getResult(); + $types = $this->entityManager->createQueryBuilder() ->select('types') ->from(Payment::class, 'types', 'types.id') ->getQuery() ->getResult(); + if(!empty($default)) { + $types["default"] = array_values($default)[0]; + } + return $types; } + /** + * @param Order $order + * @param ValueAddress $billingAddress + * @param Shop $shop + * @return object|Customer|null + */ public function getCustomer(ValueOrder $order, ValueAddress $billingAddress, Shop $shop) { $customer = $this->entityManager->getRepository(Customer::class) @@ -729,6 +803,12 @@ public function getCustomer(ValueOrder $order, ValueAddress $billingAddress, Sho return $this->createCustomer($order, $billingAddress, $shop); } + /** + * @param Order $order + * @param ValueAddress $billingAddress + * @param Shop $shop + * @return Customer + */ public function createCustomer(ValueOrder $order, ValueAddress $billingAddress, Shop $shop) { $customer = new Customer(); @@ -774,15 +854,16 @@ public function createCustomer(ValueOrder $order, ValueAddress $billingAddress, try { $this->entityManager->persist($customer); $this->entityManager->flush(); - } catch (OptimisticLockException $e) { - $this->logger->error('Error writing customer data.'); - } catch (ORMException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error writing customer data.'); } return $customer; } + /** + * @return object|null + */ public function getDefaultGroup() { return $this->entityManager->getRepository(Group::class)->findOneBy(array()); @@ -804,7 +885,7 @@ public function addAfterbuyOrderIdToOrders($orders) } /** - * TODO: Optimize performance + * * @param Order[] $orders */ public function resetArticleChangeTime(array $orders) @@ -835,4 +916,109 @@ public function resetArticleChangeTime(array $orders) $this->logger->error($e->getMessage()); } } + + /** + * @param Billing|Shipping|ModelEntity $entity + * @return ValueAddress + */ + public function buildAddress(ModelEntity $entity) { + $address = new ValueAddress(); + $address->setFirstname($entity->getFirstName()); + $address->setLastname($entity->getLastName()); + $address->setCompany($entity->getCompany()); + $address->setStreet($entity->getStreet()); + + if($entity->getAdditionalAddressLine1()) { + $address->setAdditionalAddressLine1($entity->getAdditionalAddressLine1()); + } + $address->setZipcode($entity->getZipCode()); + $address->setCity($entity->getCity()); + $address->setCountry($entity->getCountry()->getIso()); + $address->setPhone($entity->getPhone()); + + return $address; + } + + /** + * @param ShopwareOrder|ModelEntity $entity + * @return ArrayCollection + */ + public function buildPositions(ShopwareOrder $entity) { + $positions = new ArrayCollection(); + + foreach($entity->getDetails() as $position) { + /** + * @var Detail $position + */ + $orderPosition = new OrderPosition(); + if($position->getEan()) { + $orderPosition->setExternalIdentifier($position->getEan()); + } + + $orderPosition->setInternalIdentifier($position->getArticleNumber()); + $orderPosition->setName($position->getArticleName()); + $orderPosition->setPrice($position->getPrice()); + $orderPosition->setQuantity($position->getQuantity()); + $orderPosition->setTax($position->getTaxRate()); + + $positions->add($orderPosition); + } + + return $positions; + } + + /** + * @param Order $order + * @param ShopwareOrder $entity + */ + public function setOrderValues(Order &$order, ShopwareOrder $entity) { + /** @noinspection PhpParamsInspection */ + $order->setCreateDate($entity->getOrderTime()); + $order->setShipping($entity->getInvoiceShipping()); + + try { + $order->setShippingType($entity->getDispatch()->getName()); + } + catch(Exception $e) { + $order->setShippingType('Standard'); + } + + $order->setPaymentType($entity->getPayment()->getDescription()); + $order->setPaymentTypeId($entity->getPayment()->getId()); + + if($entity->getTaxFree()) { + $order->setTaxFree(true); + } + $order->setInternalIdentifier($entity->getNumber()); + $order->setCurrency($entity->getCurrency()); + $order->setTransactionId($entity->getTransactionId()); + } + + /** + * @param Order $order + * @param ShopwareOrder $entity + */ + public function setOrderStatus(Order &$order, ShopwareOrder $entity) { + if($entity->getPaymentStatus()->getId() === 12) { + $order->setPaid(true); + $order->setCleared(true); + } + } + + /** + * @param Order $order + * @param ValueAddress $billingAddress + * @param ShopwareOrder $entity + */ + public function setOrderCustomerData(Order &$order, ValueAddress &$billingAddress, ShopwareOrder $entity) { + if ($entity->getCustomer()) { + $billingAddress->setEmail($entity->getCustomer()->getEmail()); + $order->setCustomerNumber($entity->getCustomer()->getNumber()); + } + + if ($entity->getCustomer() && $entity->getCustomer()->getBirthday()) { + /** @noinspection PhpParamsInspection */ + $billingAddress->setBirthday($entity->getCustomer()->getBirthday()); + } + } } \ No newline at end of file diff --git a/Services/Helper/ShopwareResetHelper.php b/Services/Helper/ShopwareResetHelper.php index aa34e83..938bc8c 100644 --- a/Services/Helper/ShopwareResetHelper.php +++ b/Services/Helper/ShopwareResetHelper.php @@ -11,87 +11,99 @@ class ShopwareResetHelper extends AbstractHelper { - protected $entities; + protected $shopwareAttributesArray; public function initHelper($entities) { - $this->entities = $entities; + $this->shopwareAttributesArray = $entities; } public function resetShopConnection() + { + $result = $this->resetAttributes(); + + // reset table afterbuy_status + $this->resetStatus(); + + return $result; + } + + /** + * @return array + */ + private function resetAttributes() { $result = [ 'msg' => 'success', 'data' => [], ]; - //TODO: separate into methods (1. reset attributes, 2. reset status) - // reset all afterbuy attributes - foreach ($this->entities as $entity) { - if ($this->resetShopConnectionEntity($entity) !== 'success') { + foreach ($this->shopwareAttributesArray as $shopwareAttributes) { + if ($this->resetShopConnectionEntity($shopwareAttributes) !== 'success') { $result['msg'] = 'failure'; - $result['data'][] = $entity; + $result['data'][] = $shopwareAttributes; } } + return $result; + } - // reset table afterbuy_status + private function resetShopConnectionEntity($shopwareAttributes) + { + $prefix = 'afterbuy'; /** @var ClassMetadata $metadata */ - $metadata = $this->entityManager->getClassMetadata(Status::class); + $metadata = $this->entityManager->getClassMetadata($shopwareAttributes); $builder = $this->entityManager->createQueryBuilder(); - $builder->update(Status::class, 'a'); + $builder->update($shopwareAttributes, 'a'); foreach ($metadata->fieldMappings as $name => $column) { - // skip id column - if ($column['type'] !== 'datetime') { + // skip column names not starting with 'afterbuy' + if (substr($name, 0, strlen($prefix)) !== $prefix) { continue; } $builder->set('a.' . $name, ':null'); } + /** @var Query $builder */ try { $builder - ->setParameter('null', new DateTime('01-01-1970')) + ->setParameter('null', null) ->getQuery() ->execute(); + } catch (Exception $e) { + return 'failure'; } - return $result; + return 'success'; } - private function resetShopConnectionEntity($entity) + private function resetStatus() { - $prefix = 'afterbuy'; - /** @var ClassMetadata $metadata */ - $metadata = $this->entityManager->getClassMetadata($entity); + $metadata = $this->entityManager->getClassMetadata(Status::class); $builder = $this->entityManager->createQueryBuilder(); - $builder->update($entity, 'a'); + $builder->update(Status::class, 'a'); foreach ($metadata->fieldMappings as $name => $column) { - // skip column names not starting with 'afterbuy' - if (substr($name, 0, strlen($prefix)) !== $prefix) { + // skip id column + if ($column['type'] !== 'datetime') { continue; } $builder->set('a.' . $name, ':null'); } - /** @var Query $builder */ try { $builder - ->setParameter('null', null) + ->setParameter('null', new DateTime('01-01-1970')) ->getQuery() ->execute(); - } catch (Exception $e) { - return 'failure'; + $this->logger->error('Error executing reset query!'); } - - return 'success'; } -} \ No newline at end of file +} diff --git a/Services/ReadData/External/ReadCategoriesService.php b/Services/ReadData/External/ReadCategoriesService.php index 88278cc..e79954c 100644 --- a/Services/ReadData/External/ReadCategoriesService.php +++ b/Services/ReadData/External/ReadCategoriesService.php @@ -62,9 +62,7 @@ public function transform(array $data) } foreach ($data as $entity) { - /** - * @var Category $value - */ + /** @var Category $value */ $value = new $this->targetEntity(); foreach ($fieldMappings as list($afterbuyVar, $valueObjVar)) { diff --git a/Services/ReadData/External/ReadOrdersService.php b/Services/ReadData/External/ReadOrdersService.php index cd8f70d..ceb3961 100644 --- a/Services/ReadData/External/ReadOrdersService.php +++ b/Services/ReadData/External/ReadOrdersService.php @@ -7,12 +7,16 @@ use Exception; use Fatchip\Afterbuy\ApiClient; use viaebShopwareAfterbuy\Components\Helper; +use viaebShopwareAfterbuy\Services\Helper\AfterbuyOrderHelper; use viaebShopwareAfterbuy\Services\ReadData\AbstractReadDataService; use viaebShopwareAfterbuy\Services\ReadData\ReadDataInterface; -use viaebShopwareAfterbuy\ValueObjects\Address; use viaebShopwareAfterbuy\ValueObjects\Order; -use viaebShopwareAfterbuy\ValueObjects\OrderPosition; +/** + * Class ReadOrdersService + * @package viaebShopwareAfterbuy\Services\ReadData\External + * @property AfterbuyOrderHelper $helper + */ class ReadOrdersService extends AbstractReadDataService implements ReadDataInterface { /** @@ -37,11 +41,10 @@ public function transform(array $data) { return array(); } - $targetData = array(); - if(!array_key_exists('Orders', $data['Result'])) { return array(); } + $targetData = array(); //handle single result if(array_key_exists('OrderID', $data['Result']['Orders']['Order'])) { @@ -51,13 +54,9 @@ public function transform(array $data) { } foreach($orders as $entity) { - - /** - * @var Order $value - */ + /** @var Order $value */ $value = new $this->targetEntity(); - //mappings for valueObject $value->setExternalIdentifier($entity['OrderID']); $value->setAmount(Helper::convertDeString2Float($entity['PaymentInfo']['FullAmount'])); @@ -70,148 +69,22 @@ public function transform(array $data) { $value->setCustomerNumber('AB' . $entity['BuyerInfo']['BillingAddress']['AfterbuyUserID']); - /** - * set payment type - */ - if(array_key_exists('PaymentFunction', $entity['PaymentInfo'])) { - $value->setPaymentType($entity['PaymentInfo']['PaymentFunction']); - } - - if(array_key_exists('PaymentID', $entity['PaymentInfo'])) { - $value->setPaymentType($entity['PaymentInfo']['PaymentID']); - } - - - //Positions - /** - * structure differs is multiple articles per order / need to handle - */ - - if((int)$entity['SoldItems']['ItemsInOrder'] > 1) { - foreach($entity['SoldItems']['SoldItem'] as $position) { - $orderPosition = new OrderPosition(); - - $orderPosition->setName($position['ItemTitle']); - - if(array_key_exists('ShopProductDetails', $position) && array_key_exists('ProductID', $position['ShopProductDetails'])) { - $orderPosition->setExternalIdentifier($position['ShopProductDetails']['ProductID']); - $orderPosition->setInternalIdentifier($position['ShopProductDetails']['EAN']); - } else { - $orderPosition->setExternalIdentifier($position['ItemID']); - } - - $orderPosition->setQuantity($position['ItemQuantity']); - $orderPosition->setPrice(Helper::convertDeString2Float($position['ItemPrice'])); - $orderPosition->setTax(Helper::convertDeString2Float($position['TaxRate'])); - - $value->getPositions()->add($orderPosition); - - if(Helper::convertDeString2Float($position['TaxRate'])) { - $value->addNetAmount(Helper::convertDeString2Float($position['ItemPrice']) / (1 + Helper::convertDeString2Float($position['TaxRate']) / 100), $position['ItemQuantity']); - } - } - } else { - $orderPosition = new OrderPosition(); - - $orderPosition->setName($entity['SoldItems']['SoldItem']['ItemTitle']); - $orderPosition->setPrice(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['ItemPrice'])); - - if(array_key_exists('ShopProductDetails', $entity['SoldItems']['SoldItem']) && array_key_exists('ProductID', $entity['SoldItems']['SoldItem']['ShopProductDetails'])) { - $orderPosition->setExternalIdentifier($entity['SoldItems']['SoldItem']['ShopProductDetails']['ProductID']); - } else { - $orderPosition->setExternalIdentifier($entity['SoldItems']['SoldItem']['ItemID']); - } - - $orderPosition->setQuantity($entity['SoldItems']['SoldItem']['ItemQuantity']); - $orderPosition->setTax(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['TaxRate'])); - - $value->getPositions()->add($orderPosition); - - if(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['TaxRate'])) { - $value->addNetAmount(Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['ItemPrice']) / (1 + Helper::convertDeString2Float($entity['SoldItems']['SoldItem']['TaxRate']) / 100), - $entity['SoldItems']['SoldItem']['ItemQuantity']); - } - } - - //Shipping Costs - $shippingNet = Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTotalCost']) / (1 + Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTaxRate']) / 100); - - $value->setShippingNet($shippingNet); - $value->setShipping(Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTotalCost'])); - $value->setShippingTax(Helper::convertDeString2Float($entity['ShippingInfo']['ShippingTaxRate'])); - - if(array_key_exists('DeliveryDate', $entity['ShippingInfo'])) { - $value->setShipped(true); - } - - if($shippingNet) { - $value->addNetAmount($shippingNet, 1); - } + $this->helper->setPaymentType($value, $entity); + $this->helper->buildOrderPositions($value, $entity); + $this->helper->setShippingCosts($value, $entity); + $this->helper->setShipmentStatus($value, $entity); + $this->helper->setTransactionDetails($value, $entity); + $this->helper->setBillingAddress($value, $entity); + $this->helper->setShippingAddress($value, $entity); $value->setPaid(Helper::convertDeString2Float($entity['PaymentInfo']['AlreadyPaid'])); - if(array_key_exists('PaymentTransactionID', $entity['PaymentInfo'])) { - $value->setTransactionId($entity['PaymentInfo']['PaymentTransactionID']); - } - - - //Addresses - $billingAddress = new Address(); - - $billingAddress->setFirstname($entity['BuyerInfo']['BillingAddress']['FirstName']); - $billingAddress->setLastname($entity['BuyerInfo']['BillingAddress']['LastName']); - - if($entity['BuyerInfo']['BillingAddress']['Title'] === 'Frau') { - $billingAddress->setSalutation('mrs'); - } else { - $billingAddress->setSalutation('mr'); - } - - $billingAddress->setCompany($entity['BuyerInfo']['BillingAddress']['Company']); - $billingAddress->setStreet($entity['BuyerInfo']['BillingAddress']['Street']); - $billingAddress->setAdditionalAddressLine1($entity['BuyerInfo']['BillingAddress']['Street2']); - $billingAddress->setZipcode($entity['BuyerInfo']['BillingAddress']['PostalCode']); - $billingAddress->setCity($entity['BuyerInfo']['BillingAddress']['City']); - $billingAddress->setCountry($entity['BuyerInfo']['BillingAddress']['CountryISO']); - $billingAddress->setPhone($entity['BuyerInfo']['BillingAddress']['Phone']); - $billingAddress->setVatId($entity['BuyerInfo']['BillingAddress']['TaxIDNumber']); - $billingAddress->setEmail($entity['BuyerInfo']['BillingAddress']['Mail']); - - $value->setBillingAddress($billingAddress); - - if(array_key_exists('ShippingAddress', $entity['BuyerInfo']) && $entity['BuyerInfo']['ShippingAddress']['FirstName'] && !$entity['BuyerInfo']['ShippingAddress']['LastName'] && - $entity['BuyerInfo']['ShippingAddress']['Street'] && $entity['BuyerInfo']['ShippingAddress']['CountryISO'] && $entity['BuyerInfo']['ShippingAddress']['PostalCode']) { - $shippingAddress = new Address(); - - $shippingAddress->setFirstname($entity['BuyerInfo']['ShippingAddress']['FirstName']); - $shippingAddress->setLastname($entity['BuyerInfo']['ShippingAddress']['LastName']); - - - - if(isset($entity['BuyerInfo']['ShippingAddress']['Title']) && $entity['BuyerInfo']['ShippingAddress']['Title'] === 'Frau') { - $shippingAddress->setSalutation('mrs'); - } else { - $shippingAddress->setSalutation('mr'); - } - - $shippingAddress->setCompany($entity['BuyerInfo']['ShippingAddress']['Company']); - $shippingAddress->setStreet($entity['BuyerInfo']['ShippingAddress']['Street']); - $shippingAddress->setAdditionalAddressLine1($entity['BuyerInfo']['ShippingAddress']['Street2']); - $shippingAddress->setZipcode($entity['BuyerInfo']['ShippingAddress']['PostalCode']); - $shippingAddress->setCity($entity['BuyerInfo']['ShippingAddress']['City']); - $shippingAddress->setCountry($entity['BuyerInfo']['ShippingAddress']['CountryISO']); - $shippingAddress->setPhone($entity['BuyerInfo']['ShippingAddress']['Phone']); - - $value->setShippingAddress($shippingAddress); - } - $targetData[] = $value; } return $targetData; } - /** * provides api data. dummy data as used here can be used in tests * diff --git a/Services/ReadData/External/ReadProductsService.php b/Services/ReadData/External/ReadProductsService.php index d5d045a..76f6522 100644 --- a/Services/ReadData/External/ReadProductsService.php +++ b/Services/ReadData/External/ReadProductsService.php @@ -4,15 +4,18 @@ namespace viaebShopwareAfterbuy\Services\ReadData\External; use Fatchip\Afterbuy\ApiClient; -use viaebShopwareAfterbuy\Components\Helper; use viaebShopwareAfterbuy\Services\Helper\AfterbuyProductsHelper; use viaebShopwareAfterbuy\Services\ReadData\AbstractReadDataService; use viaebShopwareAfterbuy\Services\ReadData\ReadDataInterface; use viaebShopwareAfterbuy\ValueObjects\Article as ValueArticle; +/** + * Class ReadProductsService + * @package viaebShopwareAfterbuy\Services\ReadData\External + * @property AfterbuyProductsHelper $helper + */ class ReadProductsService extends AbstractReadDataService implements ReadDataInterface { - /** * @param array $filter * @@ -27,7 +30,7 @@ public function get(array $filter) /** * transforms api input into ValueArticle (targetEntity) - * TODO: refactor + * * @param array $products * * @return ValueArticle[] @@ -49,125 +52,17 @@ public function transform(array $products) continue; } - /** @var ValueArticle $valueArticle */ - $valueArticle = new $this->targetEntity(); - - $valueArticle->setExternalIdentifier($product['ProductID']); - $valueArticle->setAnr($product['Anr']); - - /** TODO: move + refactor start */ - switch ((int)$this->config['ordernumberMapping']) { - case 0: - $valueArticle->setOrdernunmber($valueArticle->getExternalIdentifier()); - break; - case 1: - $valueArticle->setOrdernunmber($valueArticle->getAnr()); - if ( - !$valueArticle->getOrdernunmber() - || $valueArticle->getOrdernunmber() === 0 - || $valueArticle->getOrdernunmber() === '0' - ) { - continue 2; - } - break; - } - /** TODO: move end */ - - $valueArticle->setEan($product['EAN']); - $valueArticle->setName($product['Name']); - $valueArticle->setPrice(Helper::convertDeString2Float($product['SellingPrice'])); - $valueArticle->setManufacturer($product['ProductBrand']); - $valueArticle->setStock($product['Quantity']); - $valueArticle->setStockMin((int)$product['MinimumStock']); - $valueArticle->setTax(Helper::convertDeString2Float($product['TaxRate'])); - $valueArticle->setDescription($product['Description']); - $valueArticle->setUnitOfQuantity($product['UnitOfQuantity']); - $valueArticle->setBasePriceFactor($product['BasepriceFactor']); - $valueArticle->setWeight($product['Weight']); - $valueArticle->setSupplierNumber($product['ManufacturerPartNumber']); - $valueArticle->setDiscontinued($product['Discontinued']); - - $valueArticle->setFree1(key_exists('FreeValue1', $product) ? $product['FreeValue1'] : ''); - $valueArticle->setFree2(key_exists('FreeValue2', $product) ? $product['FreeValue2'] : ''); - $valueArticle->setFree3(key_exists('FreeValue3', $product) ? $product['FreeValue3'] : ''); - $valueArticle->setFree4(key_exists('FreeValue4', $product) ? $product['FreeValue4'] : ''); - $valueArticle->setFree5(key_exists('FreeValue5', $product) ? $product['FreeValue5'] : ''); - $valueArticle->setFree6(key_exists('FreeValue6', $product) ? $product['FreeValue6'] : ''); - $valueArticle->setFree7(key_exists('FreeValue7', $product) ? $product['FreeValue7'] : ''); - $valueArticle->setFree8(key_exists('FreeValue8', $product) ? $product['FreeValue8'] : ''); - $valueArticle->setFree9(key_exists('FreeValue9', $product) ? $product['FreeValue9'] : ''); - $valueArticle->setFree10(key_exists('FreeValue10', $product) ? $product['FreeValue10'] : ''); - - /** @var AfterbuyProductsHelper $helper */ - $helper = $this->helper; - $helper->addProductPictures($product, $valueArticle); - - /** TODO: move start */ - // catalogs - categories - if (array_key_exists('Catalogs', $product) && array_key_exists('CatalogID', $product['Catalogs'])) { - $catalogIDs = $product['Catalogs']['CatalogID']; - if ( ! is_array($catalogIDs)) { - $catalogIDs = [$catalogIDs]; - } - - $valueArticle->setExternalCategoryIds($catalogIDs); - } - /** TODO: move end */ - - if ((int)$product['Quantity'] > (int)$product['MinimumStock'] && Helper::convertDeString2Float($product['SellingPrice'] > 0)) { - $valueArticle->setActive(true); - } - - /** TODO: move start */ - $variants = []; - - if (!array_key_exists('Attributes', $product) && array_key_exists('BaseProducts', $product) && $product['BaseProductFlag'] !== '1' - && array_key_exists('BaseProductID', $product['BaseProducts']['BaseProduct'])) { - $valueArticle->setMainArticleId($product['BaseProducts']['BaseProduct']['BaseProductID']); - - $variants[] = array( - 'option' => 'Variation', - 'value' => $product['Name'], - ); - } - - if (array_key_exists('Attributes', $product) && array_key_exists('BaseProducts', $product) && $product['BaseProductFlag'] !== '1' - && array_key_exists('BaseProductID', $product['BaseProducts']['BaseProduct'])) { - $valueArticle->setMainArticleId($product['BaseProducts']['BaseProduct']['BaseProductID']); - - - if (array_key_exists('AttributName', $product['Attributes']['Attribut'])) { - $variants[] = array( - 'option' => $product['Attributes']['Attribut']['AttributName'], - 'value' => $product['Attributes']['Attribut']['AttributValue'], - ); - } else { - $variants = []; - - foreach ($product['Attributes']['Attribut'] as $option) { - $variant = array( - 'option' => $option['AttributName'], - 'value' => $option['AttributValue'], - ); + $valueArticle = $this->helper->createValueArticle($product, $this->targetEntity); - $variants[] = $variant; - } - } - } - /** TODO: move end */ - - /** TODO: move start */ - if ( - key_exists('BaseProductFlag', $product) and $product['BaseProductFlag'] !== '1' - or !key_exists('BaseProductFlag', $product) - ) { - $helper->readAttributes($valueArticle, $product); + //ignore product if article number is not valid + if(empty($valueArticle->getOrdernunmber() || $valueArticle->getOrdernunmber() === 0 || $valueArticle->getOrdernunmber() === '0')) { + continue; } - if ( ! empty($variants) && $product['BaseProductFlag'] !== '1') { - $valueArticle->setVariants($variants); - } - /** TODO: move end */ + $valueArticle = $this->helper->setDefaultArticleValues($valueArticle, $product); + $this->helper->addProductPictures($product, $valueArticle); + $valueArticle = $this->helper->addCatalogs($valueArticle, $product); + $valueArticle = $this->helper->setVariants($valueArticle, $product); if(!$valueArticle->getMainArticleId()) { $valueArticles[] = $valueArticle; @@ -190,7 +85,6 @@ public function transform(array $products) */ public function read(array $filter) { - $resource = new ApiClient($this->apiConfig, $this->logger); $data = $resource->getAllShopProductsFromAfterbuy($filter); diff --git a/Services/ReadData/Internal/ReadOrdersService.php b/Services/ReadData/Internal/ReadOrdersService.php index 5a9f056..71a6546 100644 --- a/Services/ReadData/Internal/ReadOrdersService.php +++ b/Services/ReadData/Internal/ReadOrdersService.php @@ -2,25 +2,15 @@ namespace viaebShopwareAfterbuy\Services\ReadData\Internal; -use Exception; -use viaebShopwareAfterbuy\Services\Helper\ShopwareOrderHelper; -use Doctrine\Common\Collections\ArrayCollection; use viaebShopwareAfterbuy\Services\ReadData\AbstractReadDataService; use viaebShopwareAfterbuy\Services\ReadData\ReadDataInterface; -use viaebShopwareAfterbuy\ValueObjects\Address; use viaebShopwareAfterbuy\ValueObjects\Order; -use viaebShopwareAfterbuy\ValueObjects\OrderPosition; -use Shopware\Models\Order\Detail; use Shopware\Models\Order\Repository; class ReadOrdersService extends AbstractReadDataService implements ReadDataInterface { - /** @var ShopwareOrderHelper */ - public $helper; - /** * @param array $filter * @return array|null - * @throws Exception */ public function get(array $filter) { $data = $this->read($filter); @@ -43,110 +33,31 @@ public function transform(array $data) { $targetData = array(); foreach($data as $entity) { - /** - * @var \Shopware\Models\Order\Order $entity - */ - /** ignore order if not valid */ if($entity->getBilling() === null || $entity->getDetails() === null) { continue; } - /** - * @var Order $order - */ + /** @var Order $order */ $order = new $this->targetEntity(); - $positions = new ArrayCollection(); - - foreach($entity->getDetails() as $position) { - /** - * @var Detail $position - */ - $orderPosition = new OrderPosition(); - if($position->getEan()) { - $orderPosition->setExternalIdentifier($position->getEan()); - } - - $orderPosition->setInternalIdentifier($position->getArticleNumber()); - $orderPosition->setName($position->getArticleName()); - $orderPosition->setPrice($position->getPrice()); - $orderPosition->setQuantity($position->getQuantity()); - $orderPosition->setTax($position->getTaxRate()); - - $positions->add($orderPosition); - } - + //set order positions + $positions = $this->helper->buildPositions($entity); $order->setPositions($positions); - $billingAddress = new Address(); - $billingAddress->setFirstname($entity->getBilling()->getFirstName()); - $billingAddress->setLastname($entity->getBilling()->getLastName()); - $billingAddress->setCompany($entity->getBilling()->getCompany()); - $billingAddress->setStreet($entity->getBilling()->getStreet()); - - if($entity->getBilling()->getAdditionalAddressLine1()) { - $billingAddress->setAdditionalAddressLine1($entity->getBilling()->getAdditionalAddressLine1()); - } - $billingAddress->setZipcode($entity->getBilling()->getZipCode()); - $billingAddress->setCity($entity->getBilling()->getCity()); - $billingAddress->setCountry($entity->getBilling()->getCountry()->getIso()); - $billingAddress->setPhone($entity->getBilling()->getPhone()); - - if ($entity->getCustomer()) { - $billingAddress->setEmail($entity->getCustomer()->getEmail()); - $order->setCustomerNumber($entity->getCustomer()->getNumber()); - } - - if ($entity->getCustomer() && $entity->getCustomer()->getBirthday()) { - /** @noinspection PhpParamsInspection */ - $billingAddress->setBirthday($entity->getCustomer()->getBirthday()); - } + //set address related information + $billingAddress = $this->helper->buildAddress($entity->getBilling()); + $shippingAddress = $this->helper->buildAddress($entity->getShipping()); - $shippingAddress = new Address(); - $shippingAddress->setFirstname($entity->getShipping()->getFirstName()); - $shippingAddress->setLastname($entity->getShipping()->getLastName()); - $shippingAddress->setCompany($entity->getShipping()->getCompany()); - $shippingAddress->setStreet($entity->getShipping()->getStreet()); - if($entity->getShipping()->getAdditionalAddressLine1()) { - $shippingAddress->setAdditionalAddressLine1($entity->getShipping()->getAdditionalAddressLine1()); - } - $shippingAddress->setZipcode($entity->getShipping()->getZipCode()); - $shippingAddress->setCity($entity->getShipping()->getCity()); - $shippingAddress->setCountry($entity->getShipping()->getCountry()->getIso()); + //set customer related data + $this->helper->setOrderCustomerData($order, $billingAddress, $entity); $order->setBillingAddress($billingAddress); $order->setShippingAddress($shippingAddress); - /** @noinspection PhpParamsInspection */ - $order->setCreateDate($entity->getOrderTime()); - $order->setShipping($entity->getInvoiceShipping()); - - try { - $shippingType = $entity->getDispatch(); - $order->setShippingType($shippingType->getName()); - } - catch(Exception $e) { - $order->setShippingType('Standard'); - } - - $order->setPaymentType($entity->getPayment()->getName()); - $order->setPaymentTypeId($entity->getPayment()->getId()); - - if($entity->getTaxFree()) { - $order->setTaxFree(true); - } - - $order->setInternalIdentifier($entity->getNumber()); - - $order->setCurrency($entity->getCurrency()); - - if($entity->getPaymentStatus()->getId() === 12) { - $order->setPaid(true); - $order->setCleared(true); - } - - $order->setTransactionId($entity->getTransactionId()); + //set values + $this->helper->setOrderValues($order, $entity); + $this->helper->setOrderStatus($order, $entity); $targetData[] = $order; } @@ -160,7 +71,6 @@ public function transform(array $data) { * * @param array $filter * @return array - * @throws Exception */ public function read(array $filter) { diff --git a/Services/ReadData/Internal/ReadProductsService.php b/Services/ReadData/Internal/ReadProductsService.php index b62072e..893a37b 100644 --- a/Services/ReadData/Internal/ReadProductsService.php +++ b/Services/ReadData/Internal/ReadProductsService.php @@ -7,13 +7,15 @@ use viaebShopwareAfterbuy\Services\ReadData\AbstractReadDataService; use viaebShopwareAfterbuy\Services\ReadData\ReadDataInterface; +/** + * Class ReadProductsService + * @package viaebShopwareAfterbuy\Services\ReadData\Internal + * @property ShopwareArticleHelper $helper + */ class ReadProductsService extends AbstractReadDataService implements ReadDataInterface { protected $customerGroup; - /** @var ShopwareArticleHelper */ - public $helper; - /** * @param array $filter * @return array|null @@ -32,16 +34,11 @@ public function get(array $filter) { public function transform(array $data) { $this->logger->debug('Receiving products from shop', $data); - /** - * @var ShopwareArticleHelper $helper - */ - $helper = $this->helper; - if($this->targetEntity === null) { return array(); } - $this->customerGroup = $helper->getDefaultCustomerGroup($this->config['customerGroup']); + $this->customerGroup = $this->helper->getDefaultCustomerGroup($this->config['customerGroup']); if($this->customerGroup === null) { $this->logger->error('Default customer group not defined'); @@ -65,13 +62,13 @@ public function transform(array $data) { } /** @var Article $entity */ - $article = $helper->setArticleMainValues($entity, $this->targetEntity); - $helper->assignCategories($article, $entity); - $helper->assignArticleImages($entity, $article); + $article = $this->helper->setArticleMainValues($entity, $this->targetEntity); + $this->helper->assignCategories($article, $entity); + $this->helper->assignArticleImages($entity, $article); if(!$entity->getConfiguratorSet()) { //simple article - $helper->setSimpleArticleValues($entity, $article, $netInput); + $this->helper->setSimpleArticleValues($entity, $article, $netInput); } else { $article->setInternalIdentifier('AB' . $entity->getMainDetail()->getNumber()); @@ -82,13 +79,11 @@ public function transform(array $data) { $this->helper->fixMissingAttribute($detail); } - $variant = $helper->setVariantValues($entity, $detail, $this->targetEntity, $netInput); + $variant = $this->helper->setVariantValues($entity, $detail, $this->targetEntity, $netInput); - $helper->assignArticleImages($entity, $variant, $detail); + $this->helper->assignArticleImages($entity, $variant, $detail); - if($article->getVariantArticles() !== null) { - $article->getVariantArticles()->add($variant); - } + $article->getVariantArticles()->add($variant); } } diff --git a/Services/ReadData/Internal/ReadStatusService.php b/Services/ReadData/Internal/ReadStatusService.php index bc175a6..ade110f 100644 --- a/Services/ReadData/Internal/ReadStatusService.php +++ b/Services/ReadData/Internal/ReadStatusService.php @@ -13,6 +13,10 @@ class ReadStatusService extends AbstractReadDataService implements ReadDataInterface { + /** + * @param array $filter + * @return array|mixed + */ public function get(array $filter) { $data = $this->read($filter); @@ -20,6 +24,10 @@ public function get(array $filter) return $this->transform($data); } + /** + * @param array $orders + * @return array|mixed + */ public function transform(array $orders) { $this->logger->debug('Receiving updated orders from shop', $orders); @@ -31,10 +39,7 @@ public function transform(array $orders) $values = []; foreach ($orders as $order) { - /** - * @var Order $order - */ - + /** @var Order $order */ if(!$order->getAttribute()->getAfterbuyOrderId()) { continue; } @@ -58,7 +63,10 @@ public function transform(array $orders) return $values; } - + /** + * @param array $filter + * @return mixed + */ public function read(array $filter) { /** diff --git a/Services/WriteData/External/WriteCategoriesService.php b/Services/WriteData/External/WriteCategoriesService.php index e046236..0953434 100644 --- a/Services/WriteData/External/WriteCategoriesService.php +++ b/Services/WriteData/External/WriteCategoriesService.php @@ -4,7 +4,6 @@ use Exception; use Fatchip\Afterbuy\ApiClient; -use viaebShopwareAfterbuy\Services\Helper\ShopwareCategoryHelper; use viaebShopwareAfterbuy\Services\WriteData\AbstractWriteDataService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; use viaebShopwareAfterbuy\ValueObjects\Category as ValueCategory; @@ -22,9 +21,6 @@ class WriteCategoriesService extends AbstractWriteDataService implements WriteDa */ protected $isAttribute; - /** @var ShopwareCategoryHelper $helper */ - public $helper; - /** * @param ValueCategory[] $valueCategories * diff --git a/Services/WriteData/External/WriteOrdersService.php b/Services/WriteData/External/WriteOrdersService.php index 6c85753..c3dff7a 100644 --- a/Services/WriteData/External/WriteOrdersService.php +++ b/Services/WriteData/External/WriteOrdersService.php @@ -12,13 +12,15 @@ use viaebShopwareAfterbuy\ValueObjects\Order; use viaebShopwareAfterbuy\ValueObjects\OrderPosition; +/** + * Class WriteOrdersService + * @package viaebShopwareAfterbuy\Services\WriteData\External + * @property ShopwareOrderHelper $helper + */ class WriteOrdersService extends AbstractWriteDataService implements WriteDataInterface { protected $ABCountries; - /** @var ShopwareOrderHelper $helper */ - public $helper; - /** * @param array $data * @return array|null @@ -42,12 +44,7 @@ public function transform(array $data) { $orders = []; - /** - * @var ShopwareOrderHelper $helper - */ - $helper = $this->helper; - - $this->ABCountries = $helper->getABCountryCodes(); + $this->ABCountries = $this->helper->getABCountryCodes(); foreach($data as $value) { /** @@ -60,6 +57,7 @@ public function transform(array $data) { $internalIdentifyer = $value->getInternalIdentifier(); + /** @noinspection PhpNonStrictObjectEqualityInspection */ $orders[$value->getInternalIdentifier()] = array( 'PosAnz' => $value->getPositions()->count(), 'Kbenutzername' => $value->getCustomerNumber(), @@ -72,6 +70,8 @@ public function transform(array $data) { 'KOrt' => $value->getBillingAddress()->getCity(), 'KLand' => $this->ABCountries[$value->getBillingAddress()->getCountry()], + 'Lieferanschrift' => ($value->getBillingAddress()->compare($value->getShippingAddress())) ? 0 : 1, + 'KLFirma' => $value->getShippingAddress()->getCompany(), 'KLVorname' => $value->getShippingAddress()->getFirstname(), 'KLNachname' => $value->getShippingAddress()->getLastname(), diff --git a/Services/WriteData/External/WriteProductsService.php b/Services/WriteData/External/WriteProductsService.php index eefbbb1..c029791 100644 --- a/Services/WriteData/External/WriteProductsService.php +++ b/Services/WriteData/External/WriteProductsService.php @@ -7,13 +7,13 @@ use viaebShopwareAfterbuy\Services\Helper\AfterbuyProductsHelper; use viaebShopwareAfterbuy\Services\WriteData\AbstractWriteDataService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; -use Shopware\Models\Customer\Group; - +/** + * Class WriteProductsService + * @package viaebShopwareAfterbuy\Services\WriteData\External + * @property AfterbuyProductsHelper $helper + */ class WriteProductsService extends AbstractWriteDataService implements WriteDataInterface { - /** @var AfterbuyProductsHelper */ - public $helper; - /** * @param null|array $data * @return mixed @@ -32,29 +32,19 @@ public function put(array $data) { */ public function transform(array $data) { $this->logger->debug('Storing ' . count($data) . ' items.', array($data)); - /** - * @var Group $customerGroup - */ $api = new ApiClient($this->apiConfig, $this->logger); - /** - * @var AfterbuyProductsHelper $helper - */ - $helper = $this->helper; - - //TODO: move to send method - $afterbuyProductIds = $helper->submitAfterbuySimpleProducts($data, $api); + $afterbuyProductIds = $this->helper->submitAfterbuySimpleProducts($data, $api); - $afterbuyProductIds = $helper->submitAfterbuyVariantProducts($data, $api, $afterbuyProductIds); + $afterbuyProductIds = $this->helper->submitAfterbuyVariantProducts($data, $api, $afterbuyProductIds); return $afterbuyProductIds; } - /** * @param $targetData - * @return mixed * + * @return mixed */ public function send($targetData) { diff --git a/Services/WriteData/Internal/WriteCategoriesService.php b/Services/WriteData/Internal/WriteCategoriesService.php index b5d3699..ecd5426 100644 --- a/Services/WriteData/Internal/WriteCategoriesService.php +++ b/Services/WriteData/Internal/WriteCategoriesService.php @@ -2,7 +2,6 @@ namespace viaebShopwareAfterbuy\Services\WriteData\Internal; -use Doctrine\ORM\ORMException; use viaebShopwareAfterbuy\Services\Helper\ShopwareCategoryHelper; use viaebShopwareAfterbuy\Services\WriteData\AbstractWriteDataService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; @@ -24,7 +23,6 @@ class WriteCategoriesService extends AbstractWriteDataService implements WriteDa /** * @param array $data * @return mixed - * @throws ORMException */ public function put(array $data) { @@ -38,7 +36,6 @@ public function put(array $data) * @param ValueCategory[] $valueCategories * * @return mixed - * @throws ORMException */ public function transform(array $valueCategories) { @@ -54,38 +51,6 @@ public function transform(array $valueCategories) $shopwareCategories = $categoryHelper->addCategoriesToShopware($valueCategoryTrees); -// $valueCategories = $categoryHelper->sortValueCategoriesByParentID($valueCategories); -// -// foreach ($valueCategories as $valueCategory) { -// /** -// * @var ShopwareCategory $shopwareCategory -// */ -// $shopwareCategory = $categoryHelper->getEntity( -// $valueCategory->getExternalIdentifier(), -// $this->identifier, -// $this->isAttribute -// ); -// -// $shopwareCategory->setName($valueCategory->getName()); -// $shopwareCategory->setMetaDescription($valueCategory->getDescription()); -// -// if($shopwareCategory->getParent() === null) { -// $shopwareCategory->setParent($categoryHelper->findParentCategory($valueCategory, $this->identifier)); -// } -// -// $shopwareCategory->setPosition($valueCategory->getPosition()); -// $shopwareCategory->setCmsText($valueCategory->getCmsText()); -// $shopwareCategory->setActive($valueCategory->getActive()); -// -// $this->entityManager->persist($shopwareCategory); -// -// try { -// $this->entityManager->flush($shopwareCategory); -// } catch (OptimisticLockException $e) { -// $this->logger->error('Error saving category', array(json_encode($valueCategory))); -// } -// } - return $shopwareCategories; } diff --git a/Services/WriteData/Internal/WriteOrdersService.php b/Services/WriteData/Internal/WriteOrdersService.php index b877b43..1496b0d 100644 --- a/Services/WriteData/Internal/WriteOrdersService.php +++ b/Services/WriteData/Internal/WriteOrdersService.php @@ -5,19 +5,19 @@ use Doctrine\ORM\ORMException; use Exception; +use Shopware\Models\Order\Order; use viaebShopwareAfterbuy\Models\Status; use viaebShopwareAfterbuy\Services\Helper\ShopwareOrderHelper; use viaebShopwareAfterbuy\Services\WriteData\AbstractWriteDataService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; -use viaebShopwareAfterbuy\ValueObjects\Order; use Shopware\Models\Shop\Shop; +/** + * Class WriteOrdersService + * @package viaebShopwareAfterbuy\Services\WriteData\Internal + * @property ShopwareOrderHelper $helper + */ class WriteOrdersService extends AbstractWriteDataService implements WriteDataInterface { - - /** - * @var ShopwareOrderHelper $helper - */ - /** * @var array */ @@ -31,7 +31,6 @@ class WriteOrdersService extends AbstractWriteDataService implements WriteDataIn /** * @param array $data * @return mixed - * @throws ORMException */ public function put(array $data) { $data = $this->transform($data); @@ -44,19 +43,15 @@ public function put(array $data) { * * @param array $data * @return mixed - * @throws ORMException */ public function transform(array $data) { - /** @var ShopwareOrderHelper $helper */ - $helper = $this->helper; - if($this->config['targetShop'] === null) { $this->logger->error('Target shop not defined'); exit('Target shop not defined'); } - $this->targetShop = $helper->getShop($this->config['targetShop']); - $this->countries = $helper->getCountries(); + $this->targetShop = $this->helper->getShop($this->config['targetShop']); + $this->countries = $this->helper->getCountries(); foreach($data as $value) { //log and ignore order if country is not setup in shop @@ -74,64 +69,37 @@ public function transform(array $data) { $this->logger->error('Default shipping import type not set.'); exit('Default shipping import type not set.'); } - - /** - * @var Order $value - */ - - /** - * @var \Shopware\Models\Order\Order $order - */ - $order = $helper->getEntity($value->getExternalIdentifier(), 'number'); + /** @var Order $order */ + $order = $this->helper->getEntity($value->getExternalIdentifier(), 'number'); //fullfilled orders should not get updated - if($order->getId() && $helper->isFullfilled($order)) { + if($order->getId() && $this->helper->isFullfilled($order)) { continue; } - $helper->setOrderMainValues($value, $order, $this->targetShop); - $helper->setOrderTaxValues($value, $order); - - /** - * set payment status - */ - $helper->setPaymentStatus($value, $order); - - /** - * set shipping status - */ - $helper->setShippingStatus($value, $order); + $this->helper->setOrderMainValues($value, $order, $this->targetShop); + $this->helper->setOrderTaxValues($value, $order); + $this->helper->setPaymentStatus($value, $order); + $this->helper->setShippingStatus($value, $order); + $this->helper->setPaymentType($value, $order, $this->config); - /** - * set payment type - */ - $helper->setPaymentType($value, $order, $this->config); - - $customer = $helper->getCustomer($value, $value->getBillingAddress(), $this->targetShop); + $customer = $this->helper->getCustomer($value, $value->getBillingAddress(), $this->targetShop); $order->setCustomer($customer); - /** - * set billing address - */ if($customer === null) { continue; } - $helper->setAddress($value, $order, $customer); - - /** - * set shipping address - */ - $helper->setAddress($value, $order, $customer, 'shipping'); - - /** - * set and update positions - */ - $helper->setPositions($value, $order); - - $helper->setShippingType($order, $this->config['shipping']); + $this->helper->setAddress($value, $order, $customer); + $this->helper->setAddress($value, $order, $customer, 'shipping'); + $this->helper->setPositions($value, $order); + $this->helper->setShippingType($order, $this->config['shipping']); - $this->entityManager->persist($order); + try { + $this->entityManager->persist($order); + } catch (ORMException $e) { + $this->logger->error('ORMException while storing order'); + } } return $data; @@ -143,10 +111,7 @@ public function transform(array $data) { * @return mixed */ public function send($targetData) { - /** @var ShopwareOrderHelper $helper */ - $helper = $this->helper; - - $helper->resetArticleChangeTime($targetData); + $this->helper->resetArticleChangeTime($targetData); try { $this->entityManager->flush(); @@ -160,6 +125,10 @@ public function send($targetData) { return array(); } + /** + * @param bool $force + * @return array + */ public function getOrderImportDateFilter(bool $force) { if($force) { diff --git a/Services/WriteData/Internal/WriteProductsService.php b/Services/WriteData/Internal/WriteProductsService.php index db80492..dff6846 100644 --- a/Services/WriteData/Internal/WriteProductsService.php +++ b/Services/WriteData/Internal/WriteProductsService.php @@ -6,7 +6,6 @@ use Doctrine\ORM\ORMException; use viaebShopwareAfterbuy\Models\Status; -use viaebShopwareAfterbuy\Services\Helper\ShopwareArticleHelper; use viaebShopwareAfterbuy\Services\WriteData\AbstractWriteDataService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; use viaebShopwareAfterbuy\ValueObjects\Article as ValueArticle; @@ -15,15 +14,10 @@ class WriteProductsService extends AbstractWriteDataService implements WriteDataInterface { - - /** @var ShopwareArticleHelper $helper */ - public $helper; - /** * @param array $data * * @return array - * @throws ORMException */ public function put(array $data) { @@ -37,7 +31,6 @@ public function put(array $data) * could may be moved into separate helper * * @param ValueArticle[] $valueArticles - * @throws ORMException */ public function transform(array $valueArticles) { @@ -75,10 +68,9 @@ public function send($targetData) { try { $this->entityManager->flush(); - } catch (OptimisticLockException $e) { + } catch (OptimisticLockException | ORMException $e) { $this->logger->error('Error storing products', $targetData); exit('Error storing products'); - } catch (ORMException $e) { } if(!empty($targetData)) { diff --git a/Services/WriteData/Internal/WriteStatusService.php b/Services/WriteData/Internal/WriteStatusService.php index 4c3cd35..f9f8e90 100644 --- a/Services/WriteData/Internal/WriteStatusService.php +++ b/Services/WriteData/Internal/WriteStatusService.php @@ -3,13 +3,11 @@ namespace viaebShopwareAfterbuy\Services\WriteData\Internal; -use Doctrine\ORM\ORMException; use Exception; use Shopware\Models\Order\Order; use viaebShopwareAfterbuy\Services\Helper\ShopwareOrderHelper; use viaebShopwareAfterbuy\Services\WriteData\AbstractWriteDataService; use viaebShopwareAfterbuy\Services\WriteData\WriteDataInterface; -use Shopware\Models\Shop\Shop; class WriteStatusService extends AbstractWriteDataService implements WriteDataInterface { @@ -22,14 +20,9 @@ class WriteStatusService extends AbstractWriteDataService implements WriteDataIn */ protected $countries; - /** @var ShopwareOrderHelper */ - public $helper; - - /** * @param array $data * @return mixed - * @throws ORMException */ public function put(array $data) { $data = $this->transform($data); @@ -42,7 +35,6 @@ public function put(array $data) { * * @param array $data * @return mixed - * @throws ORMException */ public function transform(array $data) { @@ -60,7 +52,12 @@ public function transform(array $data) { $this->helper->setShippingStatus($value, $order); - $this->entityManager->persist($order); + try { + $this->entityManager->persist($order); + } + catch(Exception $e) { + $this->logger->error('Error updating order state', array($order->getId())); + } } try { diff --git a/Subscriber/ControllerPath.php b/Subscriber/ControllerPath.php index cb10780..967337c 100644 --- a/Subscriber/ControllerPath.php +++ b/Subscriber/ControllerPath.php @@ -1,4 +1,5 @@ controller->Request()->getActionName() == 'load') { $this->view->extendsTemplate('backend/viaeb_extend_article_list/view/list_view.js'); } elseif ($this->controller->Request()->getActionName() == 'columnConfig') { - /** @var ShopwareArticleHelper $orderHelper */ - $orderHelper = $this->helper; $columnConfig = $this->controller->View()->getAssign(); - $columnConfig = $orderHelper->manipulateArticleList($columnConfig, $this->config); + $columnConfig = $this->helper->manipulateArticleList($columnConfig, $this->config); $this->controller->View()->assign($columnConfig); } diff --git a/Subscriber/PostDispatchSecureBackendOrder.php b/Subscriber/PostDispatchSecureBackendOrder.php index eef2eba..3ee6c60 100644 --- a/Subscriber/PostDispatchSecureBackendOrder.php +++ b/Subscriber/PostDispatchSecureBackendOrder.php @@ -5,6 +5,11 @@ use viaebShopwareAfterbuy\Services\Helper\ShopwareOrderHelper; +/** + * Class PostDispatchSecureBackendOrder + * @package viaebShopwareAfterbuy\Subscriber + * @property ShopwareOrderHelper $helper + */ class PostDispatchSecureBackendOrder extends AbstractPostDispatchSecureBackend { /** @noinspection PhpUnused */ @@ -14,13 +19,8 @@ public function onPostDispatchSecureBackendOrder() $this->view->extendsTemplate('backend/viaeb_extend_order/view/list_view.js'); $this->view->extendsTemplate('backend/viaeb_extend_order/model/order_model.tpl'); } elseif ($this->controller->Request()->getActionName() === 'getList') { - /** @var ShopwareOrderHelper $orderHelper */ - $orderHelper = $this->helper; - $orders = $this->controller->View()->getAssign(); - - $orders = $orderHelper->addAfterbuyOrderIdToOrders($orders); - + $orders = $this->helper->addAfterbuyOrderIdToOrders($orders); $this->controller->View()->assign($orders); } } diff --git a/ValueObjects/Address.php b/ValueObjects/Address.php index b1532a2..69f0fa5 100755 --- a/ValueObjects/Address.php +++ b/ValueObjects/Address.php @@ -4,8 +4,9 @@ namespace viaebShopwareAfterbuy\ValueObjects; use DateTime; +use JsonSerializable; -class Address extends AbstractValueObject +class Address extends AbstractValueObject implements JsonSerializable { /** * Contains the name of the address address company @@ -113,6 +114,23 @@ class Address extends AbstractValueObject */ protected $birthday; + /** + * @return array + */ + function jsonSerialize() { + return [ + 'company' => $this->company, + 'firstname' => $this->firstname, + 'lastname' => $this->lastname, + 'street' => $this->street, + 'additionalAddressLine1' => $this->additionalAddressLine1, + 'zip' => $this->zipcode, + 'city' => $this->city, + 'country' => $this->country, + 'phone' => $this->phone + ]; + } + /** * @return DateTime */ @@ -386,5 +404,13 @@ public function setEmail(string $email) $this->email = $email; } - + /** + * used to compare billing and shippings address by ignoring several properties. relevant properties are defined in jsonSerialize + * + * @param Address $addr + * @return bool + */ + public function compare(Address $addr) { + return json_encode($this) === json_encode($addr); + } } diff --git a/ValueObjects/Article.php b/ValueObjects/Article.php index 8a75d2a..2216522 100644 --- a/ValueObjects/Article.php +++ b/ValueObjects/Article.php @@ -7,6 +7,9 @@ class Article extends AbstractValueObject { + public static $BASE_PRODUCT_FLAG__VARIATION_SET = '1'; + public static $BASE_PRODUCT_FLAG__PRODUCT_SET = '2'; + public static $BASE_PRODUCT_FLAG__SET_ENTITY = '3'; /** * we cannot define external identifier types, we have to handle those as strings @@ -22,6 +25,17 @@ class Article extends AbstractValueObject */ public $internalIdentifier; + + /** + * @var string + */ + public $keywords; + + /** + * @var float + */ + public $buyingPrice = 0.00; + /** * @var int */ @@ -47,24 +61,54 @@ class Article extends AbstractValueObject */ public $ean; + /** + * @var + */ public $stockMin; + /** + * @var float + */ public $pseudoPrice; + /** + * @var float + */ public $tax; + /** + * @var array + */ public $variants = []; + /** + * @var + */ public $mainArticleId; + /** + * @var string + */ public $description; + /** + * @var + */ public $supplierNumber; + /** + * @var string + */ public $shortDescription; + /** + * @var + */ public $variantId; + /** + * @var array + */ public $externalCategoryIds = []; /** @var bool */ @@ -91,6 +135,9 @@ class Article extends AbstractValueObject /** @var string $ordernunmber */ private $ordernunmber; + /** @var string $baseProductFlag */ + private $baseProductFlag; + /** * @return string */ @@ -149,15 +196,45 @@ public function setUnitOfQuantity(string $unitOfQuantity) */ public $mainImageThumbnailUrl; + /** + * @var + */ public $free1; + /** + * @var + */ public $free2; + /** + * @var + */ public $free3; + /** + * @var + */ public $free4; + /** + * @var + */ public $free5; + /** + * @var + */ public $free6; + /** + * @var + */ public $free7; + /** + * @var + */ public $free8; + /** + * @var + */ public $free9; + /** + * @var + */ public $free10; @@ -234,6 +311,9 @@ public function setVariantId($variantId) /** @var ProductPicture[] */ private $productPictures = []; + /** + * @var ArrayCollection + */ protected $variantArticles; /** @@ -269,6 +349,9 @@ public function setSupplierNumber($supplierNumber) } + /** + * Article constructor. + */ public function __construct() { $this->variantArticles = new ArrayCollection(); @@ -534,6 +617,9 @@ public function addProductPicture(ProductPicture $productPicture) $this->productPictures[] = $productPicture; } + /** + * @return bool + */ public function isMainProduct() { return $this->mainArticleId === null; @@ -587,8 +673,6 @@ public function setArticleProperties(array $articleProperties) $this->articleProperties = $articleProperties; } - - /** * @return mixed */ @@ -780,4 +864,50 @@ public function setLastStock(bool $lastStock) { $this->lastStock = $lastStock; } -} \ No newline at end of file + + /** + * @return float + */ + public function getBuyingPrice() + { + return $this->buyingPrice; + } + + /** + * @param float $buyingPrice + */ + public function setBuyingPrice(float $buyingPrice) + { + $this->buyingPrice = $buyingPrice; + } + + /** + * @return string + */ + public function getKeywords() + { + return $this->keywords; + } + + /** + * @param string $keywords + */ + public function setKeywords(string $keywords) + { + $this->keywords = $keywords; + } + + /** + * @return string + */ + public function getBaseProductFlag(){ + return $this->baseProductFlag; + } + + /** + * @param string $baseProductFlag + */ + public function setBaseProductFlag(string $baseProductFlag) { + $this->baseProductFlag = $baseProductFlag; + } +} diff --git a/plugin.xml b/plugin.xml index c0ab314..c2a229a 100755 --- a/plugin.xml +++ b/plugin.xml @@ -9,7 +9,27 @@ https://www.via-connect.de/ ViA-Online GmbH - + + + +
  • New: added universal payment method as fallback
  • +
  • fixed: shipping address missing in order export
  • +
  • fixed: wrong payment descirption in order export
  • + + ]]> +
    + + +
  • New: added universal payment method as fallback
  • +
  • fixed: shipping address missing in order export
  • +
  • fixed: wrong payment descirption in order export
  • + + ]]> +
    +
    + @@ -34,7 +54,6 @@ ]]> - updateAttributes(); + + $this->crateFallbackPayment(); } /** * @param InstallContext $context - * @throws \Doctrine\ORM\OptimisticLockException - * @throws \Doctrine\ORM\Tools\ToolsException - * @throws \Doctrine\ORM\ORMException + * @throws OptimisticLockException + * @throws ToolsException + * @throws ORMException */ public function install(InstallContext $context) { @@ -67,6 +76,7 @@ public function install(InstallContext $context) $this->updateAttributes(); + /** @var EntityManager $em */ $em = $this->container->get('models'); $tool = new SchemaTool($em); $classes = [$em->getClassMetadata(Status::class)]; @@ -74,6 +84,7 @@ public function install(InstallContext $context) $tableNames = array('afterbuy_status'); /** @var AbstractSchemaManager $schemaManager */ + /** @noinspection PhpUndefinedMethodInspection */ $schemaManager = Shopware()->Container()->get('models')->getConnection()->getSchemaManager(); if (!$schemaManager->tablesExist($tableNames)) { $tool->createSchema($classes); @@ -88,6 +99,8 @@ public function install(InstallContext $context) $em->persist($status); $em->flush(); } + $this->crateFallbackPayment(); + } /** @@ -102,10 +115,13 @@ public function fixDefaultValueTypes() { // Retrieve the default config setting from the configs // mainSystem, ExportAllArticles, ordernumberMapping + /** @noinspection SqlResolve */ $sql = ' - SELECT name, value - FROM s_core_config_elements - WHERE name="mainSystem" OR name="ExportAllArticles" OR name="ordernumberMapping" + SELECT el.name, el.value + FROM s_core_config_elements el + LEFT JOIN s_core_config_forms form + ON el.form_id = form.id + WHERE (el.name="mainSystem" OR el.name="ExportAllArticles" OR el.name="ordernumberMapping") AND form.name="viaebShopwareAfterbuy" '; try { @@ -129,8 +145,7 @@ public function fixDefaultValueTypes() ]); } } - } catch (Zend_Db_Adapter_Exception $e) { - } catch (Zend_Db_Statement_Exception $e) { + } catch (Zend_Db_Adapter_Exception | Zend_Db_Statement_Exception $e) { } } @@ -156,12 +171,14 @@ public function deleteAttributes() { } public function deleteSchema() { + /** @var EntityManager $em */ $em = $this->container->get('models'); $tool = new SchemaTool($em); $classes = [$em->getClassMetadata(Status::class)]; $tableNames = array('afterbuy_status'); + /** @noinspection PhpUndefinedMethodInspection */ $schemaManager = Shopware()->Container()->get('models')->getConnection()->getSchemaManager(); /** @var AbstractSchemaManager $schemaManager */ if ($schemaManager->tablesExist($tableNames)) { @@ -170,6 +187,7 @@ public function deleteSchema() { } public function updateAttributes() { + /** @var CrudService $service */ $service = $this->container->get('shopware_attribute.crud_service'); $service->update('s_categories_attributes', 'afterbuy_catalog_id', 'string'); @@ -209,4 +227,26 @@ public function createFreeTextAttributes(CrudService $service) { ]); } } + + public function crateFallbackPayment() + { + /** @var EntityManager $em */ + $em = $this->container->get('models'); + /** @var Repository $shopRepository */ + $shopRepository = $em->getRepository(Payment::class); + + $payment = new Payment(); + $payment_array = [ + 'name' => ShopwareConfigHelper::$AB_UNI_PAYMENT, + 'description' => 'Afterbuy Universal', + 'additionalDescription' => 'Fallback payment for Afterbuy', + ]; + + if (!$shopRepository->findOneBy(['name' => $payment_array['name']])) { + $payment->fromArray($payment_array); + + $em->persist($payment); + $em->flush(); + } + } }