/** * @covers sBasket::sCheckForESD */ public function testsCheckForESD() { // No session, expect false $this->assertFalse($this->module->sCheckForESD()); $this->module->sSYSTEM->sSESSION_ID = uniqid(); $this->session->offsetSet('sessionId', $this->module->sSYSTEM->sSESSION_ID); // Get random non-esd article and add it to the basket $randomNoESDArticle = $this->db->fetchRow('SELECT detail.ordernumber FROM s_articles_details detail LEFT JOIN s_articles article ON article.id = detail.articleID LEFT JOIN s_articles_esd esd ON esd.articledetailsID = detail.id WHERE detail.active = 1 AND esd.id IS NULL ORDER BY RAND() LIMIT 1'); $this->assertGreaterThan(0, $this->module->sAddArticle($randomNoESDArticle['ordernumber'], 1)); $this->assertFalse($this->module->sCheckForESD()); // Get random esd article $randomESDArticle = $this->db->fetchRow('SELECT detail.* FROM s_articles_details detail LEFT JOIN s_articles article ON article.id = detail.articleID LEFT JOIN s_articles_esd esd ON esd.articledetailsID = detail.id WHERE esd.id IS NOT NULL ORDER BY RAND() LIMIT 1'); $this->db->update('s_articles_details', array('active' => 1), array('id = ?' => $randomESDArticle['id'])); $this->db->update('s_articles', array('active' => 1), array('id = ?' => $randomESDArticle['articleID'])); $this->module->sAddArticle($randomESDArticle['ordernumber'], 1); $this->assertTrue($this->module->sCheckForESD()); // Housekeeping $this->db->delete('s_order_basket', array('sessionID = ?' => $this->session->get('sessionId'))); $this->db->update('s_articles_details', array('active' => 0), array('id = ?' => $randomESDArticle['id'])); $this->db->update('s_articles', array('active' => 0), array('id = ?' => $randomESDArticle['articleID'])); }
/** * @param array $category * @return bool|int */ public function import(array $category) { $category = $this->prepareCategoryData($category); // Try to find an existing category by name and parent $model = null; if (isset($category['parent']) && isset($category['name'])) { $model = $this->repository->findOneBy(['parent' => $category['parent'], 'name' => $category['name']]); } if (!$model instanceof Category) { $model = new Category(); } $parentModel = null; if (isset($category['parent'])) { $parentModel = $this->repository->find((int) $category['parent']); if (!$parentModel instanceof Category) { $this->logger->error("Parent category {$category['parent']} not found!"); return false; } } $model->fromArray($category); $model->setParent($parentModel); $this->em->persist($model); $this->em->flush(); // Set category attributes $attributes = $this->prepareCategoryAttributesData($category); unset($category); $categoryId = $model->getId(); if (!empty($attributes)) { $attributeID = $this->db->fetchOne("SELECT id FROM s_categories_attributes WHERE categoryID = ?", [$categoryId]); if ($attributeID === false) { $attributes['categoryID'] = $categoryId; $this->db->insert('s_categories_attributes', $attributes); } else { $this->db->update('s_categories_attributes', $attributes, ['categoryID = ?' => $categoryId]); } } return $categoryId; }
/** * Helper function for sAdmin::sGetUserData() * Gets user shipping data (address, payment) * * @param $userId * @param $userData * @param $countryQuery * @return mixed */ private function getUserShippingData($userId, $userData, $countryQuery) { $shipping = $this->db->fetchRow("SELECT * FROM s_user_shippingaddress WHERE userID = ?", array($userId)); $shipping = $shipping ?: array(); $attributes = $this->getUserShippingAddressAttributes($userId); $userData["shippingaddress"] = array_merge($attributes, $shipping); // If shipping address is not available, billing address is coeval the shipping address $countryShipping = $this->config->get('sCOUNTRYSHIPPING'); if (!isset($userData["shippingaddress"]["firstname"])) { $userData["shippingaddress"] = $userData["billingaddress"]; $userData["shippingaddress"]["eqalBilling"] = true; } else { if ($userData["shippingaddress"]["countryID"] != $userData["billingaddress"]["countryID"] && empty($countryShipping)) { $this->db->update('s_user_shippingaddress', array('countryID' => $userData["billingaddress"]["countryID"]), array('id = ?' => $userData["shippingaddress"]["id"])); $userData["shippingaddress"]["countryID"] = $userData["billingaddress"]["countryID"]; } } if (empty($userData["shippingaddress"]["countryID"])) { $targetCountryId = $userData["billingaddress"]["countryID"]; } else { $targetCountryId = $userData["shippingaddress"]["countryID"]; } $userData["additional"]["countryShipping"] = $this->db->fetchRow($countryQuery, array($targetCountryId)); $userData["additional"]["countryShipping"] = $userData["additional"]["countryShipping"] ?: array(); $userData["additional"]["countryShipping"] = $this->sGetCountryTranslation($userData["additional"]["countryShipping"]); $this->session->offsetSet('sCountry', $userData["additional"]["countryShipping"]["id"]); // State selection $userData["additional"]["stateShipping"] = $this->db->fetchRow("SELECT * FROM s_core_countries_states WHERE id = ?", array($userData["shippingaddress"]["stateID"])); $userData["additional"]["stateShipping"] = $userData["additional"]["stateShipping"] ?: array(); $userData["additional"]["stateShipping"] = $this->sGetCountryStateTranslation($userData["additional"]["stateShipping"]); // Add stateId to session $this->session->offsetSet('sState', $userData["additional"]["stateShipping"]["id"]); // Add areaId to session $this->session->offsetSet('sArea', $userData["additional"]["countryShipping"]["areaID"]); $userData["additional"]["payment"] = $this->sGetPaymentMeanById($userData["additional"]["user"]["paymentID"], $userData); return $userData; }
/** * executes the current product export * * @param resource $handleResource used as a file or the stdout to fetch the smarty output */ public function executeExport($handleResource) { fwrite($handleResource, $this->sSmarty->fetch('string:' . $this->sSettings['header'], $this->sFeedID)); $context = $this->contextService->getShopContext(); $sql = $this->sCreateSql(); $result = $this->db->query($sql); if ($result === false) { return; } // Update db with the latest values $count = (int) $result->rowCount(); $this->db->update('s_export', array('last_export' => new Zend_Date(), 'cache_refreshed' => new Zend_Date(), 'count_articles' => $count), array('id = ?' => $this->sFeedID)); // fetches all required data to smarty $rows = array(); for ($rowIndex = 1; $row = $result->fetch(); $rowIndex++) { if (!empty($row['group_ordernumber_2'])) { $row['group_ordernumber'] = $this->_decode_line($row['group_ordernumber_2']); $row['group_pricenet'] = explode(';', $row['group_pricenet_2']); $row['group_price'] = explode(';', $row['group_price_2']); $row['group_instock'] = explode(';', $row['group_instock_2']); $row['group_active'] = explode(';', $row['group_active_2']); unset($row['group_ordernumber_2'], $row['group_pricenet_2']); unset($row['group_price_2'], $row['group_instock_2'], $row['group_active_2']); for ($i = 1; $i <= 10; $i++) { if (!empty($row['group_group' . $i])) { $row['group_group' . $i] = $this->_decode_line($row['group_group' . $i]); } else { unset($row['group_group' . $i]); } if (!empty($row['group_option' . $i])) { $row['group_option' . $i] = $this->_decode_line($row['group_option' . $i]); } else { unset($row['group_option' . $i]); } } unset($row['group_additionaltext']); } elseif (!empty($row['group_ordernumber'])) { $row['group_ordernumber'] = $this->_decode_line($row['group_ordernumber']); $row['group_additionaltext'] = $this->_decode_line($row['group_additionaltext']); $row['group_pricenet'] = explode(';', $row['group_pricenet']); $row['group_price'] = explode(';', $row['group_price']); $row['group_instock'] = explode(';', $row['group_instock']); $row['group_active'] = explode(';', $row['group_active']); } if (!empty($row['article_translation_fallback'])) { $translation = $this->sMapTranslation('article', $row['article_translation_fallback']); if ($row['main_detail_id'] != $row['articledetailsID']) { unset($translation['additionaltext']); } $row = array_merge($row, $translation); } if (!empty($row['article_translation'])) { $translation = $this->sMapTranslation('article', $row['article_translation']); if ($row['main_detail_id'] != $row['articledetailsID']) { unset($translation['additionaltext']); } $row = array_merge($row, $translation); } if (!empty($row['detail_translation_fallback'])) { $translation = $this->sMapTranslation('detail', $row['detail_translation_fallback']); $row = array_merge($row, $translation); } if (!empty($row['detail_translation'])) { $translation = $this->sMapTranslation('detail', $row['detail_translation']); $row = array_merge($row, $translation); } $row['name'] = htmlspecialchars_decode($row['name']); $row['supplier'] = htmlspecialchars_decode($row['supplier']); //cast it to float to prevent the division by zero warning $row['purchaseunit'] = floatval($row['purchaseunit']); $row['referenceunit'] = floatval($row['referenceunit']); if (!empty($row['purchaseunit']) && !empty($row['referenceunit'])) { $row['referenceprice'] = Shopware()->Modules()->Articles()->calculateReferencePrice($row['price'], $row['purchaseunit'], $row['referenceunit']); } if ($row['configurator'] > 0) { if (empty($this->sSettings["variant_export"]) || $this->sSettings["variant_export"] == 1) { $row['group_additionaltext'] = array(); if (!empty($row['group_ordernumber'])) { foreach ($row['group_ordernumber'] as $orderNumber) { $product = new StoreFrontBundle\Struct\ListProduct((int) $row['articleID'], (int) $row["articledetailsID"], $orderNumber); $product->setAdditional($row['additionaltext']); $product = $this->additionalTextService->buildAdditionalText($product, $context); if (array_key_exists($orderNumber, $row['group_additionaltext'])) { $row['group_additionaltext'][$orderNumber] = $product->getAdditional(); } if ($orderNumber == $row['ordernumber']) { $row['additionaltext'] = $product->getAdditional(); } } } } $product = new StoreFrontBundle\Struct\ListProduct((int) $row['articleID'], (int) $row["articledetailsID"], $row['ordernumber']); $product->setAdditional($row['additionaltext']); $product = $this->additionalTextService->buildAdditionalText($product, $context); $row['additionaltext'] = $product->getAdditional(); } $rows[] = $row; if ($rowIndex == $count || count($rows) >= 50) { @set_time_limit(30); $this->sSmarty->assign('sArticles', $rows); $rows = array(); $template = 'string:{foreach $sArticles as $sArticle}' . $this->sSettings['body'] . '{/foreach}'; fwrite($handleResource, $this->sSmarty->fetch($template, $this->sFeedID)); } } fwrite($handleResource, $this->sSmarty->fetch('string:' . $this->sSettings['footer'], $this->sFeedID)); fclose($handleResource); }
/** * Insert/Update data into db * * @param array $records * @throws \Enlight_Event_Exception * @throws \Exception * @throws \Zend_Db_Adapter_Exception */ public function write($records) { if (empty($records['default'])) { $message = SnippetsHelper::getNamespace()->get('adapters/articlesImages/no_records', 'No new article image records were found.'); throw new \Exception($message); } $records = $this->eventManager->filter('Shopware_Components_SwagImportExport_DbAdapters_ArticlesImagesDbAdapter_Write', $records, ['subject' => $this]); foreach ($records['default'] as $record) { try { $record = $this->validator->filterEmptyString($record); $this->validator->checkRequiredFields($record); /** @var \Shopware\Models\Article\Detail $articleDetailModel */ $articleDetailModel = $this->manager->getRepository(Detail::class)->findOneBy(['number' => $record['ordernumber']]); if (!$articleDetailModel) { $message = SnippetsHelper::getNamespace()->get('adapters/articlesImages/article_not_found', 'Article with number %s does not exists'); throw new AdapterException(sprintf($message, $record['ordernumber'])); } $record = $this->dataManager->setDefaultFields($record, $articleDetailModel->getArticle()->getId()); $this->validator->validate($record, ArticleImageValidator::$mapper); $relations = []; if (isset($record['relations'])) { $importedRelations = explode("&", $record['relations']); foreach ($importedRelations as $key => $relation) { if ($relation === "") { continue; } $variantConfig = explode('|', preg_replace('/{|}/', '', $relation)); foreach ($variantConfig as $config) { list($group, $option) = explode(":", $config); //Get configurator group $cGroupModel = $this->manager->getRepository(Group::class)->findOneBy(['name' => $group]); if ($cGroupModel === null) { continue; } //Get configurator option $cOptionModel = $this->manager->getRepository(Option::class)->findOneBy(['name' => $option, 'groupId' => $cGroupModel->getId()]); if ($cOptionModel === null) { continue; } $relations[$key][] = ["group" => $cGroupModel, "option" => $cOptionModel]; } } } /** @var \Shopware\Models\Article\Article $article */ $article = $articleDetailModel->getArticle(); $name = pathinfo($record['image'], PATHINFO_FILENAME); $media = false; if ($this->imageImportMode === 1) { $mediaRepository = $this->manager->getRepository(Media::class); $media = $mediaRepository->findOneBy(['name' => $name]); } //create new media if ($this->imageImportMode === 2 || empty($media)) { $path = $this->load($record['image'], $name); $file = new File($path); $media = new Media(); $media->setAlbumId(-1); $media->setAlbum($this->manager->getRepository(Album::class)->find(-1)); $media->setFile($file); $media->setName(pathinfo($record['image'], PATHINFO_FILENAME)); $media->setDescription(''); $media->setCreated(new \DateTime()); $media->setUserId(0); $this->manager->persist($media); $this->manager->flush(); //thumbnail flag //TODO: validate thumbnail $thumbnail = (bool) $record['thumbnail']; //generate thumbnails if ($media->getType() == Media::TYPE_IMAGE && $thumbnail) { $this->thumbnailManager->createMediaThumbnail($media, [], true); } } $image = new Image(); $image->setArticle($article); $image->setPosition($record['position']); $image->setPath($media->getName()); $image->setExtension($media->getExtension()); $image->setMedia($media); $image->setMain($record['main']); $image->setDescription($record['description']); $this->manager->persist($image); $this->manager->flush(); if ($relations && !empty($relations)) { $this->setImageMappings($relations, $image->getId()); } // Prevent multiple images from being a preview if ((int) $record['main'] === 1) { $this->db->update('s_articles_img', ['main' => 2], ['articleID = ?' => $article->getId(), 'id <> ?' => $image->getId()]); } } catch (AdapterException $e) { $message = $e->getMessage(); $this->saveMessage($message); } } }
/** * @param array $article */ private function setArticlePrices(array $article) { $this->db->update('s_articles_prices', ['articleID' => $article['articleID']], ['articledetailsID = ?' => $article['articledetailsID']]); }