public function getExtensions() { $data = array(); try { $file = 'http://d52ndf1ixk2tu.cloudfront.net/media/featured_product.csv'; /* https does not work */ $content = $this->urlGetContents($file); if ($content == false) { $file = 'https://www.iwdagency.com/extensions/media/featured_product.csv'; $content = $this->urlGetContents($file); if ($content == false) { return ""; } } $path = Mage::getBaseDir('media') . DS . 'import' . DS . 'featured_product.csv'; if (!file_exists(Mage::getBaseDir('media') . DS . 'import')) { mkdir(Mage::getBaseDir('media') . DS . 'import'); } file_put_contents($path, $content); $csv = new Varien_File_Csv(); $data = $csv->getData($path); @unlink($path); } catch (Exception $e) { Mage::logException($e); } return $data; }
public function saveAction() { if ($data = $this->getRequest()->getPost()) { $file_path = Mage::getBaseDir() . '/media/enquiryform/' . str_replace(' ', "_", $data['name']) . '_' . date("d_m_Y_H_i_s") . '.csv'; $mage_csv = new Varien_File_Csv(); $mage_csv->saveData($file_path, $data); exit; $model = Mage::getModel('eventmanager/eventmanagercustom'); $model->setData($data)->setId($this->getRequest()->getParam('id')); try { if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) { $model->setCreatedTime(now())->setUpdateTime(now()); } else { $model->setUpdateTime(now()); } $model->save(); Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('eventmanager')->__('Custom event request was successfully saved')); Mage::getSingleton('adminhtml/session')->setFormData(false); if ($this->getRequest()->getParam('back')) { $this->_redirect('*/*/edit', array('id' => $model->getId())); return; } $this->_redirect('*/*/'); return; } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setFormData($data); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); return; } } Mage::getSingleton('adminhtml/session')->addError(Mage::helper('eventmanager')->__('Unable to find the request to save')); $this->_redirect('*/*/'); }
public function importMotorsDataAction() { $helper = Mage::helper('M2ePro/Component_Ebay_Motors'); $motorsType = $this->getRequest()->getPost('motors_type'); if (!$motorsType || empty($_FILES['source']['tmp_name'])) { $this->getSession()->addError(Mage::helper('M2ePro')->__('Some of required fields are not filled up.')); return $this->_redirect('*/*/index'); } $csvParser = new Varien_File_Csv(); $tempCsvData = $csvParser->getData($_FILES['source']['tmp_name']); $csvData = array(); $headers = array_shift($tempCsvData); foreach ($tempCsvData as $csvRow) { $csvData[] = array_combine($headers, $csvRow); } $added = 0; $existedItems = $this->getExistedMotorsItems(); $connWrite = Mage::getSingleton('core/resource')->getConnection('core/write'); $tableName = $helper->getDictionaryTable($motorsType); foreach ($csvData as $csvRow) { if (!($insertsData = $this->getPreparedInsertData($csvRow, $existedItems))) { continue; } $added++; $connWrite->insert($tableName, $insertsData); } $this->_getSession()->addSuccess("Successfully added '{$added}' compatibility records."); return $this->_redirect('*/*/index'); }
public function importDataAction() { try { if ($this->getRequest()->getPost()) { if (isset($_FILES['import_file']['name']) && $_FILES['import_file']['name'] != '') { $uploaderFile = new Varien_File_Uploader('import_file'); $uploaderFile->setAllowedExtensions(array('csv')); $uploaderFile->setAllowRenameFiles(true); $uploaderFile->setFilesDispersion(false); $uploaderFilePath = Mage::getBaseDir('cache') . DS . 'mgs' . DS . 'brand' . DS . 'import' . DS . 'csv' . DS; $uploaderFile->save($uploaderFilePath, $_FILES['import_file']['name']); $filePath = $uploaderFilePath . $uploaderFile->getUploadedFileName(); $csv = new Varien_File_Csv(); $brands = $csv->getData($filePath); $i = 0; foreach ($brands as $brand) { if ($i > 0) { Mage::helper('brand')->import($brand); } $i++; } $urlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('id_path', 'brand/index/'); foreach ($urlRewriteCollection as $url) { $url->delete(); } $urlRewrite = Mage::getModel('core/url_rewrite')->loadByIdPath('brand/index')->setIdPath('brand/index'); if (Mage::helper('brand')->urlKey() != '') { $urlRewrite->setRequestPath(Mage::helper('brand')->urlKey()); } else { $urlRewrite->setRequestPath('brand'); } $urlRewrite->setTargetPath('brand/index/index'); $urlRewrite->setIsSystem(1); $urlRewrite->save(); $collection = Mage::getModel('brand/brand')->getCollection(); foreach ($collection as $brand) { $urlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('id_path', 'brand/view/' . $brand->getId()); foreach ($urlRewriteCollection as $url) { $url->delete(); } $urlRewrite = Mage::getModel('core/url_rewrite')->loadByIdPath('brand/view/' . $brand->getId())->setIdPath('brand/view/' . $brand->getId()); if (Mage::helper('brand')->urlKey() != '') { $urlRewrite->setRequestPath(Mage::helper('brand')->urlKey() . '/' . $brand->getUrlKey()); } else { $urlRewrite->setRequestPath('brand/' . $brand->getUrlKey()); } $urlRewrite->setTargetPath('brand/index/view/id/' . $brand->getId()); $urlRewrite->setIsSystem(1); $urlRewrite->save(); } Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('brand')->__('All brands were successfully imported.')); $this->_redirect('*/*/index'); } } } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); $this->_redirect('*/*/import'); } }
public function importproductAction() { if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') { try { $types = explode('.', $_FILES['fileToUpload']['name']); $fileType = $types[count($types) - 1]; if ($fileType != 'csv') { echo Mage::helper('inventoryplus')->__("Wrong file's format"); return; } $fileName = $_FILES['fileToUpload']['tmp_name']; $Object = new Varien_File_Csv(); $dataFile = $Object->getData($fileName); $receiptstockProduct = array(); $receiptstockProducts = array(); $fields = array(); $count = 0; $receiptstockHelper = Mage::helper('inventoryreceipt'); $url = Mage::getUrl('inventoryreceiptadmin/adminhtml_receipt/index'); if (count($dataFile)) { foreach ($dataFile as $col => $row) { if ($col == 0) { if (count($row)) { foreach ($row as $index => $cell) { $fields[$index] = (string) $cell; } } } elseif ($col > 0) { if (count($row)) { foreach ($row as $index => $cell) { if (isset($fields[$index])) { $receiptstockProduct[$fields[$index]] = $cell; } } } $receiptstockProducts[] = $receiptstockProduct; } } } else { if (count($dataFile) == 0) { echo Mage::helper('inventoryreceipt')->__("File is empty"); return; } } if (count($receiptstockProducts) > 0) { $receiptstockHelper->importProduct($receiptstockProducts); } else { echo Mage::helper('inventoryreceipt')->__("Wrong information's structure"); return; } } catch (Exception $e) { } } }
public function getLanguageCsvData() { $website = $this->getWebsite(); $file = $website->getLanguageDirFile(); try { $csv = new Varien_File_Csv(); $data = $csv->getData($file); return $data; } catch (Exception $e) { return NULL; } }
public function saveAction() { $data = $this->getRequest()->getParams(); $uploader = new Mage_Core_Model_File_Uploader('file'); $uploader->setAllowedExtensions(array('csv')); $uploader->setAllowRenameFiles(true); $path = Mage::getBaseDir('var') . DS . 'import'; if (!file_exists($path)) { mkdir($path, 0777); } try { $result = $uploader->save($path); $fullPath = $result['path'] . DS . $result['file']; $csv = new Varien_File_Csv(); $data = $csv->getData($fullPath); $items = array(); if (count($data) > 1) { for ($i = 1; $i < count($data); $i++) { $item = array(); for ($j = 0; $j < count($data[0]); $j++) { if (isset($data[$i][$j]) && trim($data[$i][$j]) != '') { $item[strtolower($data[0][$j])] = $data[$i][$j]; } } $items[] = $item; } } $resource = Mage::getSingleton('core/resource'); $writeConnection = $resource->getConnection('core_write'); $table = $resource->getTableName('seo/redirect'); $table2 = $resource->getTableName('seo/redirect_store'); $i = 0; foreach ($items as $item) { pr($item); if (!isset($item['url_from']) || !isset($item['url_to'])) { continue; } $item = new Varien_Object($item); $query = "REPLACE {$table} SET\n url_from = '" . addslashes($item->getUrlFrom()) . "',\n url_to = '" . addslashes($item->getUrlTo()) . "',\n is_redirect_only_error_page = '" . addslashes($item->getIsRedirectOnlyErrorPage()) . "',\n comments = '" . addslashes($item->getComments()) . "',\n is_active = '" . addslashes($item->getIsActive()) . "';\n REPLACE {$table2} SET\n store_id = 0,\n redirect_id = LAST_INSERT_ID();\n "; $writeConnection->query($query); $i++; } Mage::getSingleton('adminhtml/session')->addSuccess('' . $i . ' records were inserted or updated'); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } $this->_redirect('*/*/'); }
protected function _importStopwords($file) { $csv = new Varien_File_Csv(); $data = $csv->getData(Mage::getBaseDir('var') . DS . 'import' . DS . $file); $result = array(); foreach ($data as $value) { $result[] = array('stopword' => $value[0]); } if (strlen(serialize($result)) < 65535) { $config = new Mage_Core_Model_Config(); $config->saveConfig('searchsphinx/advanced/stopwords', serialize($result), 'default', 0); } else { return 'File too long'; } return sprintf('Imported %s lines', count($result)); }
public function saveAction() { $data = $this->getRequest()->getParams(); $uploader = new Mage_Core_Model_File_Uploader('file'); $uploader->setAllowedExtensions(array('csv')); $uploader->setAllowRenameFiles(true); $path = Mage::getBaseDir('var') . DS . 'import'; if (!file_exists($path)) { mkdir($path, 0777); } try { $result = $uploader->save($path); $fullPath = $result['path'] . DS . $result['file']; $csv = new Varien_File_Csv(); $data = $csv->getData($fullPath); $items = array(); if (count($data) > 1) { for ($i = 1; $i < count($data); $i++) { $item = array(); for ($j = 0; $j < count($data[0]); $j++) { if (isset($data[$i][$j]) && trim($data[$i][$j]) != '') { $item[strtolower($data[0][$j])] = $data[$i][$j]; } } $items[] = $item; } } $resource = Mage::getSingleton('core/resource'); $writeConnection = $resource->getConnection('core_write'); $table = $resource->getTableName('seoautolink/link'); $table2 = $resource->getTableName('seoautolink/link_store'); $i = 0; foreach ($items as $item) { if (!isset($item['keyword'])) { continue; } $item = new Varien_Object($item); $query = "REPLACE {$table} SET\n keyword = '" . addslashes($item->getKeyword()) . "',\n url = '" . addslashes($item->getUrl()) . "',\n url_title = '" . addslashes($item->getUrlTitle()) . "',\n url_target = '" . addslashes($item->getUrlTarget()) . "',\n is_nofollow = '" . (int) $item->getIsNofollow() . "',\n max_replacements = '" . (int) $item->getMaxReplacements() . "',\n sort_order = '" . (int) $item->getSortOrder() . "',\n occurence = '" . (int) $item->getOccurence() . "',\n is_active = '" . (int) $item->getIsActive() . "',\n created_at = '" . now() . "',\n updated_at = '" . now() . "';\n REPLACE {$table2} SET\n store_id = '" . (int) $item->getStoreId() . "',\n link_id = LAST_INSERT_ID();\n "; $writeConnection->query($query); $i++; } Mage::getSingleton('adminhtml/session')->addSuccess('' . $i . ' records were inserted or updated'); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } $this->_redirect('*/*/'); }
public function importFilesRelations($csvPath, $uploadedFiles) { $csv = new Varien_File_Csv(); $data = $csv->getData($csvPath); foreach ($data as $line) { if (!is_array($line) || count($line) != 2) { continue; } $files = explode(';', $line[1]); $fileIds = array(); foreach ($files as $path) { $fileIds[] = array_search(Mage::getBaseDir('media') . '/downloads_import/' . $path, $uploadedFiles); } $skus = explode(';', $line[0]); $this->_assignFiles($fileIds, $skus); } }
public function getExtensions() { $data = array(); try { $file = 'http://dg8i44zfacfed.cloudfront.net/featured_product.csv'; $content = $this->urlGetContents($file); $path = Mage::getBaseDir('media') . DS . 'import' . DS . 'featured_product.csv'; if (!file_exists(Mage::getBaseDir('media') . DS . 'import')) { mkdir(Mage::getBaseDir('media') . DS . 'import'); } file_put_contents($path, $content); $csv = new Varien_File_Csv(); $data = $csv->getData($path); @unlink($path); } catch (Exception $e) { Mage::logException($e); } return $data; }
public function getImportCsvAction() { if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') { try { $fileName = $_FILES['fileToUpload']['tmp_name']; $Object = new Varien_File_Csv(); $dataFile = $Object->getData($fileName); $warehouseProduct = array(); $warehouseProducts = array(); $fields = array(); $count = 0; $helper = Mage::helper('inventorywarehouse/warehouse'); if (count($dataFile)) { foreach ($dataFile as $col => $row) { if ($col == 0) { if (count($row)) { foreach ($row as $index => $cell) { $fields[$index] = (string) $cell; } } } elseif ($col > 0) { if (count($row)) { foreach ($row as $index => $cell) { if (isset($fields[$index])) { $warehouseProduct[$fields[$index]] = $cell; } } } $source = $this->getRequest()->getParam('source'); $productId = Mage::getModel('catalog/product')->getIdBySku($warehouseProduct['SKU']); $warehouseproduct = Mage::getModel('inventoryplus/warehouse_product')->getCollection()->addFieldToFilter('warehouse_id', $source)->addFieldToFilter('product_id', $productId); if (!$warehouseproduct->getSize()) { $warehouseProducts[] = $warehouseProduct; } } } } $helper->importProduct($warehouseProducts); } catch (Exception $e) { } } }
/** * Export the eParcel table rates as a CSV file. */ public function exportTableratesAction() { $rates = Mage::getResourceModel('australia/shipping_carrier_eparcel_collection'); $response = array(array('Country', 'Region/State', 'Postcodes', 'Weight from', 'Weight to', 'Parcel Cost', 'Cost Per Kg', 'Delivery Type', 'Charge Code Individual', 'Charge Code Business')); foreach ($rates as $rate) { $countryId = $rate->getData('dest_country_id'); $countryCode = Mage::getModel('directory/country')->load($countryId)->getIso3Code(); $regionId = $rate->getData('dest_region_id'); $regionCode = Mage::getModel('directory/region')->load($regionId)->getCode(); $response[] = array($countryCode, $regionCode, $rate->getData('dest_zip'), $rate->getData('condition_from_value'), $rate->getData('condition_to_value'), $rate->getData('price'), $rate->getData('price_per_kg'), $rate->getData('delivery_type'), $rate->getData('charge_code_individual'), $rate->getData('charge_code_business')); } $csv = new Varien_File_Csv(); $temp = tmpfile(); foreach ($response as $responseRow) { $csv->fputcsv($temp, $responseRow); } rewind($temp); $contents = stream_get_contents($temp); $this->_prepareDownloadResponse('tablerates.csv', $contents); fclose($temp); }
public function saveAction() { if (!isset($_FILES['csv_store'])) { Mage::getSingleton('core/session')->addError('Not selected file!'); $this->_redirect('*/*/importstore'); return; } $oFile = new Varien_File_Csv(); $data = $oFile->getData($_FILES['csv_store']['tmp_name']); $store = Mage::getModel('storepickup/store'); $storeData = array(); try { $total = 0; foreach ($data as $col => $row) { if ($col == 0) { $index_row = $row; } else { for ($i = 0; $i < count($row); $i++) { $storeData[$index_row[$i]] = $row[$i]; } $store->setData($storeData); $store->setId(null); if ($store->import()) { $total++; } } } $this->_redirect('*/adminhtml_store/index'); if ($total != 0) { Mage::getSingleton('core/session')->addSuccess('Imported successful total ' . $total . ' stores'); } else { Mage::getSingleton('core/session')->addSuccess('Stores exist'); } } catch (Exception $e) { Mage::getSingleton('core/session')->addError($e->getMessage()); $this->_redirect('*/*/importstore'); } }
public function getPendingList() { $csv = new Varien_File_Csv(); $pendingList = array(); try { $todoList = $csv->getData($this->_helper->getStoragePath() . $this->_helper->getAllActionsFilename()); $doneList = $csv->getData($this->_helper->getStoragePath() . $this->_helper->getExecutedActionsFilename()); $todo = array(); $done = array(); foreach ($todoList as $k => $v) { $todo[$k] = implode('|', $v); } foreach ($doneList as $k => $v) { $done[$k] = implode('|', $v); } foreach (array_diff($todo, $done) as $k => $v) { $pendingList[$k] = $todoList[$k]; } } catch (Exception $e) { $this->_helper->log($e->getMessage()); } return $pendingList; }
public function import() { $file = $this->_path . $this->_fileName; if (!is_file($file)) { Mage::throwException(Mage::helper('ism_newstore_members')->__('Invalid file!')); } $csv = new Varien_File_Csv(); $data = $csv->getData($file); unset($data[0]); $skuCodes = array_column($data, 0); $prices = array_column($data, 1); $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('sku', array('in' => $skuCodes)); $prices = array_combine($skuCodes, $prices); foreach ($collection as $item) { try { $item->setIsmNewstoremembersPrice($prices[$item->getSku()])->save(); } catch (Exception $e) { Mage::log('Error with product: ' . $item->getSku()); } } unlink($file); return $this; }
public function indexAction() { $file = "https://cart.simicommerce.com/media/simicart/languages/0/e/e089b299ff3a892ebe25e02725c4b33a.csv"; $file = Mage::getBaseDir('media') . DS . 'simicart' . DS . 'languages' . DS . "2/5/53de68fd512d1216dd74ae964b99d7e8.csv"; $csv = new Varien_File_Csv(); $data = $csv->getData($file); $codes = $data[0]; //print_r($data);die(); for ($i = 1; $i < count($data); $i++) { for ($j = 1; $j < count($data[$i]); $j++) { if ($codes[$j]) { //ton tai code if (strpos($data[$i][0], '/*') === false) { // ko phai comment if ($data[$i][$j]) { // cum tu translated co ton tai $str .= '"' . $data[$i][0] . '" = "' . $data[$i][$j] . '";' . "<br>"; } } } } } echo $str; }
protected function _importData() { $reviewsFile = $this->getArg('reviews'); $ratingsFile = $this->getArg('ratings'); $mapping = $this->getArg('mapping'); $baseDir = Mage::getBaseDir(); $reviewPath = $baseDir . '/' . $reviewsFile; $ratingPath = $baseDir . '/' . $ratingsFile; if ($mapping) { $mapping = $this->_parseMapping($mapping); } if (file_exists($reviewPath) && file_exists($ratingPath)) { $csv = new Varien_File_Csv(); $reviews = $this->_getCsvWithHeaders($csv->getData($reviewPath)); $ratings = $this->_getCsvWithHeaders($csv->getData($ratingPath)); $count = 0; foreach ($reviews as $review) { $reviewModel = Mage::getModel('review/review'); $reviewModel->setData(array('entity_id' => $reviewModel->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE), 'entity_pk_value' => $mapping ? $mapping[$review['entity_pk_value']] : $review['entity_pk_value'], 'status_id' => $review['status_id'], 'customer_id' => null, 'title' => $review['title'], 'nickname' => $review['nickname'], 'detail' => $review['detail'], 'store_id' => $review['store_id'], 'stores' => array($review['store_id'])))->save(); //double save because review model checks for an id and resets this on new objects - i know it sucks $reviewModel->setCreatedAt($review['created_at'])->save(); $reviewRatings = array_filter($ratings, function ($rating) use($review) { return $rating['review_id'] == $review['review_id']; }); foreach ($reviewRatings as $rating) { Mage::getModel('rating/rating')->setRatingId($rating['rating_id'])->setReviewId($reviewModel->getId())->setCustomerId($rating['customer_id'])->addOptionVote($rating['option_id'], $mapping ? $mapping[$rating['entity_pk_value']] : $rating['entity_pk_value']); } $reviewModel->aggregate(); $count++; } echo 'Successfully imported ' . $count . ' reviews'; } else { echo "One of the files doesn't exist."; } return $this; }
public function importAction() { $fileTrue = $this->fileImportCsvUpload(); if ($fileTrue) { $file = 'var/CodImport/' . $fileTrue; $csv = new Varien_File_Csv(); $data = $csv->getData($file); if (count($data[0] == 2) && $data[0][0] == 'Country' && $data[0][1] == 'Zip/Postal Code') { //echo "<pre>"; print_r($data);die; //Mage::getResourceModel('cod/postcode')->truncate(); $coll = Mage::getModel('cod/postcode')->getCollection(); $tableName = $coll->getResource()->getMainTable(); $conn = $coll->getConnection(); $conn->truncateTable($tableName); $i = 1; foreach ($data as $value) { if ($i != 1) { $datacsv = array('website_id' => 1, 'dest_country_id' => $value[0], 'dest_zip' => $value[1]); $model = Mage::getModel('cod/postcode')->setData($datacsv); try { $insertId = $model->save()->getId(); } catch (Exception $e) { echo $e->getMessage(); } } $i++; } Mage::getSingleton('core/session')->addSuccess("Import success"); } else { Mage::getSingleton('core/session')->addError("Import is failed."); } } else { Mage::getSingleton('core/session')->addError("Import is failed."); } $this->_redirect("*/*/index"); }
/** * @function save type Form csv data * * * * * */ public function typeFormSurvery() { try { $path = Mage::getBaseDir() . DS . 'survey_csv'; if (!is_dir()) { mkdir($path); } $uploader = new Varien_File_Uploader('csv_file'); $uploader->setAllowedExtensions(array('csv')); $uploader->setAllowCreateFolders(true); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $savedPath = $uploader->save($path, $fname); $savedFilePath = $savedPath['path'] . DS . $savedPath['file']; $csv = new Varien_File_Csv(); $data = $csv->getData($savedFilePath); unlink($savedFilePath); $surveryModel = Mage::getModel('survey/survey'); $hasColumnNameRow = $surveryModel->getCollection()->setPageSize(1); //zend_debug::dump($data);exit; if (count($hasColumnNameRow) == 0) { //$surveryModel->setData('completed', strtotime(trim($value[1]))); //$surveryModel->setData('token', trim($value[4])); $surveryModel->setData('q1', $data[0][1]); $surveryModel->setData('q2', $data[0][3]); // $surveryModel->setData('q3', $data[0][11]); $surveryModel->setData('q4', $data[0][2]); $surveryModel->setData('q5', $data[0][5]); $surveryModel->setData('q6', $data[0][4]); $surveryModel->setData('q7', $data[0][7]); $surveryModel->setData('q8', $data[0][6]); //$surveryModel->setData('q9', $data[0][17]); $surveryModel->save(); $surveryModel->unsetData(); } unset($data[0]); foreach ($data as $key => $value) { $surveryModel->setData('token', $value[9]); $date = trim($value[12]); $date = str_replace('/', '-', $date); $surveryModel->setData('completed', date('Y-m-d', strtotime($date))); $surveryModel->setData('q1', $value[1]); $surveryModel->setData('q2', $value[3]); //$surveryModel->setData('q3', $value[11]); $surveryModel->setData('q4', $value[2]); $surveryModel->setData('q5', $value[5]); $surveryModel->setData('q6', $value[4]); $surveryModel->setData('q7', $value[7]); $surveryModel->setData('q8', $value[6]); //$surveryModel->setData('q9', $value[17]); $surveryModel->save(); $surveryModel->unsetData(); } Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Survey Uploaded Successfully.. ')); Mage::getSingleton('adminhtml/session')->setCrmData(false); $this->_redirect('*/*/'); return; } catch (exception $e) { Mage::getSingleton('adminhtml/session')->addError('There is some error.. '); Mage::getSingleton('adminhtml/session')->setCrmData($this->getRequest()->getPost()); $this->_redirect('*/*/'); return; } }
/** * */ public function massPrintAction() { $prepareKey = $this->getRequest()->getParam('massaction_prepare_key'); $ids = $this->getRequest()->getParam($prepareKey); $labelType = $this->getRequest()->getParam('labelType'); $printMethod = $this->getRequest()->getParam('printMethod'); $row_start = $this->getRequest()->getParam('row_start'); $col_start = $this->getRequest()->getParam('col_start'); $labelInfo = array('xmlData' => file_get_contents('js/itwebexperts_payperrentals/labelPrinter/dymo_labels/' . $labelType . '.label'), 'data' => array()); foreach (explode(',', $ids) as $label) { $barcodeType = 'Code128Auto'; if ($label > 0) { $sendReturnId = Mage::getModel('payperrentals/rentalqueue')->load($label); $resOrder = Mage::getModel('payperrentals/sendreturn')->load($sendReturnId->getSendreturnId()); $snArr = explode(',', $resOrder->getSn()); $customer = Mage::getModel('customer/customer')->load($resOrder->getCustomerId()); /** @var $address Mage_Customer_Model_Address */ $address = Mage::getModel('customer/address')->load($customer->getDefaultShipping()); /** replace \n and blank space to avoid indenting in pdf */ $addressFormated = str_replace("\n", "", $address->format('html_special')); $re = "/(<br\\s?\\/>)\\s*/"; $addressFormated = preg_replace($re, '$1', $addressFormated); /** regex remove trailing <br/> */ $re = "/<br\\/>\\z/"; $addressFormated = preg_replace($re, '', $addressFormated); $product = Mage::getModel('catalog/product')->load($resOrder->getProductId()); $productName = $product->getName(); $productDescription = $product->getDescription(); foreach ($snArr as $sn) { $labelInfo['data'][] = array('ProductsName' => $productName, 'Barcode' => $sn, 'BarcodeType' => $barcodeType, 'ProductsDescription' => $productDescription, 'Address' => $sn . "\n\n" . $addressFormated, 'products_name' => $productName, 'barcode' => $sn, 'barcode_type' => $barcodeType, 'products_description' => $productDescription, 'customers_address' => $addressFormated); } } } if ($printMethod == 'dymo') { $html = array('labelInfo' => $labelInfo); $this->getResponse()->setBody(Zend_Json::encode($html)); } else { if ($printMethod == 'pdf') { Mage::helper('payperrentals/labels')->setData($labelInfo['data']); Mage::helper('payperrentals/labels')->setLabelsType($labelType); Mage::helper('payperrentals/labels')->setStartLocation($row_start, $col_start); Mage::helper('payperrentals/labels')->buildPDF(); } else { $csv = new Varien_File_Csv(); $sepString = $this->getRequest()->getParam('field_separator'); $sep = ';'; switch ($sepString) { case 'tab': $sep = ' '; break; case 'semicolon': $sep = ';'; break; case 'colon': $sep = ':'; break; case 'comma': $sep = ','; } if ($sep) { $csv->setDelimiter($sep); } $io = new Varien_Io_File(); $path = Mage::getBaseDir('var') . DS . 'export' . DS; //best would be to add exported path through config $name = md5(microtime()); $file = $path . DS . $name . '.csv'; /** * It is possible that you have name collision (summer/winter time +1/-1) * Try to create unique name for exported .csv file */ while (file_exists($file)) { sleep(1); $name = md5(microtime()); $file = $path . DS . $name . '.csv'; } $io->setAllowCreateFolders(true); $io->open(array('path' => $path)); $io->streamOpen($file, 'w+'); $io->streamLock(true); $headers = array('ProductsName', 'Barcode', 'BarcodeType', 'ProductsDescription', 'Address', 'products_name', 'barcode', 'barcode_type', 'products_description', 'customers_address'); $io->streamWriteCsv($headers, $sep); foreach ($labelInfo['data'] as $row) { $io->streamWriteCsv($row, $sep); } $io->streamUnlock(); $io->streamClose(); //$csv->saveData($file, $labelInfo['data']); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"labelSpreadsheet.csv\";"); header("Content-Transfer-Encoding: binary"); //echo $io->streamReadCsv($sep); echo file_get_contents($file); //echo $csv->getData($file); die; } } }
/** * Retrieve data from file * * @param string $file * @return array */ protected function _getFileData($file) { $data = array(); if (file_exists($file)) { $parser = new Varien_File_Csv(); $parser->setDelimiter(self::CSV_SEPARATOR); $data = $parser->getDataPairs($file); } return $data; }
/** * * @param type $file_code is code of options function getList() * @return array */ protected function readCsvFile($file_code) { $f_name = $this->getFileNameByCode($file_code); $path_folder = str_replace(array('\\', '/'), DS, self::_PATH_FOLDER); $folder = Mage::getBaseDir('media') . DS . $path_folder; $file = $folder . DS . $f_name; $csv = new Varien_File_Csv(); $data = $this->getDataPairs($csv->getData($file)); //if use cache if (Mage::app()->useCache('translate')) { $this->_cache->save(serialize($data), self::_PRE_CACHE_KEY . $file_code, array('cache_localization_data'), 60 * 60 * 24); } return $data; }
protected function _importRates() { $fileName = $_FILES['import_rates_file']['tmp_name']; $csvObject = new Varien_File_Csv(); $csvData = $csvObject->getData($fileName); /** checks columns */ $csvFields = array(0 => Mage::helper('tax')->__('Code'), 1 => Mage::helper('tax')->__('Country'), 2 => Mage::helper('tax')->__('State'), 3 => Mage::helper('tax')->__('Zip/Post Code'), 4 => Mage::helper('tax')->__('Rate'), 5 => Mage::helper('tax')->__('Zip/Post is Range'), 6 => Mage::helper('tax')->__('Range From'), 7 => Mage::helper('tax')->__('Range To')); $stores = array(); $unset = array(); $storeCollection = Mage::getModel('core/store')->getCollection()->setLoadDefault(false); for ($i = count($csvFields); $i < count($csvData[0]); $i++) { $header = $csvData[0][$i]; $found = false; foreach ($storeCollection as $store) { if ($header == $store->getCode()) { $csvFields[$i] = $store->getCode(); $stores[$i] = $store->getId(); $found = true; } } if (!$found) { $unset[] = $i; } } $regions = array(); if ($unset) { foreach ($unset as $u) { unset($csvData[0][$u]); } } if ($csvData[0] == $csvFields) { /** @var $helper Mage_Adminhtml_Helper_Data */ $helper = Mage::helper('adminhtml'); foreach ($csvData as $k => $v) { if ($k == 0) { continue; } //end of file has more then one empty lines if (count($v) <= 1 && !strlen($v[0])) { continue; } if ($unset) { foreach ($unset as $u) { unset($v[$u]); } } if (count($csvFields) != count($v)) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('Invalid file upload attempt')); } $country = Mage::getModel('directory/country')->loadByCode($v[1], 'iso2_code'); if (!$country->getId()) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('One of the country has invalid code.')); continue; } if (!isset($regions[$v[1]])) { $regions[$v[1]]['*'] = '*'; $regionCollection = Mage::getModel('directory/region')->getCollection()->addCountryFilter($v[1]); if ($regionCollection->getSize()) { foreach ($regionCollection as $region) { $regions[$v[1]][$region->getCode()] = $region->getRegionId(); } } } if (!empty($regions[$v[1]][$v[2]])) { $rateData = array('code' => $helper->stripTags($v[0]), 'tax_country_id' => $v[1], 'tax_region_id' => $regions[$v[1]][$v[2]] == '*' ? 0 : $regions[$v[1]][$v[2]], 'tax_postcode' => empty($v[3]) || $v[3] == '*' ? null : $v[3], 'rate' => $v[4], 'zip_is_range' => $v[5], 'zip_from' => $v[6], 'zip_to' => $v[7]); $rateModel = Mage::getModel('tax/calculation_rate')->loadByCode($rateData['code']); foreach ($rateData as $dataName => $dataValue) { $rateModel->setData($dataName, $dataValue); } $titles = array(); foreach ($stores as $field => $id) { $titles[$id] = $v[$field]; } //filter tags in titles foreach ($titles as &$title) { $title = $helper->stripTags($title); } $rateModel->setTitle($titles); $rateModel->save(); } } } else { Mage::throwException(Mage::helper('tax')->__('Invalid file format upload attempt')); } }
protected function runUpdate() { $this->setData('script_started_at', Mage::app()->getLocale()->date(null, null, Mage::app()->getLocale()->getDefaultLocale())); $this->setData('script_finished_at', Mage::app()->getLocale()->date(null, null, Mage::app()->getLocale()->getDefaultLocale())); $messages = array(); $this->setData('messages', $messages); $website = $this->getRequest()->getParam('website'); $store = $this->getRequest()->getParam('store'); $testmode = $this->getRequest()->getParam('testmode', 0); $sku = $this->getRequest()->getParam('sku'); $limit = (int) $this->getRequest()->getParam('limit', 0); $offset = (int) $this->getRequest()->getParam('offset', 0); if ($limit > 100) { $limit = 100; } $store_code = Mage_Core_Model_Store::DEFAULT_CODE; if ($store != "") { $store_code = $store; } $this->setData('is_feed', false); try { $Generator = Mage::getModel('googlebasefeedgenerator/generator', array('store_code' => $store_code)); $messages[] = array('msg' => 'Store ' . Mage::app()->getStore($store_code)->getName(), 'type' => 'info'); /* @var $Generator RocketWeb_GoogleBaseFeedGenerator_Model_Generator*/ if ($testmode) { if ($limit > $Generator->getConfigVar('button_max_products')) { $limit = $Generator->getConfigVar('button_max_products'); } $this->setTestMode(true); $Generator->setTestMode(true); if ($sku) { $Generator->setTestSku($sku); $this->setTestSku($sku); } elseif ($offset >= 0 && $limit > 0) { $Generator->setTestOffset($offset); $this->setTestOffset($offset); $Generator->setTestLimit($limit); $this->setTestLimit($limit); } else { Mage::throwException(sprintf("Invalid parameters for test mode: sku %s or offset %s and limit %s", $sku, $offset, $limit)); } $messages[] = array('msg' => 'Test mode.', 'type' => 'info'); } else { $this->setTestMode(false); } if (!$Generator->getConfigVar('is_turned_on')) { $messages[] = array('msg' => 'Can\'t generate feed. It\'s disabled from config option: RocketWeb Extensions > Google Base Feed Generator > Settings > Enabled.', 'type' => 'error'); $this->setData('messages', $messages); return; } if (!$this->getTestMode()) { $collection = Mage::getModel('catalog/product')->getCollection(); $collection->setStoreId(Mage::app()->getStore($store_code)->getStoreId()); $count = $collection->getSize(); if ($count > $Generator->getConfigVar('button_max_products')) { Mage::throwException(sprintf("Too many products. Detected %d products more than the limit allowed of %d.", $count, $Generator->getConfigVar('button_max_products'))); } } // Generate feed - costly process. $Generator->run(); if ($Generator->getCountProductsExported() > 0) { $this->setData('is_feed', true); } } catch (Exception $e) { $messages[] = array('msg' => 'Error:<br />' . $e->getMessage(), 'type' => 'error'); } $count_products = 0; $count_skipped = 0; if (isset($Generator) && is_object($Generator) && $Generator instanceof RocketWeb_GoogleBaseFeedGenerator_Model_Generator) { $count_products = $Generator->getCountProductsExported(); $count_skipped = $Generator->getCountProductsSkipped(); } $feed_data = array(); if ($this->getIsFeed() && $sku != "" && $count_products > 0 && file_exists($Generator->getFeedPath())) { /* tsv file */ $csv = new Varien_File_Csv(); $csv->setDelimiter("\t"); $csv->setEnclosure('~'); // dummy enclosure $rows = $csv->getData($Generator->getFeedPath()); $i = 0; foreach ($rows as $row) { if ($i == 0) { $i++; continue; } $feed_data[] = array_combine($rows[0], $row); $i++; } } $this->setFeedData($feed_data); $messages[] = array('msg' => sprintf("The feed was generated.<br />%d items were added %d products were skipped.", $count_products, $count_skipped), 'type' => 'info'); $this->setData('messages', $messages); $this->setData('script_finished_at', Mage::app()->getLocale()->date(null, null, Mage::app()->getLocale()->getDefaultLocale())); }
public function prepareAction() { $this->_title($this->__('Inventory'))->_title($this->__('Add New Physical Stocktaking')); if ($data = $this->getRequest()->getPost() || !Mage::helper('inventoryplus')->isWarehouseEnabled() || $this->getRequest()->getParam('warehouse_id')) { if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') { try { /* Starting upload */ $uploader = new Varien_File_Uploader('fileToUpload'); // Any extention would work $uploader->setAllowedExtensions(array('csv')); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); try { $fileName = $_FILES['fileToUpload']['tmp_name']; $Object = new Varien_File_Csv(); $dataFile = $Object->getData($fileName); $adjustStockProduct = array(); $adjustStockProducts = array(); $fields = array(); if (count($dataFile)) { foreach ($dataFile as $col => $row) { if ($col == 0) { if (count($row)) { foreach ($row as $index => $cell) { $fields[$index] = (string) $cell; } } } elseif ($col > 0) { if (count($row)) { foreach ($row as $index => $cell) { if (isset($fields[$index])) { $adjustStockProduct[$fields[$index]] = $cell; } } } $adjustStockProducts[] = $adjustStockProduct; } } } if (count($adjustStockProducts)) { $adjustStockProducts['warehouse_id'] = $this->getRequest()->getPost('warehouse_id'); Mage::getModel('admin/session')->setData('physicalstocktaking_product_import', $adjustStockProducts); $this->loadLayout()->_setActiveMenu('inventoryplus/stock_onhand/physical_stock'); $this->getLayout()->getBlock('head')->setCanLoadExtJs(true)->removeItem('js', 'mage/adminhtml/grid.js')->addItem('js', 'magestore/adminhtml/inventory/grid.js'); $this->_addContent($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit')->setPhysicalstocktakingProducts($adjustStockProducts))->_addLeft($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit_tabs')->setPhysicalstocktakingProducts($adjustStockProducts)); $this->renderLayout(); } else { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventoryphysicalstocktaking')->__('Unable to find item to save')); $this->_redirect('*/*/new'); } } catch (Exception $e) { } } catch (Exception $e) { } } else { if ($this->getRequest()->getPost('warehouse_id')) { $adjustStockProducts['warehouse_id'] = $this->getRequest()->getPost('warehouse_id'); } if (!Mage::helper('inventoryplus')->isWarehouseEnabled()) { $adjustStockProducts['warehouse_id'] = Mage::getModel('inventoryplus/warehouse')->getCollection()->getFirstItem()->getId(); $adminId = Mage::getSingleton('admin/session')->getUser()->getId(); $canPhysicalAdmins = Mage::getModel('inventoryplus/warehouse_permission')->getCollection()->addFieldToFilter('warehouse_id', $adjustStockProducts['warehouse_id'])->addFieldToFilter('admin_id', $adminId)->addFieldToFilter('can_physical', 1); if (!$canPhysicalAdmins->getSize()) { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventoryphysicalstocktaking')->__('You have not permission to physical stocktaking!')); session_write_close(); $this->_redirect('*/*/'); } } else { if (!$this->getRequest()->getPost('warehouse_id') && $this->getRequest()->getParam('warehouse_id')) { $adjustStockProducts['warehouse_id'] = $this->getRequest()->getParam('warehouse_id'); } } Mage::getModel('admin/session')->setData('physicalstocktaking_product_warehouse', $adjustStockProducts); $this->loadLayout()->_setActiveMenu('inventoryplus/stock_onhand/physical_stock'); $this->getLayout()->getBlock('head')->setCanLoadExtJs(true)->removeItem('js', 'mage/adminhtml/grid.js')->addItem('js', 'magestore/adminhtml/inventory/grid.js'); $this->_addContent($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit')->setPhysicalstocktakingProducts($adjustStockProducts))->_addLeft($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit_tabs')->setPhysicalstocktakingProducts($adjustStockProducts)); $this->renderLayout(); } } else { Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventoryphysicalstocktaking')->__('Unable to find item to save')); $this->_redirect('*/*/new'); } }
public function importproductAction() { if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') { try { $fileName = $_FILES['fileToUpload']['tmp_name']; $Object = new Varien_File_Csv(); $dataFile = $Object->getData($fileName); $supplierProduct = array(); $supplierProducts = array(); $fields = array(); $count = 0; $supplierHelper = Mage::helper('inventorypurchasing/supplier'); if (count($dataFile)) { foreach ($dataFile as $col => $row) { if ($col == 0) { if (count($row)) { foreach ($row as $index => $cell) { $fields[$index] = (string) $cell; } } } elseif ($col > 0) { if (count($row)) { foreach ($row as $index => $cell) { if (isset($fields[$index])) { $supplierProduct[$fields[$index]] = $cell; } } } $supplierProducts[] = $supplierProduct; } } } $supplierHelper->importProduct($supplierProducts); } catch (Exception $e) { } } }
public function createImageAction() { $file = Mage::getBaseDir('media') . DS . 'simicart' . DS . 'languages' . DS . '210f8511708eee01582b78ff241481a6/it_IT/default.csv'; $csv = new Varien_File_Csv(); $data = $csv->getData($file); $codes = $data[0]; print_r($codes); return; $image_file = $_GET['src']; $corner_radius = isset($_GET['radius']) ? $_GET['radius'] : 20; // The default corner radius is set to 20px $angle = isset($_GET['angle']) ? $_GET['angle'] : 0; // The default angle is set to 0º $topleft = (isset($_GET['topleft']) and $_GET['topleft'] == "no") ? false : true; // Top-left rounded corner is shown by default $bottomleft = (isset($_GET['bottomleft']) and $_GET['bottomleft'] == "no") ? false : true; // Bottom-left rounded corner is shown by default $bottomright = (isset($_GET['bottomright']) and $_GET['bottomright'] == "no") ? false : true; // Bottom-right rounded corner is shown by default $topright = (isset($_GET['topright']) and $_GET['topright'] == "no") ? false : true; // Top-right rounded corner is shown by default $images_dir = ''; $corner_source = imagecreatefrompng('rounded_corner.png'); $corner_width = imagesx($corner_source); $corner_height = imagesy($corner_source); $corner_resized = imagecreatetruecolor($corner_radius, $corner_radius); imagecopyresampled($corner_resized, $corner_source, 0, 0, 0, 0, $corner_radius, $corner_radius, $corner_width, $corner_height); $corner_width = imagesx($corner_resized); $corner_height = imagesy($corner_resized); $image = imagecreatetruecolor($corner_width, $corner_height); $image = imagecreatefromjpeg($images_dir . $image_file); // replace filename with $_GET['src'] $size = getimagesize($images_dir . $image_file); // replace filename with $_GET['src'] $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0); // Top-left corner if ($topleft == true) { $dest_x = 0; $dest_y = 0; imagecolortransparent($corner_resized, $black); imagecopymerge($image, $corner_resized, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100); } // Bottom-left corner if ($bottomleft == true) { $dest_x = 0; $dest_y = $size[1] - $corner_height; $rotated = imagerotate($corner_resized, 90, 0); imagecolortransparent($rotated, $black); imagecopymerge($image, $rotated, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100); } // Bottom-right corner if ($bottomright == true) { $dest_x = $size[0] - $corner_width; $dest_y = $size[1] - $corner_height; $rotated = imagerotate($corner_resized, 180, 0); imagecolortransparent($rotated, $black); imagecopymerge($image, $rotated, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100); } // Top-right corner if ($topright == true) { $dest_x = $size[0] - $corner_width; $dest_y = 0; $rotated = imagerotate($corner_resized, 270, 0); imagecolortransparent($rotated, $black); imagecopymerge($image, $rotated, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100); } // Rotate image $image = imagerotate($image, $angle, $white); // Output final image imagejpeg($image); // Remove temp files imagedestroy($image); imagedestroy($corner_source); }
/** * @title "Process Adding Products into Listing" * @hidden */ public function processAddProductsToListingAction() { $sourceType = $this->getRequest()->getPost('source_type', 'sku'); $listing = Mage::getModel('M2ePro/Listing')->load($this->getRequest()->getPost('listing_id')); if (empty($_FILES['source']['tmp_name']) || !$listing) { $this->_getSession()->addError('Some required fields are empty.'); $this->_redirectUrl(Mage::helper('adminhtml')->getUrl('*/*/processAddProductsToListing')); } $csvParser = new Varien_File_Csv(); $tempCsvData = $csvParser->getData($_FILES['source']['tmp_name']); $csvData = array(); $headers = array_shift($tempCsvData); foreach ($tempCsvData as $csvRow) { $csvData[] = array_combine($headers, $csvRow); } $success = 0; foreach ($csvData as $csvRow) { $magentoProduct = $sourceType == 'id' ? Mage::getModel('catalog/product')->load($csvRow['id']) : Mage::getModel('catalog/product')->loadByAttribute('sku', $csvRow['sku']); if (!$magentoProduct) { continue; } $listingProduct = $listing->addProduct($magentoProduct); if ($listingProduct instanceof Ess_M2ePro_Model_Listing_Product) { $success++; } } $this->_getSession()->addSuccess("Success '{$success}' Products."); $this->_redirectUrl(Mage::helper('M2ePro/View_Development')->getPageModuleTabUrl()); }
public function exportordersAction() { //DebugBreak(); $file_path = Mage::getBaseDir() . '/var/export/sales_order_export.csv'; $mage_csv = new Varien_File_Csv(); $information_row = array(); $area_name = $this->getRequest()->getParam('area-name'); $from_date = $this->getRequest()->getParam('from-date'); $to_date = $this->getRequest()->getParam('to-date'); $data[0]['area'] = 'Area'; $data[0]['date'] = 'Date'; $data[0]['count'] = 'Total Orders'; $data[0]['subtotal'] = 'Subtotal'; $data[0]['invoiced'] = 'Invoiced'; $data[0]['refunded'] = 'Refunded'; $data[0]['tax_amount'] = 'Tax amount'; $data[0]['shipping_amount'] = 'Shipping Amount'; $data[0]['discounts'] = 'Discounts'; $data[0]['cancelled'] = 'Cancelled'; if ($area_name == "All Areas") { //DebugBreak(); $collection = Mage::getModel('pincode/pincode')->getCollection(); $i = 1; foreach ($collection as $collection_area) { $area_names[] = $collection_area->getData('area_name'); } foreach ($area_names as $area_name) { $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); $read = Mage::getSingleton('core/resource')->getConnection('core_read'); $sql1 = "SELECT pin_code FROM pincode where area_name='" . $area_name . "'"; $res = $read->fetchRow($sql1); $pincode = $res['pin_code']; $sql2 = "SELECT count(postcode),email FROM sales_flat_order_address where postcode in ('" . $pincode . "') and address_type='billing' group by sales_flat_order_address.postcode"; $res1 = $read->fetchRow($sql2); $sql3 = "select count(sales_flat_order_address.postcode),sum(sales_flat_order.subtotal),sum(sales_flat_order.base_subtotal_invoiced),sum(sales_flat_order.subtotal_refunded),sum(sales_flat_order.base_shipping_tax_amount),sum(sales_flat_order.shipping_amount),sum(sales_flat_order.discount_amount),sum(sales_flat_order.subtotal_canceled),date(sales_flat_order.created_at) from sales_flat_order,sales_flat_order_address where sales_flat_order_address.parent_id = sales_flat_order.entity_id and sales_flat_order_address.postcode in ('" . $pincode . "')and sales_flat_order_address.address_type='billing' and date(sales_flat_order.created_at) between '" . $from_date . "' and '" . $to_date . "' group by sales_flat_order_address.postcode,date(sales_flat_order.created_at)"; $ress2 = $read->fetchAll($sql3); foreach ($ress2 as $res2) { //DebugBreak(); $data[$i]['area'] = $area_name; $data[$i]['date'] = $res2['date(sales_flat_order.created_at)']; $data[$i]['count'] = $res2['count(sales_flat_order_address.postcode)']; $data[$i]['subtotal'] = $res2['sum(sales_flat_order.subtotal)']; $data[$i]['invoiced'] = $res2['sum(sales_flat_order.base_subtotal_invoiced)']; $data[$i]['refunded'] = $res2['sum(sales_flat_order.subtotal_refunded)']; $data[$i]['tax_amount'] = $res2['sum(sales_flat_order.base_shipping_tax_amount)']; $data[$i]['shipping_amount'] = $res2['sum(sales_flat_order.shipping_amount)']; $data[$i]['discounts'] = $res2['sum(sales_flat_order.discount_amount)']; $data[$i]['cancelled'] = $res2['sum(sales_flat_order.subtotal_canceled)']; $orders_placed[] = $res2['count(sales_flat_order_address.postcode)']; $subtotal[] = $res2['sum(sales_flat_order.subtotal)']; $base_subtotal_invoiced[] = $res2['sum(sales_flat_order.base_subtotal_invoiced)']; $subtotal_refunded[] = $res2['sum(sales_flat_order.subtotal_refunded)']; $base_shipping_tax_amount[] = $res2['sum(sales_flat_order.base_shipping_tax_amount)']; $shipping_amount[] = $res2['sum(sales_flat_order.shipping_amount)']; $discount_amount[] = $res2['sum(sales_flat_order.discount_amount)']; $subtotal_canceled[] = $res2['sum(sales_flat_order.subtotal_canceled)']; $i++; } $data[$i]['area'] = 'Total'; $data[$i]['date'] = ' '; $data[$i]['count'] = array_sum($orders_placed); $data[$i]['subtotal'] = array_sum($subtotal); $data[$i]['invoiced'] = array_sum($base_subtotal_invoiced); $data[$i]['refunded'] = array_sum($subtotal_refunded); $data[$i]['tax_amount'] = array_sum($base_shipping_tax_amount); $data[$i]['shipping_amount'] = array_sum($shipping_amount); $data[$i]['discounts'] = array_sum($discount_amount); $data[$i]['cancelled'] = array_sum($subtotal_canceled); } foreach ($data as $val) { $information_row[] = $val; } } else { $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); $read = Mage::getSingleton('core/resource')->getConnection('core_read'); $sql1 = "SELECT pin_code FROM pincode where area_name='" . $area_name . "'"; $res = $read->fetchRow($sql1); $pincode = $res['pin_code']; $sql2 = "SELECT count(postcode),email FROM sales_flat_order_address where postcode in (" . $pincode . ") and address_type='billing' group by sales_flat_order_address.postcode"; $res1 = $read->fetchRow($sql2); $sql3 = "select count(sales_flat_order_address.postcode),sum(sales_flat_order.subtotal),sum(sales_flat_order.base_subtotal_invoiced),sum(sales_flat_order.subtotal_refunded),sum(sales_flat_order.base_shipping_tax_amount),sum(sales_flat_order.shipping_amount),sum(sales_flat_order.discount_amount),sum(sales_flat_order.subtotal_canceled),date(sales_flat_order.created_at) from sales_flat_order,sales_flat_order_address where sales_flat_order_address.parent_id = sales_flat_order.entity_id and sales_flat_order_address.postcode in ('" . $pincode . "')and sales_flat_order_address.address_type='billing' and date(sales_flat_order.created_at) between '" . $from_date . "' and '" . $to_date . "' group by sales_flat_order_address.postcode,date(sales_flat_order.created_at)"; $ress2 = $read->fetchAll($sql3); $i = 1; foreach ($ress2 as $res2) { $data[$i]['area'] = $area_name; $data[$i]['date'] = $res2['date(sales_flat_order.created_at)']; $data[$i]['count'] = $res2['count(sales_flat_order_address.postcode)']; $data[$i]['subtotal'] = $res2['sum(sales_flat_order.subtotal)']; $data[$i]['invoiced'] = $res2['sum(sales_flat_order.base_subtotal_invoiced)']; $data[$i]['refunded'] = $res2['sum(sales_flat_order.subtotal_refunded)']; $data[$i]['tax_amount'] = $res2['sum(sales_flat_order.base_shipping_tax_amount)']; $data[$i]['shipping_amount'] = $res2['sum(sales_flat_order.shipping_amount)']; $data[$i]['discounts'] = $res2['sum(sales_flat_order.discount_amount)']; $data[$i]['cancelled'] = $res2['sum(sales_flat_order.subtotal_canceled)']; $orders_placed[] = $res2['count(sales_flat_order_address.postcode)']; $subtotal[] = $res2['sum(sales_flat_order.subtotal)']; $base_subtotal_invoiced[] = $res2['sum(sales_flat_order.base_subtotal_invoiced)']; $subtotal_refunded[] = $res2['sum(sales_flat_order.subtotal_refunded)']; $base_shipping_tax_amount[] = $res2['sum(sales_flat_order.base_shipping_tax_amount)']; $shipping_amount[] = $res2['sum(sales_flat_order.shipping_amount)']; $discount_amount[] = $res2['sum(sales_flat_order.discount_amount)']; $subtotal_canceled[] = $res2['sum(sales_flat_order.subtotal_canceled)']; $i++; } $data[$i]['area'] = 'Total'; $data[$i]['date'] = ' '; $data[$i]['count'] = array_sum($orders_placed); $data[$i]['subtotal'] = array_sum($subtotal); $data[$i]['invoiced'] = array_sum($base_subtotal_invoiced); $data[$i]['refunded'] = array_sum($subtotal_refunded); $data[$i]['tax_amount'] = array_sum($base_shipping_tax_amount); $data[$i]['shipping_amount'] = array_sum($shipping_amount); $data[$i]['discounts'] = array_sum($discount_amount); $data[$i]['cancelled'] = array_sum($subtotal_canceled); foreach ($data as $val) { $information_row[] = $val; } } //$data = array(); $mage_csv->saveData($file_path, $information_row); $message = $this->__('CSV is exported'); Mage::getSingleton('adminhtml/session')->addSuccess($message); $this->_redirect('*/*/salesreport'); }