Get Customer Name for Coupon Codes in Magento - php

I have searched on the net and on this site for a solution but couldn't find any.
I would like to get the customer name associated to a coupon code in Magento. I found some code for the times the coupon code was used but I couldn't get the customer name.
I tried the following code:
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app( 'admin' );
$coupon = Mage::getModel('salesrule/coupon/usage');
$coupon->load('dd_38WX9N', 'code');
if($coupon->getId()) {
$timesUsed = $coupon->getTimesUsed();
$customer = $coupon->getCustomerId();
echo $timesUsed;
echo $customer;
}
?>
Could someone please help me with that and point me to the right direction.
Thanks a lot for your help.
Daniel

Here is the good solution. you need to use the resource and not the model to get access to the table salesrule_coupon_usage and get the customer_id list
/*#var $coupon Mage_SalesRule_Model_Coupon */
$coupon = Mage::getModel('salesrule/coupon');
$coupon->load('dd_38WX9N', 'code');
if($coupon->getId()){
/* #var $resourceCouponUsage Mage_SalesRule_Model_Mysql4_Coupon_Usage */
$resourceCouponUsage = Mage::getResourceModel('salesrule/coupon_usage');
$read = $resourceCouponUsage->getReadConnection();
$select = $read->select()
->from($resourceCouponUsage->getMainTable())
->where('coupon_id = ?', $coupon->getId());
$data = $read->fetchAll($select);
print_r($data);
foreach($data as $couponUsage){
$customer = Mage::getModel('customer/customer')->load($couponUsage['customer_id']);
echo $customer->getName();
}
}

When you are able to get the ID of the customer, you also can get the whole customer object:
$customer_data = Mage::getModel('customer/customer')->load($customer_id);
print_r($customer_data);
There you can get the name as well.

Related

Magento Order Creation Programatically only working on one shipping method

