Export Dataflow with Product ID in magento - magento

I am using dataflow profile however this does not allow to export entity_id or product ID from magento. This is needed by us to integrate some remarketing code where I can't use SKU. Is there anyway to export entity_id with the dataflow profile.
Second I have to run the dataflow profile every 24 hours.
Regards,
Farrukh Khan

You can take the help from following url to export product id
http://www.vuleticd.com/2013/01/27/export-product-ids-with-magento-dataflow-advanced-profiles/
To run the dataflow profile you have to configure a script to run every 24 hrs.
Use the following code and you have to only change the profileId & csv file name.
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();
$profileId = 7; //put your profile id here
$filename = "cronimport.csv"; //file needs to be present in var/import directory
if (!isset($filename)) {
die("No file has been set!");
}
$logFileName= $filename.'_'.date('m_d_Y h_i_s_a', time()).'.log';
$recordCount = 0;
Mage::log("Import Started",null,$logFileName);
$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(1);
Mage::getSingleton('admin/session')->setUser($userModel);
if ($profileId) {
$profile->load($profileId);
if (!$profile->getId()) {
Mage::getSingleton('adminhtml/session')->addError('The profile you are trying to save no longer exists');
}
}
Mage::register('current_convert_profile', $profile);
$profile->run();
$batchModel = Mage::getSingleton('dataflow/batch');
if ($batchModel->getId())
{
if ($batchModel->getAdapter())
{
//#mail('EMAIL_ADDRESS','Cron started','Test','');
$batchId = $batchModel->getId();
$batchImportModel = $batchModel->getBatchImportModel();
$importIds = $batchImportModel->getIdCollection();
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
$adapter = Mage::getModel($batchModel->getAdapter());
foreach ($importIds as $importId) {
$recordCount++;
try{
$batchImportModel->load($importId);
if (!$batchImportModel->getId()) {
$errors[] = Mage::helper('dataflow')->__('Skip undefined row');
continue;
}
$importData = $batchImportModel->getBatchData();
try {
$adapter->saveRow($importData);
} catch (Exception $e) {
Mage::log($e->getMessage(),null,$logFileName);
continue;
}
if ($recordCount%20 == 0) {
//Mage::log($recordCount . ' - Completed!!',null,$logFileName);
}
} catch(Exception $ex) {
Mage::log('Record# ' . $recordCount . ' - SKU = ' . $importData['sku']. ' - Error - ' . $ex->getMessage(),null,$logFileName);
}
}
foreach ($profile->getExceptions() as $e) {
Mage::log($e->getMessage(),null,$logFileName);
}
}
}
echo 'Import Completed';
Mage::log("Import Completed",null,$logFileName);
//#mail('YOUR EMAIL','Cron Ended','Test','');
?>

Related

Unink log files that were created the day before in codeigniter

I am trying to unlink files that were created the day before
I have a custom application > core > MY_Log.php file and it creates a log for each error level. For easier reading.
logs > DEBUG-04-08-2016.php
logs > ERROR-04-08-2016.php
logs > INFO-04-08-2016.php
logs > DEBUG-03-08-2016.php
logs > ERROR-03-08-2016.php
logs > INFO-03-08-2016.php
Question how am I able to modify the write_log so could delete / unlink files that were created the day before?
<?php
class MY_Log extends CI_Log {
public function write_log($level, $msg)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
&& ! isset($this->_threshold_array[$this->_levels[$level]]))
{
return FALSE;
}
$filepath = $this->_log_path . $level .'-'. date('d-m-Y').'.'.$this->_file_ext;
$message = '';
if ( ! file_exists($filepath))
{
$newfile = TRUE;
// Only add protection to php files
if ($this->_file_ext === 'php')
{
$message .= "";
}
}
if ( ! $fp = #fopen($filepath, 'ab'))
{
return FALSE;
}
flock($fp, LOCK_EX);
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->_date_fmt, 'u') !== FALSE)
{
$microtime_full = microtime(TRUE);
$microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short, $microtime_full));
$date = $date->format($this->_date_fmt);
}
else
{
$date = date($this->_date_fmt);
}
$message .= $this->_format_line($level, $date, $msg);
for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($message, $written))) === FALSE)
{
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === TRUE)
{
chmod($filepath, $this->_file_permissions);
}
return is_int($result);
}
}
First of use
$config['log_threshold'] = 1;
For only error message, so there will be less number of files
Add below code just before $filepath; to delete previous date logs
$unlink_date = date('Y-m-d',strtotime("-1 days"));
$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext;
if ( file_exists($filepath_unlink))
{
unlink($filepath_unlink);
}

how to change csv filename variable in profile action xml of Dataflow-Advanced profile on run time?

