public function render(Varien_Object $row) { $actions = array(); $curWebsite = $this->getRequest()->getParam('website'); $curStore = $this->getRequest()->getParam('store'); $aParams = array(); if ($curWebsite) { $aParams['website'] = $curWebsite; } if ($curStore) { $aParams['store'] = $curStore; } if (!$aParams) { list($aParams['scope'], $aParams['scopeid']) = Mage::getModel('aitemails/aitemails')->getCurrentScope(); } $aParams['fromaitemails'] = 1; if ($row->getCustomTemplate()) { $aParams['id'] = $row->getCustomTemplateId(); $actions[] = array('url' => $this->getUrl('adminhtml/system_email_template/edit', $aParams), 'caption' => $this->__('Edit Custom Template')); } else { $aParams['templatecode'] = $row->getCode(); $aParams['localecode'] = Mage::registry('aitemails_email_template_scope_locale'); $aParams['scope'] = $row->getScope(); $aParams['scopeid'] = $row->getScopeId(); $actions[] = array('url' => $this->getUrl('adminhtml/system_email_template/new', $aParams), 'caption' => $this->__('Create Custom Template')); } $this->getColumn()->setActions($actions); return parent::render($row); }
public function uploadAndImport(Varien_Object $object) { $csvFile = $_FILES["groups"]["tmp_name"]["tablerate"]["fields"]["import"]["value"]; if (!empty($csvFile)) { $csv = trim(file_get_contents($csvFile)); $table = Mage::getSingleton('core/resource')->getTableName('shipping/tablerate'); $websiteId = $object->getScopeId(); $websiteModel = Mage::app()->getWebsite($websiteId); /* getting condition name from post instead of the following commented logic */ if (isset($_POST['groups']['tablerate']['fields']['condition_name']['inherit'])) { $conditionName = (string) Mage::getConfig()->getNode('default/carriers/tablerate/condition_name'); } else { $conditionName = $_POST['groups']['tablerate']['fields']['condition_name']['value']; } // $conditionName = $object->getValue(); // if ($conditionName{0} == '_') { // $conditionName = Mage::helper('core/string')->substr($conditionName, 1, strpos($conditionName, '/')-1); // } else { // $conditionName = $websiteModel->getConfig('carriers/tablerate/condition_name'); // } $conditionFullName = Mage::getModel('shipping/carrier_tablerate')->getCode('condition_name_short', $conditionName); if (!empty($csv)) { $exceptions = array(); $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < 5) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Table Rates File Format'); } $countryCodes = array(); $regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) > 0 && count($csvLine) < 5) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Table Rates File Format'); } else { $countryCodes[] = $csvLine[0]; $regionCodes[] = $csvLine[1]; } } if (empty($exceptions)) { $data = array(); $countryCodesToIds = array(); $regionCodesToIds = array(); $countryCodesIso2 = array(); $countryCollection = Mage::getResourceModel('directory/country_collection')->addCountryCodeFilter($countryCodes)->load(); foreach ($countryCollection->getItems() as $country) { $countryCodesToIds[$country->getData('iso3_code')] = $country->getData('country_id'); $countryCodesToIds[$country->getData('iso2_code')] = $country->getData('country_id'); $countryCodesIso2[] = $country->getData('iso2_code'); } $regionCollection = Mage::getResourceModel('directory/region_collection')->addRegionCodeFilter($regionCodes)->addCountryFilter($countryCodesIso2)->load(); foreach ($regionCollection->getItems() as $region) { $regionCodesToIds[$countryCodesToIds[$region->getData('country_id')]][$region->getData('code')] = $region->getData('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[] = Mage::helper('shipping')->__('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[] = Mage::helper('shipping')->__('Invalid Region/State "%s" in the Row #%s', $csvLine[1], $k + 1); } } else { $regionId = $regionCodesToIds[$countryCodesToIds[$csvLine[0]]][$csvLine[1]]; } if ($csvLine[2] == '*' || $csvLine[2] == '') { $zip = ''; } else { $zip = $csvLine[2]; } if (!$this->_isPositiveDecimalNumber($csvLine[3]) || $csvLine[3] == '*' || $csvLine[3] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid %s "%s" in the Row #%s', $conditionFullName, $csvLine[3], $k + 1); } else { $csvLine[3] = (double) $csvLine[3]; } if (!$this->_isPositiveDecimalNumber($csvLine[4])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Shipping Price "%s" in the Row #%s', $csvLine[4], $k + 1); } else { $csvLine[4] = (double) $csvLine[4]; } $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_zip' => $zip, 'condition_name' => $conditionName, 'condition_value' => $csvLine[3], 'price' => $csvLine[4]); $dataDetails[] = array('country' => $csvLine[0], 'region' => $csvLine[1]); } } if (empty($exceptions)) { $connection = $this->_getWriteAdapter(); $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName)); $connection->delete($table, $condition); foreach ($data as $k => $dataLine) { try { $connection->insert($table, $dataLine); } catch (Exception $e) { $exceptions[] = Mage::helper('shipping')->__('Duplicate Row #%s (Country "%s", Region/State "%s", Zip "%s" and Value "%s")', $k + 1, $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_zip'], $dataLine['condition_value']); } } } if (!empty($exceptions)) { throw new Exception("\n" . implode("\n", $exceptions)); } } } }
public function uploadAndImport(Varien_Object $object) { $csvFile = $_FILES["groups"]["tmp_name"]["eparcel"]["fields"]["import"]["value"]; if (!empty($csvFile)) { $csv = trim(file_get_contents($csvFile)); $table = Mage::getSingleton('core/resource')->getTableName('australia/eparcel'); $websiteId = $object->getScopeId(); if (isset($_POST['groups']['eparcel']['fields']['condition_name']['inherit'])) { $conditionName = (string) Mage::getConfig()->getNode('default/carriers/eparcel/condition_name'); } else { $conditionName = $_POST['groups']['eparcel']['fields']['condition_name']['value']; } $conditionFullName = Mage::getModel('australia/shipping_carrier_eparcel')->getCode('condition_name_short', $conditionName); if (!empty($csv)) { $exceptions = array(); $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < self::MIN_CSV_COLUMN_COUNT) { $exceptions[0] = Mage::helper('shipping')->__('Less than ' . self::MIN_CSV_COLUMN_COUNT . ' columns in the CSV header.'); } $countryCodes = array(); $regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); $count = count($csvLine); if ($count > 0 && $count < self::MIN_CSV_COLUMN_COUNT) { $exceptions[0] = Mage::helper('shipping')->__('Less than ' . self::MIN_CSV_COLUMN_COUNT . ' columns in row ' . ($k + 1) . '.'); } else { $countryCodes[] = $csvLine[0]; $regionCodes[] = $csvLine[1]; } } if (empty($exceptions)) { $data = array(); $countryCodesToIds = array(); $regionCodesToIds = array(); $countryCodesIso2 = array(); $countryCollection = Mage::getResourceModel('directory/country_collection')->addCountryCodeFilter($countryCodes)->load(); foreach ($countryCollection->getItems() as $country) { $countryCodesToIds[$country->getData('iso3_code')] = $country->getData('country_id'); $countryCodesToIds[$country->getData('iso2_code')] = $country->getData('country_id'); $countryCodesIso2[] = $country->getData('iso2_code'); } $regionCollection = Mage::getResourceModel('directory/region_collection')->addRegionCodeFilter($regionCodes)->addCountryFilter($countryCodesIso2)->load(); foreach ($regionCollection->getItems() as $region) { $regionCodesToIds[$region->getData('code')] = $region->getData('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[] = Mage::helper('shipping')->__('Invalid country "%s" on row #%s', $csvLine[0], $k + 1); } } else { $countryId = $countryCodesToIds[$csvLine[0]]; } if (empty($regionCodesToIds) || !array_key_exists($csvLine[1], $regionCodesToIds)) { $regionId = '0'; if ($csvLine[1] != '*' && $csvLine[1] != '') { $exceptions[] = Mage::helper('shipping')->__('Invalid region/state "%s" on row #%s', $csvLine[1], $k + 1); } } else { $regionId = $regionCodesToIds[$csvLine[1]]; } if ($csvLine[2] == '*' || $csvLine[2] == '') { $zip = ''; } else { $zip = $csvLine[2]; } if (!$this->_isPositiveDecimalNumber($csvLine[3]) || $csvLine[3] == '*' || $csvLine[3] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid %s "%s" on row #%s', $conditionFullName, $csvLine[3], $k + 1); } else { $csvLine[3] = (double) $csvLine[3]; } if (!$this->_isPositiveDecimalNumber($csvLine[4]) || $csvLine[4] == '*' || $csvLine[4] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid %s "%s" on row #%s', $conditionFullName, $csvLine[4], $k + 1); } else { $csvLine[4] = (double) $csvLine[4]; } if (!$this->_isPositiveDecimalNumber($csvLine[5])) { $exceptions[] = Mage::helper('shipping')->__('Invalid shipping price "%s" on row #%s', $csvLine[5], $k + 1); } else { $csvLine[5] = (double) $csvLine[5]; } if (!$this->_isPositiveDecimalNumber($csvLine[6])) { $exceptions[] = Mage::helper('shipping')->__('Invalid shipping price per kg "%s" on row #%s', $csvLine[6], $k + 1); } else { $csvLine[6] = (double) $csvLine[6]; } /** @var Fontis_Australia_Helper_Eparcel $helper */ $helper = Mage::helper('australia/eparcel'); if (isset($csvLine[8]) && $csvLine[8] != '' && !$helper->isValidChargeCode($csvLine[8])) { $exceptions[] = Mage::helper('shipping')->__('Invalid charge code "%s" on row #%s', $csvLine[8], $k + 1); } else { $csvLine[8] = isset($csvLine[8]) ? (string) $csvLine[8] : null; } if (isset($csvLine[9]) && $csvLine[9] != '' && !$helper->isValidChargeCode($csvLine[9])) { $exceptions[] = Mage::helper('shipping')->__('Invalid charge code "%s" on row #%s', $csvLine[9], $k + 1); } else { $csvLine[9] = isset($csvLine[9]) ? (string) $csvLine[9] : null; } // If Multi Warehouse Ext is not used the value is 0 (as for no warehouse) otherwise is positive integer from table "warehouse" if (isset($csvLine[10]) && intval($csvLine[10]) < 0) { $exceptions[] = Mage::helper('shipping')->__('Invalid warehouse ID "%s" on row #%s', $csvLine[10], $k + 1); } else { $csvLine[10] = isset($csvLine[10]) ? (int) $csvLine[10] : 0; } $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_zip' => $zip, 'condition_name' => $conditionName, 'condition_from_value' => $csvLine[3], 'condition_to_value' => $csvLine[4], 'price' => $csvLine[5], 'price_per_kg' => $csvLine[6], 'delivery_type' => $csvLine[7], 'charge_code_individual' => $csvLine[8], 'charge_code_business' => $csvLine[9], 'stock_id' => $csvLine[10]); $dataDetails[] = array('country' => $csvLine[0], 'region' => $csvLine[1]); } } if (empty($exceptions)) { $connection = $this->_getWriteAdapter(); $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName)); $connection->delete($table, $condition); foreach ($data as $k => $dataLine) { try { // convert comma-seperated postcode/postcode range // string into an array $postcodes = array(); foreach (explode(',', $dataLine['dest_zip']) as $postcodeEntry) { $postcodeEntry = explode("-", trim($postcodeEntry)); if (count($postcodeEntry) == 1) { // if the postcode entry is length 1, it's // just a single postcode $postcodes[] = $postcodeEntry[0]; } else { // otherwise it's a range, so convert that // to a sequence of numbers $pcode1 = (int) $postcodeEntry[0]; $pcode2 = (int) $postcodeEntry[1]; $postcodes = array_merge($postcodes, range(min($pcode1, $pcode2), max($pcode1, $pcode2))); } } foreach ($postcodes as $postcode) { $dataLine['dest_zip'] = str_pad($postcode, 4, "0", STR_PAD_LEFT); $connection->insert($table, $dataLine); } } catch (Exception $e) { Mage::log($e->getMessage()); $exceptions[] = $e->getMessage(); } } } if (!empty($exceptions)) { throw new Exception("\n" . implode("\n", $exceptions)); } } } }
/** * Upload table rate file and import data from it * * @param Varien_Object $object * @throws Mage_Core_Exception * @return Mage_Shipping_Model_Mysql4_Carrier_Tablerate */ public function uploadAndImport(Varien_Object $object) { if (empty($_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['tablerate']['fields']['import']['value']; $website = Mage::app()->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $this->_importUniqueHash = array(); $this->_importErrors = array(); $this->_importedRows = 0; $io = new Varien_Io_File(); $info = pathinfo($csvFile); $io->open(array('path' => $info['dirname'])); $io->streamOpen($info['basename'], 'r'); // check and skip headers $headers = $io->streamReadCsv(); if ($headers === false || count($headers) < 5) { $io->streamClose(); Mage::throwException(Mage::helper('shipping')->__('Invalid Table Rates File Format')); } if ($object->getData('groups/tablerate/fields/condition_name/inherit') == '1') { $conditionName = (string) Mage::getConfig()->getNode('default/carriers/tablerate/condition_name'); } else { $conditionName = $object->getData('groups/tablerate/fields/condition_name/value'); } $this->_importConditionName = $conditionName; $adapter = $this->_getWriteAdapter(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = array(); $this->_loadDirectoryCountries(); $this->_loadDirectoryRegions(); // delete old data by website and condition name $condition = array('website_id = ?' => $this->_importWebsiteId, 'condition_name = ?' => $this->_importConditionName); $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $io->streamReadCsv())) { $rowNumber++; if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber); if ($row !== false) { $importData[] = $row; } if (count($importData) == 5000) { $this->_saveImportData($importData); $importData = array(); } } $this->_saveImportData($importData); $io->streamClose(); } catch (Mage_Core_Exception $e) { $adapter->rollback(); $io->streamClose(); Mage::throwException($e->getMessage()); } catch (Exception $e) { $adapter->rollback(); $io->streamClose(); Mage::logException($e); Mage::throwException(Mage::helper('shipping')->__('An error occurred while import table rates.')); } $adapter->commit(); if ($this->_importErrors) { $error = Mage::helper('shipping')->__('%1$d records have been imported. See the following list of errors for each record that has not been imported: %2$s', $this->_importedRows, implode(" \n", $this->_importErrors)); Mage::throwException($error); } return $this; }
/** * Upload table rate file and import data from it * * @param Varien_Object $object * * @throws Mage_Core_Exception * @return Mage_Shipping_Model_Mysql4_Carrier_Tablerate */ public function uploadAndImport(Varien_Object $object, $csvFile = null) { $this->_log(__METHOD__); if (!$csvFile && !empty($_FILES['groups']['tmp_name']['zitec_dpd']['fields']['import']['value'])) { $csvFile = $_FILES['groups']['tmp_name']['zitec_dpd']['fields']['import']['value']; } if (!$csvFile) { return $this; } $website = Mage::app()->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $this->_importUniqueHash = array(); $this->_importErrors = array(); $this->_importedRows = 0; $io = new Varien_Io_File(); $info = pathinfo($csvFile); $io->open(array('path' => $info['dirname'])); $io->streamOpen($info['basename'], 'r'); // check and skip headers $headers = $io->streamReadCsv(); if ($headers === false || count($headers) < self::CSV_COL_COUNT) { $io->streamClose(); Mage::throwException($this->_getHelper()->__('Invalid Table Rates File Format')); } $adapter = $this->_getWriteAdapter(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = array(); $this->_loadDirectoryCountries(); $this->_loadDirectoryRegions(); // delete old data by website and condition name $condition = array('website_id = ?' => $this->_importWebsiteId); $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $io->streamReadCsv())) { $rowNumber++; if (is_array($csvLine)) { foreach ($csvLine as &$cell) { $cell = filter_var($cell, FILTER_SANITIZE_STRING); } } if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber); if ($row !== false) { $importData[] = $row; } if (count($importData) == 5000) { $this->_saveImportData($importData); $importData = array(); } } $this->_saveImportData($importData); $io->streamClose(); } catch (Mage_Core_Exception $e) { $adapter->rollback(); $io->streamClose(); Mage::throwException($e->getMessage()); } catch (Exception $e) { $adapter->rollback(); $io->streamClose(); $this->_log($e->getMessage()); Mage::throwException($this->_getHelper()->__('An error occurred while import table rates.')); } $adapter->commit(); if ($this->_importErrors) { array_unshift($this->_importErrors, ""); $error = $this->_getHelper()->__('%1$d records have been imported. See the following list of errors for each record that has not been imported: %2$s', $this->_importedRows, implode(" \n", $this->_importErrors)); Mage::throwException($error); } return $this; }
public function uploadAndImport(Varien_Object $object) { Mage::log('Eparcel uploadAndImport'); $csvFile = $_FILES["groups"]["tmp_name"]["eparcel"]["fields"]["import"]["value"]; if (!empty($csvFile)) { $csv = trim(file_get_contents($csvFile)); $table = Mage::getSingleton('core/resource')->getTableName('australia/eparcel'); $websiteId = $object->getScopeId(); $websiteModel = Mage::app()->getWebsite($websiteId); /* getting condition name from post instead of the following commented logic */ if (isset($_POST['groups']['eparcel']['fields']['condition_name']['inherit'])) { $conditionName = (string) Mage::getConfig()->getNode('default/carriers/eparcel/condition_name'); } else { $conditionName = $_POST['groups']['eparcel']['fields']['condition_name']['value']; } $conditionFullName = Mage::getModel('australia/shipping_carrier_eparcel')->getCode('condition_name_short', $conditionName); if (!empty($csv)) { $exceptions = array(); $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < 8) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Table Rates File Format'); } $countryCodes = array(); $regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) > 0 && count($csvLine) < 8) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Table Rates File Format'); } else { $countryCodes[] = $csvLine[0]; $regionCodes[] = $csvLine[1]; } } if (empty($exceptions)) { $data = array(); $countryCodesToIds = array(); $regionCodesToIds = array(); $countryCodesIso2 = array(); $countryCollection = Mage::getResourceModel('directory/country_collection')->addCountryCodeFilter($countryCodes)->load(); foreach ($countryCollection->getItems() as $country) { $countryCodesToIds[$country->getData('iso3_code')] = $country->getData('country_id'); $countryCodesToIds[$country->getData('iso2_code')] = $country->getData('country_id'); $countryCodesIso2[] = $country->getData('iso2_code'); } $regionCollection = Mage::getResourceModel('directory/region_collection')->addRegionCodeFilter($regionCodes)->addCountryFilter($countryCodesIso2)->load(); foreach ($regionCollection->getItems() as $region) { $regionCodesToIds[$region->getData('code')] = $region->getData('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[] = Mage::helper('shipping')->__('Invalid Country "%s" in the Row #%s', $csvLine[0], $k + 1); } } else { $countryId = $countryCodesToIds[$csvLine[0]]; } if (empty($regionCodesToIds) || !array_key_exists($csvLine[1], $regionCodesToIds)) { $regionId = '0'; if ($csvLine[1] != '*' && $csvLine[1] != '') { $exceptions[] = Mage::helper('shipping')->__('Invalid Region/State "%s" in the Row #%s', $csvLine[1], $k + 1); } } else { $regionId = $regionCodesToIds[$csvLine[1]]; } if ($csvLine[2] == '*' || $csvLine[2] == '') { $zip = ''; } else { $zip = $csvLine[2]; } if (!$this->_isPositiveDecimalNumber($csvLine[3]) || $csvLine[3] == '*' || $csvLine[3] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid %s "%s" in the Row #%s', $conditionFullName, $csvLine[3], $k + 1); } else { $csvLine[3] = (double) $csvLine[3]; } if (!$this->_isPositiveDecimalNumber($csvLine[4]) || $csvLine[4] == '*' || $csvLine[4] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid %s "%s" in the Row #%s', $conditionFullName, $csvLine[4], $k + 1); } else { $csvLine[4] = (double) $csvLine[4]; } if (!$this->_isPositiveDecimalNumber($csvLine[5])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Shipping Price "%s" in the Row #%s', $csvLine[5], $k + 1); } else { $csvLine[5] = (double) $csvLine[5]; } if (!$this->_isPositiveDecimalNumber($csvLine[6])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Shipping Price per Kg "%s" in the Row #%s', $csvLine[6], $k + 1); } else { $csvLine[6] = (double) $csvLine[6]; } $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_zip' => $zip, 'condition_name' => $conditionName, 'condition_from_value' => $csvLine[3], 'condition_to_value' => $csvLine[4], 'price' => $csvLine[5], 'price_per_kg' => $csvLine[6], 'delivery_type' => $csvLine[7]); $dataDetails[] = array('country' => $csvLine[0], 'region' => $csvLine[1]); } } if (empty($exceptions)) { $connection = $this->_getWriteAdapter(); $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName)); $connection->delete($table, $condition); Mage::log(count($data) . " lines read from CSV"); foreach ($data as $k => $dataLine) { try { // convert comma-seperated postcode/postcode range // string into an array $postcodes = array(); foreach (explode(',', $dataLine['dest_zip']) as $postcodeEntry) { $postcodeEntry = explode("-", trim($postcodeEntry)); if (count($postcodeEntry) == 1) { Mage::log("Line {$k}, single postcode: " . $postcodeEntry[0]); // if the postcode entry is length 1, it's // just a single postcode $postcodes[] = $postcodeEntry[0]; } else { // otherwise it's a range, so convert that // to a sequence of numbers $pcode1 = (int) $postcodeEntry[0]; $pcode2 = (int) $postcodeEntry[1]; Mage::log("Line {$k}, postcode range: {$pcode1}-{$pcode2}"); $postcodes = array_merge($postcodes, range(min($pcode1, $pcode2), max($pcode1, $pcode2))); } } Mage::log(var_export($postcodes, true)); foreach ($postcodes as $postcode) { $dataLine['dest_zip'] = str_pad($postcode, 4, "0", STR_PAD_LEFT); $connection->insert($table, $dataLine); } } catch (Exception $e) { //$exceptions[] = Mage::helper('shipping')->__('ERROR Row #%s (Country "%s", Region/State "%s", Zip "%s" and Value "%s")', ($k+1), $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_zip'], $dataLine['condition_value']); Mage::log($e->getMessage()); $exceptionas[] = $e->getMessage(); } } } if (!empty($exceptions)) { throw new Exception("\n" . implode("\n", $exceptions)); } } } }
public function uploadAndImport(Varien_Object $object) { $csvFile = $_FILES["groups"]["tmp_name"]["premiumrate"]["fields"]["import"]["value"]; $csvName = $_FILES["groups"]["name"]["premiumrate"]["fields"]["import"]["value"]; $session = Mage::getSingleton('adminhtml/session'); $dataStored = false; if (!empty($csvFile)) { $csv = trim(file_get_contents($csvFile)); $table = Mage::getSingleton('core/resource')->getTableName('premiumrate_shipping/premiumrate'); $websiteId = $object->getScopeId(); $websiteModel = Mage::app()->getWebsite($websiteId); Mage::helper('wsacommon/shipping')->saveCSV($csv, $csvName, $websiteId, 'premiumrate'); /* getting condition name from post instead of the following commented logic */ if (isset($_POST['groups']['premiumrate']['fields']['condition_name']['inherit'])) { $conditionName = (string) Mage::getConfig()->getNode('default/carriers/premiumrate/condition_name'); } else { $conditionName = $_POST['groups']['premiumrate']['fields']['condition_name']['value']; } $conditionFullName = Mage::getModel('premiumrate_shipping/carrier_premiumrate')->getCode('condition_name_short', $conditionName); if (!empty($csv)) { $exceptions = array(); $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < 15) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Premium Matrix Rates File Format'); } $countryCodes = array(); $regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) > 0 && count($csvLine) < 15) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Premium Matrix Rates File Format'); } else { $splitCountries = explode(",", trim($csvLine[0])); $splitRegions = explode(",", trim($csvLine[1])); foreach ($splitCountries as $country) { if (!in_array($country, $countryCodes)) { $countryCodes[] = trim($country); } } foreach ($splitRegions as $region) { $regionCodes[] = $region; } } } } if (empty($exceptions)) { $connection = $this->_getWriteAdapter(); $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName)); $connection->delete($table, $condition); } if (!empty($exceptions)) { throw new Exception("\n" . implode("\n", $exceptions)); } if (empty($exceptions)) { $data = array(); $countryCodesToIds = array(); $regionCodesToIds = array(); $countryCodesIso2 = array(); $counter = 0; $countryCollection = Mage::getResourceModel('directory/country_collection')->addCountryCodeFilter($countryCodes)->load(); foreach ($countryCollection->getItems() as $country) { $countryCodesToIds[$country->getData('iso3_code')] = $country->getData('country_id'); $countryCodesToIds[$country->getData('iso2_code')] = $country->getData('country_id'); $countryCodesIso2[] = $country->getData('iso2_code'); } $regionCollection = Mage::getResourceModel('directory/region_collection')->addRegionCodeFilter($regionCodes)->addCountryFilter($countryCodesIso2)->load(); foreach ($regionCollection->getItems() as $region) { $regionCodesToIds[$countryCodesToIds[$region->getData('country_id')]][$region->getData('code')] = $region->getData('region_id'); } foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); $splitCountries = explode(",", trim($csvLine[0])); $splitRegions = explode(",", trim($csvLine[1])); //$splitPostcodes = explode(",",trim($csvLine[3])); $splitPostcodes = explode(",", strtoupper(trim($csvLine[3]))); if ($csvLine[2] == '*' || $csvLine[2] == '') { $city = ''; } else { $city = $csvLine[2]; } if ($csvLine[4] == '*' || $csvLine[4] == '') { $zip_to = ''; } else { $zip_to = strtoupper(trim($csvLine[4])); } if ($csvLine[5] == '*' || $csvLine[5] == '') { $weightFrom = 0; } else { if (!$this->_isPositiveDecimalNumber($csvLine[5])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Weight From "%s" in the Row #%s', $csvLine[5], $k + 1); } else { $weightFrom = (double) $csvLine[5]; } } if ($csvLine[6] == '*' || $csvLine[6] == '') { $weightTo = 10000000; } else { if (!$this->_isPositiveDecimalNumber($csvLine[6])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Weight To "%s" in the Row #%s', $csvLine[6], $k + 1); } else { $weightTo = (double) $csvLine[6]; } } if ($csvLine[7] == '*' || $csvLine[7] == '') { $priceFrom = 0; } else { if (!$this->_isPositiveDecimalNumber($csvLine[7])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Price From "%s" in the Row #%s', $csvLine[7], $k + 1); } else { $priceFrom = (double) $csvLine[7]; } } if ($csvLine[8] == '*' || $csvLine[8] == '') { $priceTo = 10000000; } else { if (!$this->_isPositiveDecimalNumber($csvLine[8])) { $exceptions[] = Mage::helper('shipping')->__('Invalid Price To "%s" in the Row #%s', $csvLine[8], $k + 1); } else { $priceTo = (double) $csvLine[8]; } } if ($csvLine[9] == '*' || $csvLine[9] == '') { $itemFrom = 0; } else { $itemFrom = $csvLine[9]; } if ($csvLine[10] == '*' || $csvLine[10] == '') { $itemTo = 10000000; } else { $itemTo = $csvLine[10]; } if ($csvLine[12] == '*' || $csvLine[12] == '') { $algorithm = ''; } else { $algorithm = $csvLine[12]; } if ($csvLine[14] == '*' || $csvLine[14] == '') { $sortOrder = 0; } else { $sortOrder = $csvLine[14]; } foreach ($splitCountries as $country) { $country = trim($country); if (empty($countryCodesToIds) || !array_key_exists($country, $countryCodesToIds)) { $countryId = '0'; if ($country != '*' && $country != '') { $exceptions[] = Mage::helper('shipping')->__('Invalid Country "%s" in the Row #%s', $country, $k + 1); } } else { $countryId = $countryCodesToIds[$country]; } foreach ($splitRegions as $region) { if (!isset($countryCodesToIds[$country]) || !isset($regionCodesToIds[$countryCodesToIds[$country]]) || !array_key_exists($region, $regionCodesToIds[$countryCodesToIds[$country]])) { $regionId = '0'; if ($region != '*' && $region != '') { $exceptions[] = Mage::helper('shipping')->__('Invalid Region/State "%s" in the Row #%s', $region, $k + 1); } } else { $regionId = $regionCodesToIds[$countryCodesToIds[$country]][$region]; } foreach ($splitPostcodes as $postcode) { if ($postcode == '*' || $postcode == '') { $zip = ''; $new_zip_to = ''; } else { $zip_str = explode("-", $postcode); if (count($zip_str) != 2) { $zip = trim($postcode); if (ctype_digit($postcode) && trim($zip_to) == '') { $new_zip_to = trim($postcode); } else { $new_zip_to = $zip_to; } } else { $zip = trim($zip_str[0]); $new_zip_to = trim($zip_str[1]); } } $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_city' => $city, 'dest_zip' => $zip, 'dest_zip_to' => $new_zip_to, 'condition_name' => $conditionName, 'weight_from_value' => $weightFrom, 'weight_to_value' => $weightTo, 'price_from_value' => $priceFrom, 'price_to_value' => $priceTo, 'item_from_value' => $itemFrom, 'item_to_value' => $itemTo, 'price' => $csvLine[11], 'algorithm' => $algorithm, 'delivery_type' => $csvLine[13], 'sort_order' => $sortOrder); $dataDetails[] = array('country' => $country, 'region' => $region); $counter++; } } $dataStored = false; if (!empty($exceptions)) { break; } if ($counter > 1000) { foreach ($data as $k => $dataLine) { try { $connection->insert($table, $dataLine); } catch (Exception $e) { $messageStr = Mage::helper('shipping')->__('Error# 302 - Duplicate Row #%s (Country "%s", Region/State "%s", Zip "%s")', $k + 1, $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_zip']); $exceptions[] = $messageStr; Mage::helper('wsalogger/log')->postWarning('premiumrate', 'Duplicate Row', $messageStr, $this->_debug, '302', 'http://wiki.webshopapps.com/troubleshooting-guide/duplicate-row-error'); //$exceptions[] = Mage::helper('shipping')->__($e); } } Mage::helper('wsacommon/shipping')->updateStatus($session, count($data)); $counter = 0; unset($data); unset($dataDetails); $dataStored = true; } } } if (empty($exceptions) && !$dataStored) { foreach ($data as $k => $dataLine) { try { $connection->insert($table, $dataLine); } catch (Exception $e) { $messageStr = Mage::helper('shipping')->__('Error# 302 - Duplicate Row #%s (Country "%s", Region/State "%s", Zip "%s")', $k + 1, $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_zip']); $exceptions[] = $messageStr; Mage::helper('wsalogger/log')->postWarning('premiumrate', 'Duplicate Row', $messageStr, $this->_debug, 302, 'http://wiki.webshopapps.com/troubleshooting-guide/duplicate-row-error'); } } Mage::helper('wsacommon/shipping')->updateStatus($session, count($data)); } if (!empty($exceptions)) { throw new Exception("\n" . implode("\n", $exceptions)); } } } }
public function uploadAndImport(Varien_Object $object) { $field_email_id = Mage::getStoreConfig('rewardpoints/dataflow_profile/field_email'); $field_points_id = Mage::getStoreConfig('rewardpoints/dataflow_profile/field_points'); $field_order_id = Mage::getStoreConfig('rewardpoints/dataflow_profile/field_order'); $field_store_id = Mage::getStoreConfig('rewardpoints/dataflow_profile/field_store'); if (!isset($_FILES['groups'])) { return false; } $csvFile = $_FILES['groups']['tmp_name']['dataflow_profile']['fields']['import']['value']; if (!empty($csvFile)) { $csv = trim(file_get_contents($csvFile)); $table = Mage::getSingleton('core/resource')->getTableName('rewardpoints/rewardpoints_account'); $websiteId = $object->getScopeId(); $websiteModel = Mage::app()->getWebsite($websiteId); $websiteStores = $websiteModel->getStores(); $storeIds = array(); foreach ($websiteStores as $store) { /*if (!$store->getIsActive()) { continue; }*/ $storeIds[] = $store->getId(); } if (!empty($csv)) { $exceptions = array(); $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < 3) { $exceptions[0] = Mage::helper('rewardpoints')->__('Invalid File Format'); } $emailAddress = array(); //$regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) > 0 && count($csvLine) < 3) { $exceptions[0] = Mage::helper('rewardpoints')->__('Invalid File Format'); } /*else { $emailAddress[] = $csvLine[$field_email_id]; }*/ } if (empty($exceptions)) { $data = array(); $emailAddressToIds = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); $customer = null; $customer_id = ''; $points = ''; $order_id = ''; $store_id = ''; if (!isset($csvLine[$field_email_id])) { $exceptions[] = Mage::helper('rewardpoints')->__('Email address is missing in the Row #%s', $k + 1); } else { $customer = Mage::getModel('customer/customer')->setWebsiteId($websiteId)->loadByEmail($csvLine[$field_email_id]); if ($customer == null) { $exceptions[] = Mage::helper('rewardpoints')->__('Invalid email address "%s" in the Row #%s (customer might not exist)', $csvLine[$field_email_id], $k + 1); } else { $customer_id = $customer->getId(); } } if (!isset($csvLine[$field_points_id])) { $exceptions[] = Mage::helper('rewardpoints')->__('Points missing in the Row #%s', $k + 1); } else { if (!is_numeric($csvLine[$field_points_id])) { $exceptions[] = Mage::helper('rewardpoints')->__('Invalid point format "%s" in the Row #%s', $csvLine[$field_points_id], $k + 1); } else { $points = $csvLine[$field_points_id]; } } if ($field_order_id < 0) { $order_id = $field_order_id; } else { if (!isset($csvLine[$field_order_id])) { $exceptions[] = Mage::helper('rewardpoints')->__('Order id missing in the Row #%s', $k + 1); } else { $order_id = $csvLine[$field_order_id]; $order_check = Mage::getModel('sales/order')->loadByIncrementId($order_id); if (!$order_check->getId()) { $exceptions[] = Mage::helper('rewardpoints')->__('Invalid order Id "%s" in the Row #%s', $order_id, $k + 1); } } } if ($field_store_id == -1) { $store_id = implode(',', $storeIds); } else { if (!isset($csvLine[$field_store_id])) { $exceptions[] = Mage::helper('rewardpoints')->__('Store id(s) missing in the Row #%s', $k + 1); } else { $store_id = $csvLine[$field_store_id]; } } if ($points > 0) { $data[] = array('customer_id' => $customer_id, 'store_id' => $store_id, 'points_current' => $points, 'order_id' => $order_id); } else { $data[] = array('customer_id' => $customer_id, 'store_id' => $store_id, 'points_spent' => $points, 'order_id' => $order_id); } } } if (empty($exceptions)) { $connection = $this->_getWriteAdapter(); foreach ($data as $k => $dataLine) { try { $connection->insert($table, $dataLine); } catch (Exception $e) { $exceptions[] = Mage::helper('rewardpoints')->__('Problem importing Row #%s (customer "%s")', $k + 1, $dataDetails[$k]['customer_id']); } } } if (!empty($exceptions)) { throw new Exception("\n" . implode("\n", $exceptions)); } else { $message = Mage::helper('rewardpoints')->__('%s line(s) processed', sizeof($data)); Mage::getSingleton('adminhtml/session')->addSuccess($message); } } } return $this; }
public function uploadAndImport(Varien_Object $object) { if (empty($_FILES['groups']['tmp_name']['import']['fields']['file']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['import']['fields']['file']['value']; $website = Mage::app()->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $this->_importUniqueHash = array(); $this->_importErrors = array(); $this->_importedRows = 0; $io = new Varien_Io_File(); $info = pathinfo($csvFile); $io->open(array('path' => $info['dirname'])); $io->streamOpen($info['basename'], 'r'); // check and skip headers $headers = $io->streamReadCsv(";"); if ($headers === false || count($headers) < 5) { $io->streamClose(); Mage::throwException(Mage::helper('amlanding')->__('Invalid Landing Pages File Format')); } else { $this->_columns = $this->getFieldsByAliases($headers, Mage::helper('amlanding/import')->getColumnsAliasesForCsv()); } $adapter = $this->_getWriteAdapter(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = array(); $this->loadExistingPages(); while (false !== ($csvLine = $io->streamReadCsv(";"))) { $rowNumber++; if (empty($csvLine)) { continue; } $row = $this->validateCSVRow($csvLine, $rowNumber); if ($row !== false) { $importData[] = $row; } if (count($importData) == 5000) { $this->saveImportData($importData); $importData = array(); } } $this->saveImportData($importData); $io->streamClose(); } catch (Mage_Core_Exception $e) { $adapter->rollback(); $io->streamClose(); Mage::throwException($e->getMessage()); } catch (Exception $e) { $adapter->rollback(); $io->streamClose(); Mage::logException($e); Mage::throwException(Mage::helper('amlanding')->__('An error occurred while import Landing Pages.') . $e->getMessage()); } $adapter->commit(); if ($this->_importErrors) { $error = Mage::helper('shipping')->__('Landing Pages has not been imported completely. See the following list of errors:<br /> %s', implode(" \n", $this->_importErrors)); Mage::throwException($error); } return $this; }
/** * Function to process an uploaded CSV. Tested with several thousand rows and seems fine. * Does some basic validation on the file before running it, and reports errors and * success count to the user once finished. */ public function uploadAndImport(Varien_Object $object) { // Load session and any other useful variables $session = Mage::getSingleton('adminhtml/session'); $table = Mage::getSingleton('core/resource')->getTableName('massredirect/massredirect'); $websiteId = $object->getScopeId(); // CSV Information $importFile = $_FILES["groups"]["tmp_name"]["import_data"]["fields"]["massredirect_import"]["value"]; if (!empty($importFile)) { // Store errors for processing in a batch later $errors = array(); // Load CSV try { $csv = trim(file_get_contents($importFile)); } catch (Exception $e) { $errors[] = Mage::helper('adminhtml')->__('Error opening CSV file.'); $errors[] = $e; } if (!empty($csv)) { $csvLines = explode("\n", $csv); foreach ($csvLines as $k => $csvLine) { $csvLine = Mage::helper('addedbytesmassredirect')->getCsvLine($csvLine); if (count($csvLine) != 3) { $errors[] = Mage::helper('adminhtml')->__('Invalid File Format at line %s', $csvLine); } } // If errors above, we can't continue if (!empty($errors)) { throw new Exception("\n" . implode("\n", $errors)); } // No errors, so let's process the data if (empty($errors)) { // Set up connection $write = $this->_getWriteAdapter(); // Delete existing data for this website $condition = array($write->quoteInto('website_id = ?', $websiteId)); $write->delete($table, $condition); // Loop through file $data = array(); $rowsInserted = 0; $first = true; foreach ($csvLines as $k => $csvLine) { // Skip first line - it contains the headings if ($first) { $first = false; continue; } // Function requires PHP 5.3.0 and up - maybe replace? $csvLine = Mage::helper('addedbytesmassredirect')->getCsvLine($csvLine); // Old URL cannot be blank if (trim($csvLine[0]) == '') { $errors[] = Mage::helper('adminhtml')->__('Row %s does not contain an old URL.', $k + 1); } // Verify that either the New URL or SKU column are set if (trim($csvLine[1]) == '' && trim($csvLine[2]) == '') { $errors[] = Mage::helper('adminhtml')->__('Row %s must contain either a SKU or a New URL.', $k + 1); } // Clean Old URL as much as possible $oldUrl = Mage::helper('addedbytesmassredirect')->cleanUrl($csvLine[0]); // If no errors, add to data array to write if (empty($errors)) { $data[] = array('website_id' => $websiteId, 'old_url' => $oldUrl, 'sku' => $csvLine[1], 'new_url' => $csvLine[2]); } } // Write whatever data has made it through validation foreach ($data as $k => $dataLine) { try { $write->insert($table, $dataLine); $rowsInserted++; } catch (Exception $e) { $errors[] = Mage::helper('adminhtml')->__('Error in Row #%s', $k + 1); $errors[] = $e; } } $session->addSuccess(Mage::helper('adminhtml')->__($rowsInserted . ' rows (of ' . count($csvLines) . ') have been imported.')); } } } if (!empty($errors)) { throw new Exception("\n" . implode("\n", $errors)); } }
/** * Upload CSV file of Tablerate * * @see MMind_Shippingplus_Model_Config_Shippingplus._afterSave() * @param Varien_Object $object * @throws Mage_Core_Exception * @return MMind_Shippingplus_Model_Resource_Shippingplus_Import ***/ public function uploadAndImport(Varien_Object $object) { if (empty($_FILES['groups']['tmp_name']['mmshippingplus']['fields']['import_tablerate']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['mmshippingplus']['fields']['import_tablerate']['value']; $website = Mage::app()->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $io = new Varien_Io_File(); $info = pathinfo($csvFile); $io->open(array('path' => $info['dirname'])); $io->streamOpen($info['basename'], 'r'); // check and skip headers $headers = $io->streamReadCsv(); if ($headers === false || count($headers) < $this->tablerate_cols) { $io->streamClose(); Mage::throwException(Mage::helper('mmshippingplus')->__('Invalid CSV Table Rates File Format')); } $adapter = $this->_getWriteAdapter(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = array(); // delete old data by website and condition name $condition = array('website_id = ?' => $this->_importWebsiteId); $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $io->streamReadCsv())) { $rowNumber++; $nomulti = false; if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber); if ($row !== false) { // Import with Multi country $countries = explode("|", $row[1]); foreach ($countries as $country) { $row[1] = $country; // Import with Multi Region Code $regions = explode("|", $row[2]); foreach ($regions as $region) { $row[2] = $region; // Import with Multi ZIP Code $zips = explode("|", $row[3]); foreach ($zips as $zip) { $row[3] = $zip; $importData[] = $row; } } } } if (count($importData) == 5000) { $this->_saveImportData($importData); $importData = array(); } } $this->_saveImportData($importData); $io->streamClose(); } catch (Mage_Core_Exception $e) { $io->streamClose(); Mage::throwException($e->getMessage()); } catch (Exception $e) { $io->streamClose(); Mage::logException($e); Mage::throwException(Mage::helper('mmshippingplus')->__('An error occurred while import CSV Table rates.')); } $adapter->commit(); if ($this->_importErrors) { $error = Mage::helper('mmshippingplus')->__('%1$d records have been imported. See the following list of errors for each record that has not been imported: %2$s', $this->_importedRows, implode(" \n", $this->_importErrors)); Mage::throwException($error); } return $this; }
/** * Uploads the file and imports the data into the table. * * @param Varien_Object $object * @return $this */ public function uploadAndImport(Varien_Object $object) { if (empty($_FILES['groups']['tmp_name']['dpdparcelshops']['fields']['custom_parcelshops_import']['value'])) { return $this; } $website = Mage::app()->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $csvFile = $_FILES['groups']['tmp_name']['dpdparcelshops']['fields']['custom_parcelshops_import']['value']; $io = new Varien_Io_File(); $info = pathinfo($csvFile); $io->open(array('path' => $info['dirname'])); $io->streamOpen($info['basename'], 'r'); $adapter = $this->_getWriteAdapter(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = array(); $parcelShopNumber = 0; $totalrows = count(file($csvFile)); $condition = array('parcelshop_website_id = ?' => $this->_importWebsiteId); $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $io->streamReadCsv(";"))) { $rowNumber++; if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber, $totalrows); if ($row !== false) { if ($csvLine[0] == 'GR') { $parcelShopNumber++; } if (!isset($importData[$parcelShopNumber])) { $importData[$parcelShopNumber] = array(); } $importData[$parcelShopNumber] = array_merge($importData[$parcelShopNumber], $row); } } $this->_saveImportData($importData); $io->streamClose(); } catch (Mage_Core_Exception $e) { if (count($rowNumber) < 5) { $this->_importErrors[] = Mage::helper('dpd')->__('Invalid ParcelShops format in the Row #%s', $rowNumber); return false; } $adapter->rollback(); $io->streamClose(); Mage::throwException($e->getMessage()); } catch (Exception $e) { $adapter->rollback(); $io->streamClose(); Mage::helper('dpd')->log($e, Zend_Log::ERR); Mage::throwException(Mage::helper('dpd')->__('An error occurred while importing ParcelShops. Check the log for details.')); } if ($this->_importErrors) { $adapter->rollback(); $error = Mage::helper('dpd')->__('File has not been imported. See the following list of errors: %s', implode(" \n", $this->_importErrors)); Mage::throwException($error); } $adapter->commit(); return $this; }
public function uploadAndImport(Varien_Object $object) { $exceptions = array(); $csvFile = $_FILES["groups"]["tmp_name"]["shippingproviders"]["fields"]["importcsv"]["value"]; if (!empty($csvFile)) { if ($flg = $this->isValidFile($_FILES["groups"]["name"]["shippingproviders"]["fields"]["importcsv"]["value"])) { $csv = trim(file_get_contents($csvFile)); $table = 'shipping_zones'; //Mage::getSingleton('core/resource')->getTableName('matrixrate_shipping/zones'); $websiteId = $object->getScopeId(); $websiteModel = Mage::app()->getWebsite($websiteId); /* if (isset($_POST['groups']['shippingproviders']['fields']['condition_name']['inherit'])) { $conditionName = (string) Mage::getConfig()->getNode('default/carriers/matrixrate/condition_name'); } else { $conditionName = $_POST['groups']['shippingproviders']['fields']['condition_name']['value']; } $conditionFullName = Mage::getModel('matrixrate_shipping/carrier_matrixrate')->getCode('condition_name_short', $conditionName); */ $conditionName = 'standard'; $conditionFullName = 'Standard'; if (!empty($csv)) { $csvLines = explode("\n", $csv); $csvLine = array_shift($csvLines); $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) < 4) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Matrix Rates File Format'); } $countryCodes = array(); $regionCodes = array(); foreach ($csvLines as $k => $csvLine) { $csvLine = $this->_getCsvValues($csvLine); if (count($csvLine) > 0 && count($csvLine) < 4) { $exceptions[0] = Mage::helper('shipping')->__('Invalid Matrix Rates File Format'); } else { $countryCodes[] = $csvLine[0]; $regionCodes[] = $csvLine[1]; } } if (empty($exceptions)) { $data = array(); foreach ($csvLines as $k => $csvLine) { $fromFlag = false; $toFlag = false; $csvLine = $this->_getCsvValues($csvLine); if ($csvLine[0] == '*' || $csvLine[0] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid Country code in the Row #%s', $k + 1); } if ($csvLine[1] == '*' || $csvLine[1] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid Zone in the Row #%s', $k + 1); } if ($csvLine[2] == '*' || $csvLine[2] == '' || strtolower($csvLine[2]) != 'standard') { $exceptions[] = Mage::helper('shipping')->__('Invalid Delivery type "%s" in the Row #%s', $csvLine[2], $k + 1); } if ($csvLine[3] == '*' || $csvLine[3] == '') { $exceptions[] = Mage::helper('shipping')->__('Invalid Shipping provider in the Row #%s', $k + 1); } $data[] = array('country_code' => $csvLine[0], 'zone' => $csvLine[1], 'delivery_type' => $csvLine[2], 'shipping_provider' => $csvLine[3]); $dataDetails[] = array('zone' => $csvLine[1]); } } if (empty($exceptions)) { $connection = $this->_getWriteAdapter(); $condition = array($connection->quoteInto('delivery_type = ?', $conditionName)); $connection->delete($table, $condition); foreach ($data as $k => $dataLine) { try { $connection->insert($table, $dataLine); } catch (Exception $e) { $exceptions[] = Mage::helper('shipping')->__('Duplicate Row #%s (Country Code "%s", Zone "%s", Delivery Type "%s" and Shipping Provider "%s")', $k + 1, $dataLine['country_code'], $dataDetails[$k]['zone'], $dataLine['delivery_type'], $dataLine['shipping_provider']); } } } } } else { $exceptions[] = Mage::helper('shipping')->__('Invalid Shipping Provider file, only "csv" file is allowed.'); } if (!empty($exceptions)) { throw new Exception("<br>" . implode("<br>", $exceptions)); } } }