I'm new to Magento and have some difficulties with writing mdoule that will allow me to export (send to remote API) data from my magento store.
Currently what I have is created observer for "sales_order_save_after" event and what I want do in my observer is to get Order data, make them xml and send to some remote url.
Can anyone help with that? I'm using magento 1.8
you can get data in observer like below function
public function orderExportTxt(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
print_r($order->getData()); // your user detail.
}
EDIT
To get Product detail from order
<?php $order_id = 2314; //use your own order id
$order = Mage::getModel("sales/order")->load($order_id);
//load order by order id
$ordered_items = $order->getAllItems();
foreach($ordered_items as $item){
//item detail
echo $item->getItemId(); //product id
echo $item->getSku();
echo $item->getQtyOrdered(); //ordered qty of item
echo $item->getName(); // etc.
} ?>
its depends on your xml format for your third party service in which format it accept your order to be in saved.
below is just example to create xml file.
http://www.php.net//manual/en/domdocument.savexml.php
hope this will sure help you.
Let me know if i could help further.
Related
I'm building an extension that exports completed order information into a CSV file. I've been able to successfully access order and item information for the export but I'm having a problem accessing promotion data.
I'm looking to include the promotion data (catalog and cart rules) that are applied to that order in the export. Specifically I am trying to access the rule ids, names, descriptions, codes and applied dollar amount for a list of specific orders.
How would I access the promotion data in my extension?
If it helps, here is how I am currently accessing order/item data in my extension (qualifying by date frame):
$rows = array(); // array to hold data that will be exported to CSV
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$orders = $read->query("SELECT entity_id FROM sales_flat_order WHERE created_at >= '$from' AND created_at < '$today'");
while ($row = $orders->fetch()) {
$order = Mage::getModel('sales/order')->load($row['entity_id']);
$order_items = $read->query("SELECT item_id FROM sales_flat_order_item WHERE order_id={$order->getId()}");
while ($item_row = $order_items->fetch()) {
$item = Mage::getModel('sales/order_item')->load($item_row['item_id']);
$rows[] = array(
$order->getRealOrderId(),
$order->getCreatedAt(),
$item->getSky(),
$item->getQtyOrdered(),
..... );
); // end item loop
); // end order loop
Thanks in advance for any help you can provide,
-Mark
I believe this question has been answered on another question in the past. You can find the link to the original question and answer here Magento - get price rules from order
From that answer though..
//The order I want to check
$order_id = 859;
//Get the list of items for your order
$items = Mage::getModel('sales/order_item')
->getCollection()
->addFilter('order_id',array('eq'=>$order_id));
//loop through each item
foreach($items as $item){
//if the item has not had a rule applied to it skip it
if($item->getAppliedRuleIds() == '')continue;
/*
* I cant remember in the database they might be comma separated or space if multiple rules were applied
* the getAppliedRuleIds() function is the one you want
*/
foreach(explode(",",$item->getAppliedRuleIds()) as $ruleID){
//Load the rule object
$rule = Mage::getModel('catalogrule/rule')->load($ruleID);
// Throw out some information like the rule name what product it was applied to
echo "<p>".$item->getSku()." had rule ".$rule->getName()."(".$item->getAppliedRuleIds().") applied </p>";
}
}
i am using Magento 1.9.0.1 and i am developing a custom extension.
Right now i am stuck at the following thing.
Like this i use to get the customers name from an order:
$CustomerName = $observer->getOrder()->getBillingAddress()->getName();
I have custom customer attribute called sms_on_order_change and i am trying to get the value of it like that:
$SMSOnStatusChange = $observer->getResource()->getAttribute('sms_on_order_change')->getFrontend()->getValue();
But it is not working.
Here is the extension that i am using for the creation of custom customer attributes: http://www.magentocommerce.com/magento-connect/manage-customer-attributes.html
So guys, can you help me out so i can get the value of this custom attribute ?
Thanks in advance!
This should help you out:
//get order from observer
$order = $observer->getOrder();
// get customer id from order
$customer_id = $order->getCustomerId();
// condition only necessary if guest orders are allowed
if ($customer_id)
{
$_customer = Mage::getModel('customer/customer')->load($customer_id);
$sms_on_order_change = $_customer->getData('sms_on_order_change');
}
I've set an observer for sales_quote_add_item in order to clear the cart whenever a certain product is going to be added (it's only supposed to be ordered alone).
I'm just not sure on how to get the product ID of the product that is about to get added. With some trial & error I've come up with this:
$tmp = $observer->getEvent()->getQuoteItem()->getData();
echo $tmp['product_id'];
Which seems to be quite an ugly solution. I'm sure there is some shortcut or proper function to call for this, any ideas?
Your solution is good enough
$productId = $observer->getEvent()->getQuoteItem()->getProductId();
You may load product after if is needed
$product = Mage::getModel('catalog/product')->load($productId);
Use the following code to get product id of quote item data
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item)
{
$productId = $item->getProduct()->getId();
}
Hope this helps to you.
does anyone have an idea on how I could send newsletter emails to customers based on the category that they ordered from? So for instance, i would like to send a monthly email to customers who purchased exam gloves to restock their supply.
Here is one way to go about it:
1) get all of the (recent) orders
$orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('created_at', '2012-04-16 15:56:33');
Note: replace '2012-04-16 15:56:33' with correct date and timestamp.
2) Get the product's ordered
foreach($orders as $order):
// let's get some the order info
$orderData = $order->getData();
// extract the order ID from the order objecj (so we can load the whole order)
$orderId = $orderData['entity_id'];
// extract the customer's ID (so that we can find out customer's email)
$customerId = $orderData['customer_id'];
// load the customer by ID
$customer = Mage::getModel('customer/address')->load($customerId)->getData();
// get customer's email address
$customerEmail = $customer['email'];
// load the full order (so that we can get a list of product's ordered
$fullOrder = Mage::getModel('sales/order')->load($orderId);
// extract the products from the order
$products = $fullOrder->getAllItems();
endforeach;
3) Find out what category the product comes from
foreach ($products as $product):
// let's get an object with the ordered product's data
$productInfo = $product->getData();
// extract the product ID (so that we can load the product)
$prodId = $productInfo['item_id'];
// load the product
$product = Mage::getModel('catalog/product')->load($prodId);
// get all (names of) categories that this product is associated with
$categories = $product->getCategoryCollection()->addAttributeToSelect('name');
endforeach;
4) Send out a specific template to those customers (see code in first answer of this question) Sending e-mail programmatically in Magento is failing
Hope this was helpful
does anyone know how one can get the catalog- and cart price rules from an order?
I know that I can get the discount percentage from an order item via the method getDiscountPercent(), but how can I get all the rules that were applied to the whole order?
For example, I have a rule "Customer Group X gets 20% off all items in the store".
Now I want to determine which rules were actually applied when the order has been submitted by the user. I need this for an order export interface where I have to supply all discounts that the user got.
Thanks in advance!
Have a look in the sales_flat_order_item table. there is a field called applied_rule_ids which will give you the id of the rule applied to that item. Also you can find out in this table how much discount was applied and the percentage.
Example
//The order I want to check
$order_id = 859;
//Get the list of items for your order
$items = Mage::getModel('sales/order_item')
->getCollection()
->addFilter('order_id',array('eq'=>$order_id));
//loop through each item
foreach($items as $item){
//if the item has not had a rule applied to it skip it
if($item->getAppliedRuleIds() == '')continue;
/*
* I cant remember in the database they might be comma separated or space if multiple rules were applied
* the getAppliedRuleIds() function is the one you want
*/
foreach(explode(",",$item->getAppliedRuleIds()) as $ruleID){
//Load the rule object
$rule = Mage::getModel('catalogrule/rule')->load($ruleID);
// Throw out some information like the rule name what product it was applied to
echo "<p>".$item->getSku()." had rule ".$rule->getName()."(".$item->getAppliedRuleIds().") applied </p>";
}
}
/* Example of getting catalog rules applied for specific product */
$productId = 6;
$user = Mage::getSingleton('customer/session')->getCustomer();
$product = Mage::getModel('catalog/product')->load($productId);
$storeId = $product->getStoreId();
$websiteId = Mage::app()->getStore($storeId)->getWebsiteId();
$dateTs = Mage::app()->getLocale()->storeTimeStamp($storeId);
$customerGroupId = $user->getGroupId();
$resource = Mage::getResourceModel('catalogrule/rule');
$rules = $resource->getRulesFromProduct($dateTs, $websiteId, $customerGroupId, $productId);
Yeah, it's kind of a pain that Magento doesn't leave any history around in the order record when you use sale pricing with regard to how that base price was calculated.
Fortunately it's open source, so you can patch this in if you like.
I recently wrote an observer that fires when the order record is loaded, to address this very issue. It cross-references the line base_price with the product's current full-retail price. If there is a mismatch, it adds a couple fields to the order item to help expose this info to any external script that's listening (in our case, a custom order fulfillment script that relays orders to SAP using Magento's SOAP API).
Here's the basic idea - make a module in app/code/local/YourCo/SalePricing
and set up an observer class in app/code/local/YourCo/SalePricing/Model/Promo/Observer.php
<?php
class YourCo_SalePricing_Model_Promo_Observer
{
public function __construct()
{
}
// tag order items that have a sale-price
// with original retail price and total sale discount for this line
public function report_sale_pricing($observer)
{
$event = $observer->getEvent();
$order = $event->getOrder();
$items = $order->getAllItems();
foreach ($items as $item) {
// heads up, you may want to do this for other types as well...
if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
$regular_price = $this->_lookupFullRetail($item,$order->getStoreId());
$sale_price = $item->getBasePrice();
if ($regular_price - $sale_price > 0.005) {
$qty = $item->getQtyOrdered();
$total_sale_discount = ($regular_price * $qty) - ($sale_price * $qty);
$item->setFullRetailPrice((string)$regular_price);
$item->setSaleDiscount((string)$total_sale_discount);
}
}
}
}
private function _lookupFullRetail(&$item,$store_id)
{
$mpid = $item->getProductId();
$p = Mage::getModel('catalog/product')->setStoreId($store_id)->load($mpid);
return $p->getPrice();
}
}
Your module's etc/config.xml needs to tell magento when to run your observer:
<?xml version="1.0"?>
<config>
<global>
<models>
<yourco_salepricing>
<class>YourCo_SalePricing_Model</class>
</yourco_salepricing>
</models>
<events>
<sales_order_load_after>
<observers>
<yourco_salepricing>
<type>singleton</type>
<class>YourCo_SalePricing_Model_Promo_Observer</class>
<method>report_sale_pricing</method>
</yourco_salepricing>
</observers>
</sales_order_load_after>
</events>
</global>
</config>
Make sure to activate your new module in app/etc/modules/... and clear the config cache.
Now, when you load the order, you can loop over each item and check for $item->getFullRetailPrice() -- if it's there, you know the item was on sale (well, either that or the price has gone up since the order was placed). You still don't know why, ie which sale price rule was in force, but for our application we didn't really care, and getting that info to be saved with the order would have been a much tougher mod.
What might help you though:
$order = Mage::getModel('sales/order')->load(20569);
echo Mage::helper('sales')->__('Discount (%s)', $order->getDiscountDescription());
This prints out all the discount rules name which have been applied to the order.