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>";
}
}
Related
I'm more or less a total newbie to php. My goal is to get the names of items from the logged in user's cart and dynamically populate a GravityForms template with the information. I've successfully managed to do that with the code below, but there are three things that I'm failing to do. 1: I only want to populate the form with all items of a certain variation. 2: the echo function will list all of the item names, but not inside the relevant field, and the return function will populate the field, but only with the first item name. 3: I'd like to have the output items listed with some form of separator in between each item name. Here's what I have so far:
<?php
add_filter( 'gform_field_value_beat_names', 'beat_names_function' );
function beat_names_function( $value ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach ($items as $item) {
$product_variation_id = $item['variation_id'];
$license_id = new WC_Product($product_variation_id);
$license_string = $license_id->get_formatted_name();
$beat_id = $item['data']->post;
$beat_name = $beat_id->post_title;
if (strpos($license_string, 'basic') !== false) {
echo $beat_name;
}
}
}?>
As you can see, I'm attempting to use strpos to isolate the particular item variation I want to target, using a certain word found in the name of the variation option, being "basic". I'm sure there's a more secure way of doing that, but it works for now. The problem lies with the return function I set up inside the conditional strpos statement, being that it will still just return the entire list of cart items, as opposed to only the items that I'm trying to isolate with the strpos conditional.
The ultimate goal is to create a license agreement that is dynamically populated with the relevant information, including the names of the items being licensed. The item variations are different license options that I have available for the products in my store. The purpose of the above code is to filter cart items by license type so that the wrong item names don't get listed on the wrong license agreement at checkout.
Any tips would be appreciated
Figured it out after some more tinkering. I broke it down step by step to help anyone as clueless as I am
add_filter( 'gform_field_value_basic_beat_names', 'basic_beat_names_function' );
function basic_beat_names_function( $value ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
// the item names you want will be stored in this array
$license_check = array();
// Loop through cart items
foreach ($items as $item) {
// get the id number of each product variation in the cart. this won't work for "simple" products
$product_variation_id = $item['variation_id'];
// translate that id number into a string containing the name of the product, and the options applied to the product
$license_id = new WC_Product($product_variation_id);
$license_string = $license_id->get_formatted_name();
// check to see if the word "basic" is found anywhere in that string. "basic" is contained in the name of the product option being targeted
if (strpos($license_string, 'basic') !== false) {
// if the above condition is met, fetch the name of any products in the cart that have that option applied. The product name will be fetched from the title of the product's page
$beat_id = $item['data']->post;
$beat_name = $beat_id->post_title;
// store the retrieved product names in the $license_check array
$license_check [] = $beat_name;
}
}
// pull the stored product names from the $license_check array, and format them using implode and concatenation, then return the final result to the form field
return "\"" . implode("\", \"", $license_check) . "\"";
}
As a warning, the strpos method is a little hacky. It'll only work properly if your string is specific enough to target ONLY the option you're looking for.
As an example, here's the format for the product variation string being fed into the strpos function:
item-name-option-one-name-option-two-name – variation #xxx of item page title
So, if you want to filter items ONLY by option one, your safest bet would be to write the strpos function like so:
if (strpos($license_string, 'option-one-name') !== false) {
//do something
}
When all is said and done, the final result should look like: "item1", "item2", "item3", etc.
Then, to do the same with any other option, and output the result in a different field, or separate form altogether, I'll just duplicate this code, and replace any mention of the word "basic" with some different unique string contained in the other option. Don't forget to configure the gravity forms field as necessary too.
How would I get a list of all orders in Magento that have a certain product on the order?
I have built an extension and need to know all orders which contain a certain product.
This is not a duplicate question per se, so here a solution that might work for you:
$productId = {PRODUCT_ID};
$orders = array();
$collection = Mage::getResourceModel('sales/order_item_collection')
->addAttributeToFilter('product_id', array('eq' => $productId))
->load();
foreach($collection as $orderItem) {
$orders[$orderItem->getOrder()->getIncrementId()] = $orderItem->getOrder();
}
You'll end up with an array of orders which contain an orderitem for the given {PRODUCT_ID}.
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
I want to retrieve all product IDs that has a specific (custom) option value (provided by the customer in the frontend) from all orders - regardless of store/website.
The option is a text field (Mage_Catalog_Model_Product_Option_Type_Text), the SKU (and title) is test_option and the value I'm looking for is green.
I would prefer to do this with a raw MySQL query, but a solution using Magentos models/collections would definitely suffice.
try with below code
<?php $collection = Mage::getResourceModel('sales/order_collection');
$productIds = array();
foreach($collection as $order) {
$order = Mage::getModel('sales/order')->load($order->getId());
$items = $order->getAllItems();
foreach ($items as $item){
$proOptions = $item->getProductOptions();
if($proOptions['options']){
$productIds[] = $item->getProductId();
}
}
}
?>
$productIds variable returns all product ids which has a specific (custom) option value.
May it helps you !
For direct sql query you can try this. If you want to put some condition, you can add according to your requirement.
SELECT sfoi.product_id FROM sales_flat_order e
LEFT JOIN
sales_flat_order_item sfoi
ON
( e.entity_id = sfoi.order_id )
I want to send a weekly reminder email to customers who have bought something but not paid yet.
Using this script I can show an order:
<?php
//from http://www.exploremagento.com/magento/run-magento-code-outside-of-magento.php
require_once '../app/Mage.php';
umask(0);
Mage::app('default');
$orders = Mage::getModel('sales/order')->getCollection()
->setOrder('increment_id','DESC')
->setPageSize(1)
->setCurPage(1);
$LastOrderNr = $orders->getFirstItem()->getIncrementId() - 100000000;
$LastOrderNr=494;
$order = Mage::getModel('sales/order')->load($LastOrderNr); //put a valid order entity_id there;
print_r($order->debug());
echo "<br/>******************************<br/>";
?>
I can retrieve several useful info-blocks (i.e. customer's email address, total amount) but it won't show the items they have bought. How/where can I retrieve that kind of information?
In Magento ordered products called 'order items'. You can get order items data like this:
`
// 1. get order. you can load it by order entity id (f.e. 494)
$order = Mage::getModel('sales/order')->load($orderId);
// or by order increment id (100000494)
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
// 2. get order items collection
foreach ($order->getItemsCollection() as $item) {
Zend_Debug::dump($item->getData());
}
`
it can be much easier to get the last Order , especialy needed for the success Site
$order = Mage::getModel('sales/order')->load(Mage::getModel('sales/order')->getCollection()->getLastItem()->getEntityId());
Example: Last Order Costs
$grand_total = Mage::getModel('sales/order')->load(Mage::getModel('sales/order')->getCollection()->getLastItem()->getEntityId())->getGrandTotal();