Magento - Check for Customer's First Order - magento

Is there a quick way to programatically check if the currently logged in customer has ever placed an order? I'm writing an observer and at a point I want to simply say
if ($this->isCustomerLoggedIn() && (has never placed an order))
{
do this
}
possible?
Thanks!

$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', $customer->getId());
if ($this->isCustomerLoggedIn() && (!$orders->getSize()))
{
// has never placed an order
}
The above assumes that you have a $customer but if it is not accessible from the event you can usually get the currently logged in customer with:
$customer = Mage::getSingleton('customer/session')->getCustomer();

Do you need to create an event?
$session = Mage::getModel('customer/session');
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id',$session->getId())->getFirstItem();

Related

Add products to order programmatically magento admin

I have customized my create order page and in that after selecting customer and store id I have information of the product(Ex product A), I want that after admin reaches the sales_order_create then there must be that product(Product A) in the 'Items Ordered' list by default.
Thanks in advance
One of the solutions is to add an observer for the event called "create_order_session_quote_initialized". In the observer you need to add something like this:
$session = $observer->getSession();
if ($session->getProductAdded()) {
return $this;
}
$product = Mage::getModel('catalog/product')->load($productId);
$session->getQuote()->addProduct($product);
$session->setProductAdded(true);
return $this;
It's not the exact code which already works. But I hope that this will help.
First we need to initialize the quote with product(Product A).
$quoteItem = Mage::getModel('sales/quote_item')
->setProduct($product)
->setQuote($this->getQuote())
->setQty($qty)
->setPrice($product->getPrice())
->save();
Convert this quote item to order item.
$orderItem = Mage::getModel('sales/convert_quote')
->itemToOrderItem($quoteItem)
->save($this->getOrder->getId());

How to programmatically disable product for all store-view in Magento?

I want to disable product programmatically for all store view. Please help me
I tried with the following... but no luck
$storeId = 0;
Mage::getModel('catalog/product_status')->updateProductStatus($product_id, $storeId, Mage_Catalog_Model_Product_Status::STATUS_DISABLED);
Firstly $storeId=0 is default store id for admin if you want disable product for all store view then you can set $storeId=Mage:app()->getStoreId()// this is for current store id
after that you can disable all product
$product_id=1;
$storeId=Mage::app()->getStoreId();
Mage::getModel('catalog/product_status')->updateProductStatus($product_id, $storeId, Mage_Catalog_Model_Product_Status::STATUS_DISABLED);
EDIT
This is for all store view i think this is the dirty way to achieve this
<?php
$allStores = Mage::app()->getStores();
foreach ($allStores as $_eachStoreId => $val)
{
$_storeId[] = Mage::app()->getStore($_eachStoreId)->getId();
}
for($i=0;$i<count($_storeId);$i++)
{
$product_id=1;
$storeId=$_storeId[$i];
Mage::getModel('catalog/product_status')->updateProductStatus($product_id, $storeId, Mage_Catalog_Model_Product_Status::STATUS_DISABLED);
}
?>
Let me know if you have any query
By default the scope of status attribute is set to store , if we will set it to global under manage attributes , than we can update status for all store views with below code.
$loadproduct = Mage::getModel("catalog/product")->load("product_id");
$loadproduct->setStatus(2);
$loadproduct->save();
thanks
There's a much shorter way than in the answer of Keyur Shah:
foreach (Mage::app()->getStores() as $store) {
Mage::getModel('catalog/product_status')->updateProductStatus($productId, $store->getId(), Mage_Catalog_Model_Product_Status::STATUS_DISABLED);
}

How to check if a Magento product is already added in cart or not?

I want to show popup when a product is first added to cart in Magento and don't want to show a popup if the product was added again or updated.In short, I want to know product which is going to be added in the cart is First occurence or not?
The answer largely depends on how you want to deal with parent/child type products (if you need to).
If you are only dealing only with simple products or you have parent/child type products and you need to test for child id's then:
$productId = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote();
if (! $quote->hasProductId($productId)) {
// Product is not in the shopping cart so
// go head and show the popup.
}
Alternatively, if you are dealing with parent/child type products and you only want to test for the parent id then:
$productId = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$foundInCart = false;
foreach($quote->getAllVisibleItems() as $item) {
if ($item->getData('product_id') == $productId) {
$foundInCart = true;
break;
}
}
EDIT
The question was asked in a comment as to why setting a registry value in controller_action_predispatch_checkout_cart_add is not available to retrieve in cart.phtml.
Essentially registry value are only available through the life of a single request - you are posting to checkout/cart/add and then being redirected to checkout/cart/index - so your registry values are lost.
If you would like to persist a value across these then you can use the session instead:
In your observer:
Mage::getSingleton('core/session')->setData('your_var', 'your_value');
To retrieve the value
$yourVar = Mage::getSingleton('core/session')->getData('your_var', true);
The true flag being passed to getData will remove the value from the session for you.
In order check if the product is already in cart or not, you can simply use the following code:
$productId = $_product->getId(); //or however you want to get product id
$quote = Mage::getSingleton('checkout/session')->getQuote();
$items = $quote->getAllVisibleItems();
$isProductInCart = false;
foreach($items as $_item) {
if($_item->getProductId() == $productId){
$isProductInCart = true;
break;
}
}
var_dump($isProductInCart);
Hope this helps!