I am using the code below as part of a script to create Magento Orders programatically. The script works fine when I use
freeshipping_freeshipping
as the shipping method. However, when I choose any other shipping method such as a custom shipping method,flatrate_flatrate or usps_1 e.t.c, it gives me the error:
"Please Specify a shipping method"
I have searched everywhere but was unable to find a solution. Any help would be highly appreciated, thanks.
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod($shipping_method);
Edit:
I got it to work with flatrate for non US orders and an extension freeadminshipping on both US and non US orders. However, still unable to use any of the UPS or USPS shipping methods.
This method create Order and I have use this in my project it working. In your code please remove shipping method set code and try I hope that work fine for you. otherwise you can use below my code.
public function createOrderAction($paymentMethod) {
try {
$checkout_session = Mage::getSingleton('checkout/session');
$cq = $checkout_session->getQuote();
$cq->assignCustomer(Mage::getSingleton('customer/session')->getCustomer());
$quoteObj = Mage::getModel('sales/quote')->load($checkout_session->getQuoteId()); // Mage_Sales_Model_Quote
//Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
// set payment method
$quotePaymentObj = $quoteObj->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
// convert quote to order
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$quoteObj->setShippingAddress($cq->getShippingAddress());
$quoteObj->setBillingAddress($cq->getBillingAddress());
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
// convert quote addresses
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
// set payment options
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
// convert quote items
foreach ($items as $item) {
// #var $item Mage_Sales_Model_Quote_Item
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$orderItem->setWholesaler($item->getWholesaler());
$orderItem->setComment($item->getComment());
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options) {
$orderItem->setProductOptions($options);
}
if ($item->getParentItem()) {
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$orderObj->setCanShipPartiallyItem(false);
$orderObj->place();
$quoteObj->setIsActive(0)->save();
$orderObj->save();
$orderObj->sendNewOrderEmail();
return $orderObj->getId();
} catch (Exception $e){
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
}
}

Magento getAttribute is not working in list.phtml?

This is magento code that i have used to get attribute.
echo $_product->getResource()->getAttribute('attrcode')->getFrontend()->getValue($_product);
This code is working fine in view.phtml it return to attribute code value.
when i write same code in list.phtml file this code is return blank.
where i do mistake. please help.
<?php echo $_product->getAttributeText('attrcode');?>
please use that code on list page and also check attribute setting in ('Used in Product Listing': "Yes")
Here is the code get attribute name and value that that doesn't belongs to any product
$attributeCode = 'YOUR_ATTRIBUTE_CODE';
$product = Mage::getModel('catalog/product');
$productCollection = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', $attributeCode);
$attribute = $productCollection->getFirstItem()->setEntity($product->getResource());
print_r($attribute->getData()); // print out the available attributes
$options = $attribute->getSource()->getAllOptions(false);
print_r($options);
If you want to display all the values of a specific attribute in Magento 2 phtml file, then use following code
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product','attribute_code');
$values = $attribute->getSource()->getAllOptions();

Magento change shipping rate in one page checkout for COD

My question is quite simple. I need to change the shipping rate cost in one page checkout to "0" once the user select COD as payment method in one page checkout. I think I can do this easely with an observer. Could you please helpme to know what event should I observe?.
Can I use checkout_controller_onepage_save_shipping_method ?. Any kind of help will be highly appreciated!!
Details Posted By OP as answer
I override the Mage_Checkout_Model_Type_Onepage class and modify the savePayment method. Then I did this:
1.- A first try:
public function savePayment($data)
{
.....
....
$payment = $quote->getPayment();
$payment->importData($data);
$quote->save();
//My custom code
if($data['method']=='cashondelivery'){
$shipping = $quote->getShippingAddress();
$address = $quote->getBillingAddress();
$shipping->addData($address)->setShippingMethod('flatrate_flatrate');
}
Where my flatrate_flatrate is 0. Unfortunately it doesn't work well. This snippet set to 0 my Grant Total.
My second try was:
public function savePayment($data)
{
.....
....
$payment = $quote->getPayment();
$payment->importData($data);
$quote->save();
//My custom code
if($data['method']=='cashondelivery'){
$this->getQuote()->getShippingAddress()->setShippingAmount(0);
$this->getQuote()->getShippingAddress()->setBaseShippingAmount(0);
}
This code works but only a few times, I don't understand why ??.. Could somebody helpme to fix this please?. Any kind of help will be highly appreciated.
Kind regards!
Ok. Now I have this and it works but it doesn't update the grand total amount. Even the order is processed with the normal shipping cost. I mean, finally it doesn't update anything. Could somebody in someway give me a hand on this please?.
if($data['method']=='cashondelivery'){
$quote->getShippingAddress()->setShippingMethod('flatrate_flatrate');
$quote->getShippingAddress()->setShippingAmount(0);
$quote->getShippingAddress()->setBaseShippingAmount(0);
$quote->getShippingAddress()->setShippingInclTax(0);
$quote->getShippingAddress()->setBaseShippingInclTax(0);
$quote->collectTotals();
$quote->save();
}
Warming regards!
Ok, I did something crazy but it seems it works (at least partially). I override Mage_Checkout_OnepageController too and add it a new method call actualizaShippingMethodAction.
It looks like this:
public function actualizaShippingMethodAction()
{
if ($this->_expireAjax()) {
return;
}
if ($this->getRequest()->isPost()) {
$data = $this->getRequest()->getPost('shipping_method', '');
$result = $this->getOnepage()->saveShippingMethod($data);
// $result will contain error data if shipping method is empty
if (!$result) {
$this->getOnepage()->getQuote()->collectTotals();
}
$this->getOnepage()->getQuote()->collectTotals()->save();
}
}
Now in my original class that is overriding (Mage_Checkout_Model_Type_Onepage) I did this.
if($data['method']=='cashondelivery'){
$cliente = new Varien_Http_Client();
$_configuracion = array('maxredirects'=>5, 'timeout'=>30);
$llamada = Mage::getBaseUrl()."checkout/onepage/actualizaShippingMethod/";
$cliente->setUri($llamada)
->setConfig($_configuracion)
->setMethod(Zend_Http_Client::POST)
->setParameterPost('shipping_method','flatrate_flatrate');
$respuesta = $cliente->request();
$quote->getShippingAddress()->setShippingAmount(0);
$quote->getShippingAddress()->setBaseShippingAmount(0);
$quote->getShippingAddress()->setShippingInclTax(0);
$quote->getShippingAddress()->setBaseShippingInclTax(0);
$quote->collectTotals()->save();
}
$this->getCheckout()
->setStepData('payment', 'complete', true)
->setStepData('review', 'allow', true);
return array();
Now the order is passing without shipping cost as spected but the order review (summary) is not updating the final costs. And I thinks this solution has a bug because if the user returns and select another payment method the shipping cost is 0 again.
Any kind of help, whatever, will be highly, highly appreciated
THANKS
Finally I have a solution and I think is an answer to the original question. If not please pardon me.
Forget to override savePayment($data) on Mage_Checkout_Model_Type_Onepage. Just focus on overriding Mage_Checkout_OnepageController, and add to the savePaymentAction() method the following code.
$data = $this->getRequest()->getPost('payment', array());
/*Custom code*/
if($data['method']=='cashondelivery'){//Only if payment method is cashondelivery
$result = $this->getOnepage()->savePayment($data);
// get section and redirect data
$redirectUrl = $this->getOnepage()->getQuote()->getPayment()->getCheckoutRedirectUrl();
if (empty($result['error']) && !$redirectUrl) {
$this->loadLayout('checkout_onepage_review');
$result['goto_section'] = 'review';
$result['update_section'] = array(
'name' => 'review',
'html' => $this->_getReviewHtml()
);
}
if ($redirectUrl) {
$result['redirect'] = $redirectUrl;
}
//Update totals for Shipping Methods
$resultado = $this->getOnepage()->saveShippingMethod('flatrate_flatrate');
$this->getOnepage()->getQuote()->collectTotals()->save();
}else{
$result = $this->getOnepage()->savePayment($data);
// get section and redirect data
$redirectUrl = $this->getOnepage()->getQuote()->getPayment()->getCheckoutRedirectUrl();
if (empty($result['error']) && !$redirectUrl) {
$this->loadLayout('checkout_onepage_review');
$result['goto_section'] = 'review';
$result['update_section'] = array(
'name' => 'review',
'html' => $this->_getReviewHtml()
);
}
if ($redirectUrl) {
$result['redirect'] = $redirectUrl;
}
//Return the original values according with the initial user sellection
//I use a session variable to store the original selection
$shippingMethod = Mage::getSingleton('core/session')->getShippingInicial();
$resultado = $this->getOnepage()->saveShippingMethod($shippingMethod);
$this->getOnepage()->getQuote()->collectTotals()->save();
}
} catch (Mage_Payment_Exception $e) {
if ($e->getFields()) {
...
Then you have to override saveShippingMethodAction() and add the following code.
...
$result = $this->getOnepage()->saveShippingMethod($data);
//We store the Shipping Method initial selection
Mage::getSingleton('core/session')->setShippingInicial($data);
// $result will contain error data if shipping method is empty
if (!$result) { ...
If you test this you will find that it works as expected. But now it takes 2 loading times to correctly show the total costs in the review part. I read this question (IWD one page checkout extension Magento: review refresh) but it doesn't help a lot.
Could somebody point me in the right direction to update the review part twice?.
WARMING REGARDS!
Could somebody have an idea how to achieve this?. Regards!

Automatic onepage checkout - quote issue

I'm creating automated checkout feature, which will create few orders at once:
What's wrong with that?
This script let's say creates 4 different orders with different prodcuts, for different users, but problem lies here, each order created after first order has got subtotal and grand total of first order. How can I reset that?
Mage::app('default');
/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');
/**
* Retrieve the read connection
*/
$readConnection = $resource->getConnection('core_read');
$query = 'SELECT * FROM m4gsrepeated_orders WHERE execution <= CURDATE()';
$all_orders = $readConnection->fetchAll($query);
function addCartItems($products_array) {
$cart = Mage::getModel('checkout/cart');
foreach($products_array as $productw) {
$sku = $productw[0];
/** #var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
$productCollection = Mage::getModel( 'catalog/product' )
->getResourceCollection()
->addFieldToFilter( 'sku', $sku );
/** #var $product Mage_Catalog_Model_Product */
$product = $productCollection->getFirstItem();
// you should have the product now, maybe it isn't even necessary to get the ID
$product = $product->load($product->getId());
$cart->addProduct($product, $productw[1]);
}
$cart->save();
}
foreach ($all_orders as $order) {
//Set basic data
Mage::getSingleton('checkout/session')->getQuote()->setReservedOrderId(null);
$customer = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->load($order['user_id']);
// Set as Logged In and Clear Session
Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer)->renewSession();
//Set up cart
$cart = Mage::getModel('checkout/cart')->getQuote();
//get current cart items;s
$i=1;
foreach ($cart->getAllItems() as $item) {
$products_current[$i][0] = $item->getProduct()->getSku();
$products_current[$i][1] = intval($item->getQty());
$i++;
}
$i=1;
$cart = Mage::getModel('checkout/cart');
foreach( Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item ){
$cart->removeItem( $item->getId() );
}
$products_delayed = json_decode($order['items']);
addCartItems($products_delayed);
$cart->save();
//LUUUTA CREATE ORDER
# Get customer default shipping information
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
if ($customerAddressId){
$address = Mage::getModel('customer/address')->load($customerAddressId);
$shippingAddress = $address->getData();
}
# Get customer default billing information
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customerAddressId){
$address = Mage::getModel('customer/address')->load($customerAddressId);
$billingAddress = $address->getData();
}
$quote = Mage::getSingleton('checkout/session')->getQuote();
/*
* One page checkout consists of following steps
* (1) Customer login method aka Checkout method
* (2) Billing information (address)
* (3) Shipping information (address)
* (4) Shipping method
* (5) Payment information
* (6) Order review, in short: DO THE ORDER
*/
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveShippingMethod('excellence_excellence');
$quote->getShippingAddress()->setShippingMethod('excellence_excellence');
$quote->getShippingAddress()->unsGrandTotal(); //clear the values so they won't take part in calculating the totals
$quote->getShippingAddress()->unsBaseGrandTotal();
$quote->getShippingAddress()->setCollectShippingRates(true)->save();
$quote->getShippingAddress()->collectTotals(); //collect totals and ensure the initialization of the shipping methods
$quote->collectTotals();
//STEP(1)
$checkout->saveCheckoutMethod('register');
//STEP(2)
$checkout->saveBilling($billingAddress, false);
//STEP(3)
$checkout->saveShipping($shippingAddress, false);
//STEP(4)
$checkout->saveShippingMethod('excellence_excellence');
//STEP(5)
$checkout->savePayment(array('method'=>'pay'));
Mage::getSingleton('checkout/type_onepage')->getQuote()->getShippingAddress()->setShippingMethod('excellence_excellence');
//STEP(6)
/*
* $checkout->saveOrder() returns array holding empty object
* of type Mage_Checkout_Model_Type_Onepage
*/
try {
$checkout->saveOrder();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
//addCartItems($products_delayed);
$cart->truncate();
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
Mage::getSingleton('customer/session')->logout();
$customerAddressId = '';
}
Problem is fixed:
That lied in checkout/session and customer/session which had to be cleared.
Mage::getSingleton('checkout/session')->clear();
Mage::getSingleton('customer/session')->clear();
That might help someone when resolving batch ordering solution with similar method.
Thanks,
Adam

How to get Magento customer ID

Ugh how do I get the customer ID!!? These are all things I've tried! Can you see what I'm doing wrong?
//include_once "app/Mage.php";
require_once '/home/ab71714/public_html/app/Mage.php';
//Mage::app("default");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
if($customer = Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getModel('customer/customer')->load($customer->getId())->getData();
print_r($customerData);
echo $customerData->getId();
}
//$customerData = Mage::getModel('customer/customer');
//$customerID = $customerData -> getId();
//$userinfo = $customerData->_origData; // fetch users info
$customerID=$customer -> getId();
//$customerID = $customerData->getEntityId();
//$customerID = $customerData[entity_id];
Try
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
}
See Current user in Magento?
The fastest way is
Mage::getSingleton('customer/session')->getId()
The function isLoggedIn will only return a boolean as to if a customer is logged in and no other information.
The customer session does have to following functions:
getCustomerId: which will return the customer id
getCustomer: which will return the customer object.

Categories