/** * Upload table rate file and import data from it * * @param \Magento\Framework\Object $object * @throws \Magento\Framework\Exception\LocalizedException * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate * @todo: this method should be refactored as soon as updated design will be provided * @see https://wiki.corp.x.com/display/MCOMS/Magento+Filesystem+Decisions * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function uploadAndImport(\Magento\Framework\DataObject $object) { if (empty($_FILES['groups']['tmp_name']['matrixrate']['fields']['import']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['matrixrate']['fields']['import']['value']; $website = $this->_storeManager->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $this->_importUniqueHash = []; $this->_importErrors = []; $this->_importedRows = 0; $uploadDirectory = $this->_readFactory->create(ini_get('upload_tmp_dir') ?: sys_get_temp_dir()); $path = $uploadDirectory->getRelativePath($csvFile); $stream = $uploadDirectory->openFile($path); // check and skip headers $headers = $stream->readCsv(); if ($headers === false || count($headers) < 5) { $stream->close(); throw new \Magento\Framework\Exception\LocalizedException(__('Please correct Matrix Rates File Format.')); } if ($object->getData('groups/matrixrate/fields/condition_name/inherit') == '1') { $conditionName = (string) $this->_coreConfig->getValue('carriers/matrixrate/condition_name', 'default'); } else { $conditionName = $object->getData('groups/matrixrate/fields/condition_name/value'); } $this->_importConditionName = $conditionName; $adapter = $this->getConnection(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = []; $this->_loadDirectoryCountries(); $this->_loadDirectoryRegions(); // delete old data by website and condition name $condition = ['website_id = ?' => $this->_importWebsiteId, 'condition_name = ?' => $this->_importConditionName]; $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $stream->readCsv())) { $rowNumber++; if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber); if ($row !== false) { $importData[] = $row; } if (count($importData) == 5000) { $this->_saveImportData($importData); $importData = []; } } $this->_saveImportData($importData); $stream->close(); } catch (\Magento\Framework\Exception\LocalizedException $e) { $adapter->rollback(); $stream->close(); throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); } catch (\Exception $e) { $adapter->rollback(); $stream->close(); $this->_logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while importing matrix rates.')); } $adapter->commit(); if ($this->_importErrors) { $error = __('We couldn\'t import this file because of these errors: %1', implode(" \n", $this->_importErrors)); throw new \Magento\Framework\Exception\LocalizedException($error); } return $this; }
public function uploadAndImport(\Magento\Framework\DataObject $object) { $csvFile = $_FILES["groups"]["tmp_name"]["matrixrate"]["fields"]["import"]["value"]; if (!empty($csvFile)) { $csv = trim(file_get_contents($csvFile)); $table = $this->getMainTable(); $websiteModel = $this->_storeManager->getWebsite($object->getScopeId()); $websiteId = (int) $websiteModel->getId(); $this->_importWebsiteId = (int) $websiteModel->getId(); $this->_importUniqueHash = []; $this->_importErrors = []; $this->_importedRows = 0; /* getting condition name from post instead of the following commented logic */ if ($object->getData('groups/matrixrate/fields/condition_name/inherit') == '1') { $conditionName = (string) $this->_coreConfig->getValue('carriers/matrixrate/condition_name', 'default'); } else { $conditionName = $object->getData('groups/matrixrate/fields/condition_name/value'); } $conditionFullName = $this->_getConditionFullName($conditionName); if (!empty($csv)) { $exceptions = array(); $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < 7) { $exceptions[0] = __('Invalid Matrix Rates File Format'); } $countryCodes = array(); $regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) > 0 && count($csvLine) < 7) { $exceptions[0] = __('Invalid Matrix Rates File Format'); } else { $countryCodes[] = $csvLine[0]; $regionCodes[] = $csvLine[1]; } } if (empty($exceptions)) { $data = array(); $countryCodesToIds = array(); $regionCodesToIds = array(); $countryCodesIso2 = array(); /** @var $collection \Magento\Directory\Model\ResourceModel\Country\Collection */ $collection = $this->_countryCollectionFactory->create(); $collection->addCountryCodeFilter($countryCodes); foreach ($collection->getData() as $row) { $countryCodesToIds[$row['iso2_code']] = $row['country_id']; $countryCodesToIds[$row['iso3_code']] = $row['country_id']; $countryCodesIso2[] = $row['iso2_code']; } /** @var $collection \Magento\Directory\Model\ResourceModel\Region\Collection */ $collection = $this->_regionCollectionFactory->create()->addRegionCodeFilter($regionCodes)->addCountryFilter($countryCodesIso2); foreach ($collection->getData() as $row) { $regionCodesToIds[$row['country_id']][$row['code']] = (int) $row['region_id']; } foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (empty($countryCodesToIds) || !array_key_exists($csvLine[0], $countryCodesToIds)) { $countryId = '0'; if ($csvLine[0] != '*' && $csvLine[0] != '') { $exceptions[] = __('Invalid Country "%s" in the Row #%s', $csvLine[0], $k + 1); } } else { $countryId = $countryCodesToIds[$csvLine[0]]; } if (!isset($countryCodesToIds[$csvLine[0]]) || !isset($regionCodesToIds[$countryCodesToIds[$csvLine[0]]]) || !array_key_exists($csvLine[1], $regionCodesToIds[$countryCodesToIds[$csvLine[0]]])) { $regionId = '0'; if ($csvLine[1] != '*' && $csvLine[1] != '') { $exceptions[] = __('Invalid Region/State "%s" in the Row #%s', $csvLine[1], $k + 1); } } else { $regionId = $regionCodesToIds[$countryCodesToIds[$csvLine[0]]][$csvLine[1]]; } if (count($csvLine) == 9) { // we are searching for postcodes in ranges & including cities if ($csvLine[2] == '*' || $csvLine[2] == '') { $city = ''; } else { $city = $csvLine[2]; } if ($csvLine[3] == '*' || $csvLine[3] == '') { $zip = ''; } else { $zip = $csvLine[3]; } if ($csvLine[4] == '*' || $csvLine[4] == '') { $zip_to = ''; } else { $zip_to = $csvLine[4]; } if (!$this->_isPositiveDecimalNumber($csvLine[5]) || $csvLine[5] == '*' || $csvLine[5] == '') { $exceptions[] = __('Invalid %s From "%s" in the Row #%s', $conditionFullName, $csvLine[5], $k + 1); } else { $csvLine[5] = (double) $csvLine[5]; } if (!$this->_isPositiveDecimalNumber($csvLine[6])) { $exceptions[] = __('Invalid %s To "%s" in the Row #%s', $conditionFullName, $csvLine[6], $k + 1); } else { $csvLine[6] = (double) $csvLine[6]; } $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_city' => $city, 'dest_zip' => $zip, 'dest_zip_to' => $zip_to, 'condition_name' => $conditionName, 'condition_from_value' => $csvLine[5], 'condition_to_value' => $csvLine[6], 'price' => $csvLine[7], 'cost' => 0, 'delivery_type' => $csvLine[8]); } else { if ($csvLine[2] == '*' || $csvLine[2] == '') { $zip = ''; } else { $zip = $csvLine[2] . "%"; } $city = ''; $zip_to = ''; if (!$this->_isPositiveDecimalNumber($csvLine[3]) || $csvLine[3] == '*' || $csvLine[3] == '') { $exceptions[] = __('Invalid %s From "%s" in the Row #%s', $conditionFullName, $csvLine[3], $k + 1); } else { $csvLine[3] = (double) $csvLine[3]; } if (!$this->_isPositiveDecimalNumber($csvLine[4])) { $exceptions[] = __('Invalid %s To "%s" in the Row #%s', $conditionFullName, $csvLine[4], $k + 1); } else { $csvLine[4] = (double) $csvLine[4]; } $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_city' => $city, 'dest_zip' => $zip, 'dest_zip_to' => $zip_to, 'condition_name' => $conditionName, 'condition_from_value' => $csvLine[3], 'condition_to_value' => $csvLine[4], 'price' => $csvLine[5], 'cost' => 0, 'delivery_type' => $csvLine[6]); } $dataDetails[] = array('country' => $csvLine[0], 'region' => $csvLine[1]); } } if (empty($exceptions)) { $connection = $this->getConnection(); $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName)); $connection->delete($table, $condition); //foreach ($data as $k => $dataLine) { try { foreach ($data as $v) { $data2[] = array_values($v); } $this->_saveImportData($data2); } catch (\Exception $e) { //$connection->rollback(); $this->_logger->critical($e); $exceptions[] = __($e->__toString()); //__('Duplicate Row #%s (Country "%s", Region/State "%s", City "%s", Zip From "%s", Zip To "%s", Delivery Type "%s", Value From "%s" and Value To "%s")', ($k + 1), $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_city'], $dataLine['dest_zip'], $dataLine['dest_zip_to'], $dataLine['delivery_type'], $dataLine['condition_from_value'], $dataLine['condition_to_value']); } //} } if (!empty($exceptions)) { throw new \Magento\Framework\Exception\LocalizedException(__(implode("\n", $exceptions))); } } } }
/** * Upload table rate file and import data from it * * @param \Magento\Framework\DataObject $object * @throws \Magento\Framework\Exception\LocalizedException * @return \Magento\OfflineShipping\Model\ResourceModel\Carrier\Tablerate * @todo: this method should be refactored as soon as updated design will be provided * @see https://wiki.corp.x.com/display/MCOMS/Magento+Filesystem+Decisions * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function uploadAndImport(\Magento\Framework\DataObject $object) { /** * @var \Magento\Framework\App\Config\Value $object */ if (empty($_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'])) { return $this; } $filePath = $_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value']; $websiteId = $this->storeManager->getWebsite($object->getScopeId())->getId(); $conditionName = $this->getConditionName($object); $file = $this->getCsvFile($filePath); try { // delete old data by website and condition name $condition = ['website_id = ?' => $websiteId, 'condition_name = ?' => $conditionName]; $this->deleteByCondition($condition); $columns = $this->import->getColumns(); $conditionFullName = $this->_getConditionFullName($conditionName); foreach ($this->import->getData($file, $websiteId, $conditionName, $conditionFullName) as $bunch) { $this->importData($columns, $bunch); } } catch (\Exception $e) { $this->logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while importing table rates.')); } finally { $file->close(); } if ($this->import->hasErrors()) { $error = __('We couldn\'t import this file because of these errors: %1', implode(" \n", $this->import->getErrors())); throw new \Magento\Framework\Exception\LocalizedException($error); } }