I want to use Dataflow-Advanced profile to import the csv from frontend. i have googled and find a stand-alone script for that, but problem is that now this script work only for fixed csv file. I want to change the csv file name on run time to import through stand-alone script. Please refer screen-shot link https://www.diigo.com/item/image/5hhy6/7pxw?size=o to more clear. Could anyone help me to get achieve this?
Here is sample script:
require_once 'app/Mage.php';
umask(0);
ini_set("memory_limit","1024M");
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML,
Mage_Core_Model_App_Area::PART_TRANSLATE);
setlocale(LC_ALL, 'en_US');
$localeName = "en_US";
Mage::app()->getLocale()->setDefaultLocale($localeName);
Mage::app()->getLocale()->setLocale($localeName);
Mage::app()->getLocale()->setLocaleCode($localeName);
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode());
Mage::app()->setCurrentStore(0);
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_TRANSLATE);
Mage::app();
$profileId = 11; //put your profile id here
$logFileName= date("j-n-Y")."-import.log";
$recordCount = 0;
Mage::log("Import Started",null,$logFileName);
$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
Mage::getSingleton('admin/session')->setUser($userModel);
if ($profileId) {
$profile->load($profileId);
if (!$profile->getId()) {
Mage::getSingleton('adminhtml/session')->addError('The profile you are trying to save no longer exists');
}
}
Mage::register('current_convert_profile', $profile);
$profile->run();
$batchModel = Mage::getSingleton('dataflow/batch');
if ($batchModel->getId()) {
if ($batchModel->getAdapter()) {
$batchId = $batchModel->getId();
$batchImportModel = $batchModel->getBatchImportModel();
$importIds = $batchImportModel->getIdCollection();
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
$adapter = Mage::getModel($batchModel->getAdapter());
$adapter->setBatchParams($batchModel->getParams());
foreach ($importIds as $importId) {
$recordCount++;
try{
$batchImportModel->load($importId);
if (!$batchImportModel->getId()) {
$errors[] = Mage::helper('dataflow')->__('Skip undefined row');
continue;
}
$importData = $batchImportModel->getBatchData();
try {
$adapter->saveRow($importData);
} catch (Exception $e) {
Mage::log($e->getMessage(),null,$logFileName);
continue;
}
if ($recordCount%20 == 0) {
Mage::log($recordCount . ' - Completed!!',null,$logFileName);
}
} catch(Exception $ex) {
Mage::log('Record# ' . $recordCount . ' - Error - ' . $ex->getMessage(),null,$logFileName);
}
}
foreach ($profile->getExceptions() as $e) {
Mage::log($e->getMessage(),null,$logFileName);
}
}
}
Mage::log("Import Completed",null,$logFileName);
Looking forward for positive response!
Thanks in advance!
I got the solution.
require_once 'app/Mage.php';
umask(0);
ini_set("memory_limit","1024M");
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML,
Mage_Core_Model_App_Area::PART_TRANSLATE);
setlocale(LC_ALL, 'en_US');
$localeName = "en_US";
Mage::app()->getLocale()->setDefaultLocale($localeName);
Mage::app()->getLocale()->setLocale($localeName);
Mage::app()->getLocale()->setLocaleCode($localeName);
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode());
Mage::app()->setCurrentStore(0);
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_TRANSLATE);
Mage::app();
$profileId = 11; //put your profile id here
$logFileName= date("j-n-Y")."-import.log";
$recordCount = 0;
Mage::log("Import Started",null,$logFileName);
$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
Mage::getSingleton('admin/session')->setUser($userModel);
if ($profileId) {
$profile->load($profileId);
if (!$profile->getId()) {
Mage::getSingleton('adminhtml/session')->addError('The profile you are trying to save no longer exists');
}
//code to change the csv file name :: START
//echo "<pre>"; print_r($profile->getData('actions_xml')); echo "</pre>";
$str = $profile->getData('actions_xml');
$newCsv = 'import_products_new.csv'; // put your logic to get new file name as per your requirement
$new_action_xml = str_replace('import_products_old.csv', $newCsv, $str); //'import_products_old.csv' using static, as we know filename in already saved profile
$profile->setActionsXml($new_action_xml);
//code to change the csv file name :: END
}
Mage::register('current_convert_profile', $profile);
$profile->run();
$batchModel = Mage::getSingleton('dataflow/batch');
if ($batchModel->getId()) {
if ($batchModel->getAdapter()) {
$batchId = $batchModel->getId();
$batchImportModel = $batchModel->getBatchImportModel();
$importIds = $batchImportModel->getIdCollection();
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
$adapter = Mage::getModel($batchModel->getAdapter());
$adapter->setBatchParams($batchModel->getParams());
foreach ($importIds as $importId) {
$recordCount++;
try{
$batchImportModel->load($importId);
if (!$batchImportModel->getId()) {
$errors[] = Mage::helper('dataflow')->__('Skip undefined row');
continue;
}
$importData = $batchImportModel->getBatchData();
try {
$adapter->saveRow($importData);
} catch (Exception $e) {
Mage::log($e->getMessage(),null,$logFileName);
continue;
}
if ($recordCount%20 == 0) {
Mage::log($recordCount . ' - Completed!!',null,$logFileName);
}
} catch(Exception $ex) {
Mage::log('Record# ' . $recordCount . ' - Error - ' . $ex->getMessage(),null,$logFileName);
}
}
foreach ($profile->getExceptions() as $e) {
Mage::log($e->getMessage(),null,$logFileName);
}
}
}
Mage::log("Import Completed",null,$logFileName);
Hope this helps someone!
Thanks!

