Magento Import Shopping Cart Rules Programmatically

You can import exported shopping rules from exported CSV.
<?php
/**********Importing exported shopping rules from exported csv************/

require_once('app/Mage.php');
umask(0);

if (!Mage::isInstalled()) {
 echo "Application is not installed yet, please complete install wizard first.";
 exit;
}

// Only for urls // Don't remove this
$_SERVER['SCRIPT_NAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_NAME']);
$_SERVER['SCRIPT_FILENAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_FILENAME']);

Mage::app('admin')->setUseSessionInUrl(false);
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
error_reporting(E_ALL);

try {
 Mage::getConfig()->init();
 Mage::app();
} catch (Exception $e) {
 Mage::printException($e);
}
ini_set('memory_limit', '500M');

$importCount = 0;
$writeAdapter = Mage::getSingleton('core/resource')->getConnection('core_write');

try {

 $fileToImport = 'exported-rules.csv';
 $csv = new Varien_File_Csv();
 $csvDataToImport = $csv->getData($fileToImport);
 $headerFlag = 0;
 foreach ($csvDataToImport as $dataToImport) {
 if (!$headerFlag) {
 $headerColumns = array_flip($dataToImport);
 $headerFlag = 1;
 } else {
 // for assigned customer groups
 $customerGroupIds = $dataToImport[$headerColumns['customer_group_ids']];
 $customerGroupIdsArray = array();
 if (isset($customerGroupIds)) {
 $customerGroupIds = explode(',', $customerGroupIds);
 foreach ($customerGroupIds as $customerGroupId) {
 $customerGroupIdsArray[] = $customerGroupId;
 }
 }

 // for assigned website ids
 $websiteIds = $dataToImport[$headerColumns['website_ids']];
 $websiteIdsArray = array();
 if (isset($websiteIds)) {
 $websiteIds = explode(',', $websiteIds);
 foreach ($websiteIds as $websiteId) {
 $websiteIdsArray[] = $websiteId;
 }
 }

 $data = array(
 //'rule_id' => (int)($dataToImport[$headerColumns['rule_id']] + 50),
 'name' => $dataToImport[$headerColumns['name']],
 'description' => $dataToImport[$headerColumns['description']],
 'from_date' => $dataToImport[$headerColumns['from_date']],
 'to_date' => $dataToImport[$headerColumns['to_date']],
 'uses_per_customer' => $dataToImport[$headerColumns['uses_per_customer']],
 'is_active' => $dataToImport[$headerColumns['is_active']],
 'conditions_serialized' => $dataToImport[$headerColumns['conditions_serialized']],
 'actions_serialized' => $dataToImport[$headerColumns['actions_serialized']],
 'stop_rules_processing' => $dataToImport[$headerColumns['stop_rules_processing']],
 'is_advanced' => $dataToImport[$headerColumns['is_advanced']],
 'product_ids' => $dataToImport[$headerColumns['product_ids']],
 'sort_order' => $dataToImport[$headerColumns['sort_order']],
 'simple_action' => $dataToImport[$headerColumns['simple_action']],
 'discount_amount' => $dataToImport[$headerColumns['discount_amount']],
 'discount_qty' => $dataToImport[$headerColumns['discount_qty']],
 'discount_step' => $dataToImport[$headerColumns['discount_step']],
 'simple_free_shipping' => $dataToImport[$headerColumns['simple_free_shipping']],
 'apply_to_shipping' => $dataToImport[$headerColumns['apply_to_shipping']],
 'times_used' => $dataToImport[$headerColumns['times_used']],
 'is_rss' => $dataToImport[$headerColumns['is_rss']],
 'coupon_type' => $dataToImport[$headerColumns['coupon_type']],
 'use_auto_generation' => $dataToImport[$headerColumns['use_auto_generation']],
 'uses_per_coupon' => $dataToImport[$headerColumns['uses_per_coupon']],
 'customer_group_ids' => $customerGroupIdsArray,
 'website_ids' => $websiteIdsArray,
 'coupon_code' => $dataToImport[$headerColumns['coupon_code']]
 );

 $ruleModel = Mage::getModel('salesrule/rule');
 $data = filterDates($data, array('from_date', 'to_date'));
 $validateResult = $ruleModel->validateData(new Varien_Object($data));
 if ($validateResult == true) {
 if (isset($data['simple_action']) && $data['simple_action'] == 'by_percent'
 && isset($data['discount_amount'])
 ) {
 $data['discount_amount'] = min(100, $data['discount_amount']);
 }
 if (isset($data['rule']['conditions'])) {
 $data['conditions'] = $data['rule']['conditions'];
 }

 if (isset($data['rule']['actions'])) {
 $data['actions'] = $data['rule']['actions'];
 }

 unset($data['rule']);
 $ruleModel->loadPost($data);

 $ruleModel->save();

 // for assigned autogenerated coupons
 $autogeneratedCouponCodes = unserialize(trim($dataToImport[$headerColumns['autogenerated_coupon_codes']]));
 if ($ruleModel->getData('use_auto_generation') && !empty($autogeneratedCouponCodes)) {
 $coupon = Mage::getModel('salesrule/coupon');
 $now = Mage::getModel('core/date')->date('Y-m-d H:i:s');
 foreach ($autogeneratedCouponCodes as $autogeneratedCouponCode) {
 $expirationDate = $autogeneratedCouponCode['expiration_date'];
 if ($expirationDate instanceof Zend_Date) {
 $expirationDate = $expirationDate->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
 }

 $coupon->setId(null)
 ->setRuleId($ruleModel->getRuleId())
 ->setUsageLimit($autogeneratedCouponCode['usage_limit'])
 ->setUsagePerCustomer($autogeneratedCouponCode['usage_per_customer'])
 ->setExpirationDate($expirationDate)
 ->setTimesUsed($autogeneratedCouponCode['times_used'])
 ->setIsPrimary($autogeneratedCouponCode['is_primary'])
 ->setCreatedAt($now)
 //->setType(Mage_SalesRule_Helper_Coupon::COUPON_TYPE_SPECIFIC_AUTOGENERATED)
 ->setType($autogeneratedCouponCode['type'])
 ->setCode($autogeneratedCouponCode['code'])
 ->save();
 }
 }
 /*echo "UPDATE `salesrule` SET `rule_id` = '".$dataToImport[$headerColumns['rule_id']]."'
 WHERE `salesrule`.`rule_id` = '".$ruleModel->getRuleId()."';";*/
 /*$writeAdapter->query("UPDATE `salesrule` SET `rule_id` = '".$dataToImport[$headerColumns['rule_id']]."'
 WHERE `salesrule`.`rule_id` = '".$ruleModel->getRuleId()."';");*/
 //$ruleModel->setId($dataToImport[$headerColumns['rule_id']])->save();
 Mage::log('===rule_id======'.$ruleModel->getRuleId().'=====rule name===='.$dataToImport[$headerColumns['name']]);
 $ruleModel->unsetData();
 $importCount++;
 }
 }
 }

} catch (Exception $e) {
 Mage::printException($e);
}
echo "Saved $importCount customers to csv file n";


function filterDates($array, $dateFields)
{
 if (empty($dateFields)) {
 return $array;
 }
 $filterInput = new Zend_Filter_LocalizedToNormalized(array(
 'date_format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)
 ));
 $filterInternal = new Zend_Filter_NormalizedToLocalized(array(
 'date_format' => Varien_Date::DATE_INTERNAL_FORMAT
 ));

 foreach ($dateFields as $dateField) {
 if (array_key_exists($dateField, $array) && !empty($dateField)) {
 $array[$dateField] = $filterInput->filter($array[$dateField]);
 $array[$dateField] = $filterInternal->filter($array[$dateField]);
 }
 }
 return $array;
}

?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s