Tuesday, October 9, 2012

Import shopping cart price rule (coupon code)


<?php
$mageFilename = 'app/Mage.php';

require_once $mageFilename;

Varien_Profiler::enable();

Mage::setIsDeveloperMode(true);

ini_set('display_errors', 1);

umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);

class generateCouponCode{
   
    protected $_file = 'coupon_code.csv';
    protected $_count = 0;
   
    public function csvToArray($_file) {
        $csvArray = array();
        $file = fopen($_file, "r");
        fgetcsv($file);
        while (!feof($file)) {
            $values = fgetcsv($file);
            if ($values) {
                $csvArray[] = $values;
            }
        }
        return $csvArray;
    }

    public function getAllCustomerGroups() {
    //get all customer groups
        $customerGroups = Mage::getModel('customer/group')->getCollection();
        $groups = array();
        foreach ($customerGroups as $group) {
            $groups[] = $group->getId();
        }
        return $groups;
    }

    public function getAllWbsites() {
    //get all wabsites
        $websites = Mage::getModel('core/website')->getCollection();
        $websiteIds = array();
        foreach ($websites as $website) {
            $websiteIds[] = $website->getId();
        }
        return $websiteIds;
    }

    //read comments for each line
    public function generateRule($uniqueId) {

        $conditionProduct = Mage::getModel('salesrule/rule_condition_product')
                                                ->setType('salesrule/rule_condition_product')
                                                ->setAttribute('sku')
                                                ->setOperator('==')
                                                ->setValue('Bab0001');
                                               
        /** @var Mage_SalesRule_Model_Rule_Condition_Product_Found $conditionProductFound */
        $conditionProductFound = Mage::getModel('salesrule/rule_condition_product_found')
                                            ->setConditions(array($conditionProduct));
       
        /** @var Mage_SalesRule_Model_Rule_Condition_Combine $condition */
        $condition = Mage::getModel('salesrule/rule_condition_combine')
                    ->setConditions(array($conditionProductFound));
                   
        $rule = Mage::getModel('salesrule/rule');
        $rule->setName($uniqueId);
        $rule->setCouponType('2');
        $rule->setDescription('');
        $rule->setFromDate('2012-10-05');//date('Y-m-d')
        $rule->setToDate('2013-10-05');//date('Y-m-d')
        $rule->setCouponCode($uniqueId);
        $rule->setUsesPerCoupon(1); //number of allowed uses for this coupon
        $rule->setUsesPerCustomer(1); //number of allowed uses for this coupon for each customer
        $rule->setCustomerGroupIds($this->getAllCustomerGroups());
        $rule->setIsActive(1);
        $rule->setStopRulesProcessing(0); //set to 1 if you want all other rules after this to not be processed
        $rule->setIsRss(0); //set to 1 if you want this rule to be public in rss
        $rule->setIsAdvanced(1); //have no idea what it means :)
        $rule->setProductIds('');
        $rule->setSortOrder(0); // order in which the rules will be applied
        $rule->setSimpleAction('cart_fixed');
        $rule->setDiscountAmount('29.98');
        $rule->setDiscountQty(0); //Maximum Qty Discount is Applied to
        $rule->setDiscountStep(0); //used for buy_x_get_y; This is X
        $rule->setSimpleFreeShipping(0); //set to 1 for Free shipping
        $rule->setApplyToShipping(0); //set to 0 if you don't want the rule to be applied to shipping
        $rule->setWebsiteIds($this->getAllWbsites());
        $rule->setConditionsSerialized(serialize($condition->asArray()));
        $rule->setConditions($condition);
        $rule->loadPost($rule->getData());
       
        try
        {
            $rule->save();  
            Mage::log('Coupon code created for '.$uniqueId.'', null, 'couponcode.log');
            $this->_count++;
        }
        catch (Exception $e)
        {
            echo 'Caught exception for coupon code '.$uniqueId.':: ',  $e->getMessage(), "\n";
            Mage::log('Caught exception for coupon code '.$uniqueId.'::'.$e->getMessage().'', null, 'couponcode.log');
        }
    }
   