Magento : Original Price is Zero in Sales Order View from programatic order

I am generating orders from a custom web service called from a mobile app. However when the order is finally generated, I get "Original Price" as Rs0.00 . This is creating a problem since we have third party integrations for invoicing and Shipping.
However in the normal course of action when order is generated from website, the Original Price is correct.
I inspected the sales_flat_order_item table for both these orders, the original_price is indeed 0.00 in the first order, Hence I must be missing something in my code which is not setting the original_price for the orderItem.
Here is the code where the quote is converted to order.
public function placeorder($custid, $Jproduct, $store, $address, $couponCode, $is_create_quote, $transid, $payment_code, $shipping_code, $currency, $message)
{
$res = array();
$quantity_error = array();
try {
$quote_data = $this->prepareQuote($custid, $Jproduct, $store, $address, $shipping_code, $couponCode, $currency, 1, 0);
if ($quote_data["status"] == "error") {
return $quote_data;
}
$quote = Mage::getModel('sales/quote')->load($quote_data['quote_id']);
$quote = $this->setQuoteGiftMessage($quote, $message, $custid);
$quote = $this->setQuotePayment($quote, $payment_code, $transid);
$convertQuote = Mage::getSingleton('sales/convert_quote');
try {
$order = $convertQuote->addressToOrder($quote->getShippingAddress());
}
catch (Exception $Exc) {
echo $Exc->getMessage();
}
$items = $quote->getAllItems();
foreach ($items as $item) {
$orderItem = $convertQuote->itemToOrderItem($item);
$order->addItem($orderItem);
}
try {
$decode_address = json_decode(base64_decode($address));
$order->setCustomer_email($decode_address->billing->email);
$order->setCustomerFirstname($decode_address->billing->firstname)->setCustomerLastname($decode_address->billing->lastname);
}
catch (Exception $e) {
}
$order->setBillingAddress($convertQuote->addressToOrderAddress($quote->getBillingAddress()));
$order->setShippingAddress($convertQuote->addressToOrderAddress($quote->getShippingAddress()));
$order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
$order->save();
$quantity_error = $this->updateQuantityAfterOrder($Jproduct);
$res["status"] = 1;
$res["id"] = $order->getId();
$res["orderid"] = $order->getIncrementId();
$res["transid"] = $order->getPayment()->getTransactionId();
$res["shipping_method"] = $shipping_code;
$res["payment_method"] = $payment_code;
$res["quantity_error"] = $quantity_error;
$order->addStatusHistoryComment("Order was placed using Mobile App")->setIsVisibleOnFront(false)->setIsCustomerNotified(false);
if ($res["orderid"] > 0 && ($payment_code == "cashondelivery" || $payment_code == "banktransfer" || $payment_code == "free")) {
$this->ws_sendorderemail($res["orderid"]);
$order->setState(Mage_Sales_Model_Order::STATE_NEW, true)->save();
$res["order_status"] = "PENDING_PAYMENT";
} else {
$order->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
$res["order_status"] = "PENDING_PAYMENT";
}
}catch (Exception $except) {
$res["status"] = 0;
$res["shipping_method"] = $shipping_code;
$res["payment_method"] = $payment_code;
}
return $res;
}
It would be very helpful if someone points out what I missed. I will edit if any other info is required.
Missing original_price indicates that you didn't run collectTotals() on the quote yet, try the following:
$quote->collectTotals()->save();
$order->save();

Programatically create shipment (for selected items/qty on order) in magento