Magento Programmatically Edit Order Payment

I need to make a change of payment method to an order after it is placed. I have the order ID ($orderID), the order object ($order), a proper payment object, etc.
$service->retrievePaymentType() Returns the payment in the form of Mage_Sales_Model_Order_Payment
All of this happens in an extension of Mage_Checkout_Model_Type_Onepage
Does anybody know how I would go about doing this?
$order = Mage::getModel('sales/order')->load($orderID);
$service = Mage::getModel('sales/service_quote', $this->getQuote());
// Update Saved Order Payment Method
// $order->getPaymentsCollection()->clear();
$order->setPayment($service->retrievePaymentType());
$order->getPaymentsCollection()->save();
$order->save();
Thanks in advance!
Unfortunately, I had to do a direct SQL query, which is not Magento spec, but it gets the job done. If someone want's the code, leave me a comment, and I will dig it up.
Thanks though!
EDIT:
I managed to in fact get this working with Magento API:
// The payment type I want to change the target order to
$service = Mage::getModel('sales/service_quote', $this->getQuote());
$payment = $service->retrievePaymentType();
$paymentData = $payment->getData();
$oldPayment = $order->getAllPayments();
$oldPayment = $oldPayment[0];
foreach ($paymentData as $n => $v) {
$oldPayment->setData($n,$v);
}
It is a little bit hackish, but pretty effective.

Magento mass-assign products to category

As the title says,i need to mass-assign products to a category and from the admin i can only edit one product at a time; i dont know why it just doesnt work to mass add them from the "category products" tab in the category page.
Thats why i need another method that's fast,like using phpMyAdmin or something alike.
Any help?
Thanks in advance!
I created a simple script to do this outside of Magento. Be sure to test this first on a single product and make sure it looks as you'd expect.
// Load Magento
require_once 'path/to/app/Mage.php';
Mage::app();
// $productIds is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsIds = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', array('like' => 'something'))
->getAllIds();
// Array of category_ids to add.
$newCategories = array(20);
foreach ($productIds as $id) {
$product = Mage::getModel('catalog/product')->load($id);
$product->setCategoryIds(
array_merge($product->getCategoryIds(), $newCategories)
);
$product->save();
}
If you wish to overwrite a product's existing categories, change array_merge(...) to just $newCategories.
I would shy away from tackling this problem from the database side of things. If you do go that direction make sure and take lots of backups and do it during low usage.
The following thread on the Magento forum identifies the very same problem. One poster recommends a raw sql approach with example. Again, I would be careful - make sure you take backups.
The answer I like best from the thread (posted by Magento MVP):
Go into the category you don’t want them in, find the product list.
Click the check boxes on the products you want to remove and select
delete from the little dropdown.
Now go into the category where you
do want them, go to the product list. Select the NO dropdown so it
shows items not in the category. You might have to do a selective
search to limit stuff and do it in a couple iterations. Click the
check boxes and tell it to add stuff.
You may as well do this using the magento API
This is the script I use for mass adding products. sku.txt contains one sku per line.
<?php
$wsdlUrl = "magento-root/index.php/api/soap/?wsdl";
$proxy = new SoapClient($wsdlUrl);
$sessionId = $proxy->login('apiuser', 'apipasswd');
$listOfDiscountedSKUFile = "sku.txt";
function readinFile($filePath)
{
$fp = fopen($filePath,'r') or exit("Unable to open file!");
$dataItems = array();
while(!feof($fp))
{
$dataItems[] = trim(fgets($fp));
}
fclose($fp);
var_dump($dataItems);
return $dataItems;
}
function addToCategory($sku,$categoryId)
{
global $proxy,$sessionId;
$proxy->call($sessionId, 'category.assignProduct', array($categoryId, $sku));
}
function IsNullOrEmptyString($question){
return (!isset($question) || trim($question)==='');
}
$categoryId = 82;//e.g.
$listOfSKU = readinFile($listOfDiscountedSKUFile);
foreach($listOfSKU as $sku)
{
addToCategory($sku,$category);
}
?>
I managed to resolve the problem with the following code :
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$x = 1171;
$y = 2000;
$categoryID = 4;
$productPosition = 0;
while($x <= $y) {
$write->query("REPLACE INTO `catalog_category_product` (`category_id`, `product_id`, `position`) VALUES ($categoryID, $x++, $productPosition)");
}
echo "The job is done";
?>
I hope the code is clear for everyone,if it's not,reply and i'll try to explain it.
#nachito : here it is.

Resources