    public function importCsv() {
       
        $file = Mage::getBaseDir('base').DS.$this->_file;
       
        if (empty($file)) {
            throw new Exception("You need to upload a file to import.");
        }
       
        $csv = trim(file_get_contents($file));
       
        if (empty($csv)) {
            throw new Exception("The file is empty.");
        }
       
        $csv = $this->csvToArray($file);

        foreach ($csv as $key => $row) {
            $this->generateRule($row[0]);
        }
       
        echo sprintf("total %s coupon code created",$this->_count);
    }
   
}
$obj = new generateCouponCode();
$obj->importCsv();

?>

Wednesday, August 22, 2012

Backing Up The Database via SSH/Telnet

In order to back up your database via SSH or Telnet you will require 2 things:

1) SSH or Telnet access to your site. You will need to check with your hosting company to see if this is available.

2) An SSH/Telnet Client, such as PuTTy.

Open your SSH/Telnet client and log into your website. The command line prompt you will see will vary by OS.
For most hosting companies, this will bring you into the FTP root folder.

Type in the following to create a backup in the current directory:

mysqldump --opt -Q -u dbusername -p databasename > backupname.sql

Or to create a backup in a separate directory (signified by /path/to/) type:

mysqldump --opt -Q -u dbusername -p databasename > /path/to/backupname.sql

You will be prompted for the database password. Enter it and the database will backup.

If your hosting company has you on a remote MySQL server, such as mysql.yourhost.com, you will need to add the servername to the command line. The servername will be the same as in your config.php. The command line will be:

Current directory:

mysqldump --opt -Q -h servername -u dbusername -p databasename > backupname.sql

Separate directory:

mysqldump --opt -Q -h servername -u dbusername -p databasename > /path/to/backupname.sql

Thursday, August 16, 2012

PHP: Get all tables from database


<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>

Magento: Get admin user’s data (id, name, username, email, password, etc).


$userArray = Mage::getSingleton('admin/session')->getData();

$user = Mage::getSingleton('admin/session');
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();

Magento: Update layout or add js with controller



public function myAction()
{

    /* ... Some code ...*/

    $update = $this->getLayout()->getUpdate();

    /* ... Some code ...*/

    $this->addActionLayoutHandles();

    /* ... Some code ...*/

    $this->loadLayoutUpdates();

    /* ... Some code ...*/

    $update->addUpdate('
        <reference name="head">
            <action method="addJs"><script>varien/product.js</script></action>
            <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params /><!--<if/><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if /><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if /><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>skin_js</type><name>js/bundle.js</name></action>
        </reference>
    ');

    /* ... Some code ...*/

    $this->generateLayoutXml()->generateLayoutBlocks();

    /* ... Some code ...*/

    $this->renderLayout();

}


Wednesday, August 15, 2012

Magento: Admin page not found error

After moving magento to live server or demo server. If not able to access admin page or got page not found error. apply below sql query.

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

Monday, July 30, 2012

Upgrading magento from 1.4.1.1 to 1.6.0.0 (issue with upgrading databse)

If found issue with query "ALTER TABLE `sales_flat_order` ADD UNIQUE `UNQ_INCREMENT_ID` ( `increment_id` )" and taking a long time at this stage than need to find duplicate entires..

try this...

find duplicate increment ids..
SELECT increment_id, COUNT(*) c FROM sales_flat_order GROUP BY increment_id HAVING c > 1;

create new file on root and run below code..

require 'app/Mage.php';
Mage::app('admin');

 $dupes= array('R00168293-1','R00168534-1','R00168946-1');

Mage::getSingleton("core/session", array("name" => "adminhtml"));
Mage::register('isSecureArea',true);
$collection = Mage::getResourceModel('sales/order_collection')
  ->addAttributeToSelect('*')
  ->setPageSize(5000)
  ->addFieldToFilter('status', 'canceled')
  ->addFieldToFilter('increment_id', array('in'=>$dupes))
  ->load();

foreach ($collection as $col) {
  Mage::log($col->getIncrementId() . ' order deleted ');
  try {
    $col->delete();
  } catch (Exception $e) {
    throw $e;
  }
}