How to Programatically cancel order in magento 2 - php

If a customer placed an order of 3 different items with different quantities like
shirt 2 qty
Watch 1qty
pant 3qty
and cancels the order item at different times I have to set the state to order cancelled
here's my code can anyone please tell me where I am wrong
if (isset($_POST['order'])) {
$_orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$collection = $_orderCollectionFactory->create()
->addFieldToSelect('*')
->addFieldToFilter('status', ['neq' => 'cancelled']);
foreach ($collectionFactory as $order)
{
$items = $order->getAllVisibleItems();
foreach ($items as $items) {
$totalitem = $totalitem + ($item['qty_canceled']);
$itemcount = $order->getQtyOrdered();
if ($itemcount == ($totalitem))
{
$order->setState("canceled");
$order->save();
}
}
}
}

Finally, I have Solved the issue for the above code
$_orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$collection = $_orderCollectionFactory->create()
->addFieldToSelect('*')
->addFieldToFilter('status', ['neq' => 'cancelled']);
foreach ($collection as $order)
{
$items = $order->getAllVisibleItems();
$totalitem=0;
foreach ($items as $item) {
// echo '<pre>';print_r(get_class_methods($item));
// die();
$totalitem = $totalitem + ($item['qty_canceled']);
$itemcount = $order->getQtyOrdered();
if ($itemcount == ($totalitem))
{
echo $order->getIncrementId();
$order->setState("canceled");
$order->setStatus("canceled");
$order->save();
}
}
}

Related

Magento - update cart item by item ID

How to update cart item using item ID ? I have searched a lot but could not success, here is my codes -
require_once '../app/Mage.php';
Mage::app('default');
$qty = $_REQUEST['quantity'];
$item_id = (int) $_REQUEST['item_id'];
$cart = Mage::getSingleton('checkout/cart');
$quoteItem = $cart->getQuote()->getItemById($item_id);
/*$quoteItem = Mage::getModel('sales/quote_item')->getCollection()
->addFieldToFilter('item_id', array('in' => array($item_id)));*/
print_r($quoteItem);
if (!$quoteItem) {
Mage::throwException('Quote item is not found.');
}
if ($qty == 0) {
$cart->removeItem($id);
} else {
$quoteItem->setQty($qty)->save();
}
$cart->save();
I am implementing it in API , however same code is working fine in website.Please help!!!
I used the below code to update cart items and I am using observer to do that. can you please try this.
$quote = $observer->getEvent()->getQuote();
var_dump($quote->getId());
$quote = Mage::getSingleton('checkout/session')->getQuote();
//var_dump($quote->getId());
$cartItems = $quote->getAllItems();
//$storeId = Mage::app()->getStore()->getId();
foreach ($cartItems as $item) {
//echo $item->getSku();
$item->set__($value); // desired quote field from database
$item->save();
}
$quote->save();

Change value in session and save it. Laravel

I want to update product price when I submit coupon code I named my coupon as ticket. This is my function:
public function order(Request $request)
{
$products = session('cart');
$ticket_code = Input::get('ticket');
$ticket = Ticket::where('ticket', $ticket_code)->first();
foreach($products as $p){
$price = $p['price'];
}
if(count($products) && $ticket['max'] > $ticket['used']) {
$subtotal = [$price*70/100];
$ticket->used += 1;
$ticket->save();
foreach($products as $p){
$p['price'] = $subtotal;
$p->save();
}
flash()->success('Kuponas sÄ—kmingai panaudotas!');
return view('cart.order')->with(array(
'products' => $products,
'subtotal' => $subtotal,
));
}
else {
$finalTotal = 0;
$subtotal = [];
return view('cart.order')->with(array(
'products' => $products,
'subtotal' => $subtotal,
'finalTotal' => $finalTotal
));
}
}
this code doesnt work:
foreach($products as $p){
$p['price'] = $subtotal;
$p->save();
}
I get error: Call to a member function save() on array
Without the foreach the ticket itselfs works. It changes the price when submited, but only in that one page. Then when I go to payment site, the price is still displayed without ticket used.
THE WORKING SOLUTION
foreach($products as &$item) {
$item['price'] = $item['price']*70;
$item['price'] = $item['price'] / 100;
}
Session::put('cart', $products);
THIS WORKED
foreach($products as &$item) {
$item['price'] = $item['price']*70;
$item['price'] = $item['price'] / 100;
}
Session::put('cart', $products);

Add exactly 1 product to cart programmatically in Magento