I have an order that looks like this:
I want to create a shipment for the following on this order (not for everything):
2 x VCF001
1 x SBA364
To achieve this, I found the following info on the shipment api: http://bit.ly/17rpuwj
Based on this documentation of the API, I came up with the following code. When I tried to execute it, I got the following error Cannot create an empty shipment:
$order_number = '300000002';
$order = Mage::getModel('sales/order')->loadByIncrementId($order_number);
$allocations = array(
array('sku' => 'VCF001', 'allocated_qty' => 2),
array('sku' => 'SBA364', 'allocated_qty' => 1)
);
function GetOrderItemId($order_items, $sku) {
foreach ($order_items as $order_item) {
if ($order_item->getSku() == $sku) {
return $order_item->getItemId();
}
}
return 0;
}
function CreateShipment($order, $allocations)
{
// Get Order Items
$order_items = $order->getItemsCollection();
// Parepare Item Qtys For Shipment
$item_qtys = array();
foreach ($allocations as $allocation) {
$item_qtys[] = array(GetOrderItemId($order_items,
$allocation['sku']) => $allocation['allocated_qty']);
}
// Anticipate Errors
try
{
// Create Shipment
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment->create($order->getIncrementId(),
$item_qtys, 'Pick #123 Sent to Warehouse');
// Done
echo 'Shipment Created - ID #'. $shipmentId;
}
catch (Exception $e)
{
print_r($e);
}
}
CreateShipment($order, $allocations);
Any idea why this isn't working as intended? See the full exception log here : http://pastebin.com/raw.php?i=GMN4WCAE
Try it like this instead :
protected function _createShipment($order, $qtysForProducts)
{
$shipment = $order->prepareShipment($qtysForProducts);
if ($shipment) {
$shipment->register();
$shipment->sendEmail(true)
->setEmailSent(true)
->save();
$order->setIsInProcess(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
}
return $shipment;
}

Magento Core discount

I've been struggling with this for a while, should be pretty straight forward but...
I'm trying to apply coupon to order using magento cart.coupon.add api.
The product is Virtual
here is my code ( and I've tried everything i could find on google before I came here ):
protected function _applyCoupon($quoteId, $couponCode, $store = null)
{
$coupon = Mage::getModel('salesrule/coupon');
$coupon->loadByCode($couponCode);
Mage::log('_applyCoupon('.$couponCode.')');
$quote = $this->_getQuote($quoteId, $store);
if (!$quote->getItemsCount()) {
// $this->_fault('quote_is_empty');
}
$oldCouponCode = $quote->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
return false;
}
try {
//$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->setCouponCode($couponCode);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$quote->collectTotals();
$quote->save();
Mage::getModel("checkout/session")->setData("coupon_code",$couponCode);
Mage::getModel('checkout/cart')->getQuote()->setCouponCode($couponCode)->save();
Mage::getModel('checkout/cart')->getQuote()->collectTotals();
Mage::getModel('checkout/cart')->getQuote()->save();
Mage::log("_applyCoupon : Set coupon to quote:".$quote->getCouponCode());
} catch (Exception $e) {
$this->_fault("cannot_apply_coupon_code", $e->getMessage());
}
Mage::log('3');
if ($couponCode) {
Mage::log("Coupon applied");
if (!$couponCode == $quote->getCouponCode()) {
Mage::log('3.2');
$this->_fault('coupon_code_is_not_valid');
}
}
return true;
}
I've also tried applying coupon to address:
protected function applyDiscountToAddress($address,$quote)
{
Mage::log('applyDiscountToProduct ...');
$coupon = Mage::getModel('salesrule/coupon');
Mage::log("checkoutprocess: checkout/session:".Mage::getModel("checkout/session")->getData("coupon_code"));
$coupon->loadByCode(Mage::getModel("checkout/session")->getData("coupon_code"));
$rule = Mage::getModel('salesrule/rule');
$rule->load($coupon->getRuleId());
$discountamount = $rule->getDiscountAmount();
$dbldiscount = 0.00 + $discountamount;
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
Mage::log('applyDiscountToProduct $grandTotal:'.$grandTotal);
Mage::log('applyDiscountToProduct $subTotal:'.$subTotal);
$gTotal = $grandTotal - $dbldiscount;
$address->setDiscountAmount($dbldiscount)
->setBaseDiscountAmount($dbldiscount)
->setGrandTotal($gTotal)
->setBaseGrandTotal($gTotal);
$grandTotal = $address->getGrandTotal();
$baseGrandTotal = $address->getBaseGrandTotal();
Mage::log('applyDiscountToProduct Address:$grandTotal:'.$grandTotal);
Mage::log('applyDiscountToProduct Address:$baseGrandTotal:'.$baseGrandTotal);
$totals = array_sum($address->getAllTotalAmounts());
$baseTotals = array_sum($address->getAllBaseTotalAmounts());
$address->setGrandTotal($grandTotal+$totals);
$address->setBaseGrandTotal($baseGrandTotal+$baseTotals);
}
the coupon is valid but after the order being placed in the Magento admin I see that the discount amount = 0.0 and the user was charged full amount to his credit card.
Anyone....? Help...?
Finally found an answer
I needed to call setCouponCode() before adding any items to quote.
$quote= Mage::getModel('sales/quote')->setCouponCode($couponCode);

Resources