Using Magento 1.8.1, on the checkout page, I'm trying to add a product to the cart in the code. Here is the code I'm using:
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$this->addProduct($free_samples_prod_id, 1);
}
else{
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $free_samples_prod_id) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
}
The code is in: app\code\core\Mage\Checkout\Model\Cart.php under public function init()
The product does get added sucessfully, however, everytime somebody visits their cart page, the quantity increases by one. How can I modify that code so the quantity is always 1?
Thank you
Axel makes a very good point, but to answer your immediate question, why not test for the product's presence before you add it
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$alreadyAdded = false;
foreach ($items as $item) {
if($item->getId() == $free_samples_prod_id) { $alreadyAdded = true; break; }
}
if(!$alreadyAdded) { $this->addProduct($free_samples_prod_id, 1); }
}

Echo custom options with the values for Magento

How to echo all custom options with all the values by product id for Magento?
If i am using this code...
public function ws_productdetail($store_id, $service, $productid)
{
$res=array();
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productid))
->addAttributeToSelect('*');
$all_product_images = array();
$product = Mage::getModel('catalog/product')->load($productid);
foreach ($product->getMediaGalleryImages() as $image) {
$all_product_images[] = $image->getUrl();
}
foreach($productsCollection as $product)
{
$res["id"] = $product->getId();
$res["name"] = $product->getName();
$res["price"] = number_format($product->getPrice(),2);
}
return($res);
}
... how can I get the custom options?
For example say for a product JEANS, COLOR with various values {blue,black,brown} and every option will have different prices, then how i get all this information as output.
According to my understanding, you want to show the all DROPDOWN custom option on view page then try this.
$productid = $_product->getId(); //PLEASE ENTER THE PRODUCT ID HERE
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
foreach($attVal as $optionKey => $optionVal)
{
$optStr.='<dl><div class="custom_select_css">
<dt><label>'.$optionVal->getTitle().'</label></dt>
<dd class="last">
<div class="input-box">';
$optStr.= "<select id='".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$price = number_format($valuesVal->getPrice(),0);
$optStr.= "<option price='".number_format($valuesVal->getPrice(),0)."' data-label='".$colorarray[$valuesVal->getTitle()]."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle(); if($price != '0'){$optStr.=" +$".number_format($valuesVal->getPrice(),2);}$optStr.=" </option>";
}
$optStr.= "</select></div></dd><div></dl>";
}
echo $optStr;
------------------------------ UPDATED CODE -------------------------------
public function ws_customdetail ($productid)
{
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal)
{
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;
}
$inc++;
}
return $all_custom_option_array;
}
Use ws_customdetail function and pass the product id in it.
THIS IS THE EXACT CODE THAT WORKED FOR ME.
public function customdetail($productid){
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal){
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$all_custom_option_array[$inc]['custom_option_type']=$optionVal->getType();
$all_custom_option_array[$inc]['custom_option_value_array'];
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal){
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;}
$inc++;}
return $all_custom_option_array;}
HOPE THIS WILL HELP SOMEONE :)
THANX

Adjust Array Value in Shopping Cart based on User login state

How would I adjust individual values within the $_SESSION array depending on whether the user is logged_in or not logged_in. So basically the array values equate to the individual item prices within the shopping cart and will be adjusted if the user logs in or logs out of the SESSION.
Here's my current code:
PHP
if(!empty($_SESSION)){
foreach($_SESSION['basket'] as $b){
if ($session->logged_in) { $b['itemprice'] = ""; }
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
MYSQL
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) { }
The closest I've come to getting this to work is each product in the cart is given the same price which changes if the user logs in or out. However, I need each item to change to the new price specific to that items product ID.
Some of our members receive a discount on certain items, so once the user logs in from being a GUEST to the registered USER the price needs to be changed on page refresh.
An example being :
**Logged in == FALSE**
Item 1 Price: 100.00
Item 2 Price: 100.00
**User logs in (Logged in == TRUE)**
Item 1 Price: 85.00
Item 2 Price: 94.00
I hope I've been clear - any advice would be appreciated.
Thanks
OPTION A:
function updateCartPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) {
foreach ($_SESSION['basket'] as $key => $item)
{
if($result['product_id'] == $item['itemid'])
{
$_SESSION['basket'][$key]['itemprice'] = ($_SESSION['logged_in']) ? $result['price'] : $result['price_100'];
}
}
}
}
if(!empty($_SESSION)){
updateCartPrices();
foreach($_SESSION['basket'] as $b){
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
OPTION B (performance better):
function getLoggedInPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
$prices = array();
while ($result=mysql_fetch_array($query)) {
$prices[$result['product_id']] = $result['price'];
}
return $prices;
}
if(!empty($_SESSION)){
$loggedInPrices = getLoggedInPrices();
foreach($_SESSION['basket'] as $b){
if($_SESSION['logged_in'])
{
$b['itemprice'] = $loggedInPrices[$b['itemid']];
}
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) {

Categories