how to count items in an order(when item status=Mixed) using orderid in magento? - magento

I am trying to count total number of items in an order but I am unable to do so correctly.
I am using this code -
$total=0;
$order = Mage::getModel('sales/order')->load($oid);
$items = $order->getAllItems();
foreach($items as $item){
$qty = $item->getQtyToInvoice();
$total = $total + $qty;
}
echo "total :".$total;
This print correct result if the items status in orders is shipped but if the item status is mixed ,it prints 0 .

Are you simply looking for the number of items ordered, regardless of its shipped/invoiced/refunded status?
If so then then replace getQtyToInvoice() with getQtyOrdered().
For example:
foreach($items as $item){
$qty = $item->getQtyOrdered();
}
To answer the question in the comments: "I am also looking for the number of items shipped"
$item->getQtyShipped()

Related

How to get total amount from foreach lop in Laravel Controller

I want to get total amount from foreach lop data in the controller, for example, code bellow.
$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$forusdvaluetotal = coins::whereuser_id(Auth::user()->id)->get();
foreach($forusdvaluetotal as $coins){
$getsymbol = $coins->symbol.'USDT';
$getprice = $api->price("$getsymbol");
$valueinusd = $coins->balance*$getprice;
$total = $valueinusd;
}
$gettotal = $total->sum();
like "coins A" price is $50 per coin and balance 2, "coins B" price is $50 per coin and balance 5, "coins C" price is $50 per coin and balance 1. So I want to get total amount in USD by balance like ('coins A' $502 = $100 + 'coins B' $505 = $250 + 'coins A' $50*1 = $50) = $400
Please help me how to solve that in laravel controller.
Try this:
$total = 0;
foreach($forusdvaluetotal as $coins){
$getprice = $coins['market_price'];
$valueinusd = $coins['balance']*$getprice;
$total += $valueinusd;
}
return $total;
One elegant option would be to make use of Laravel's support collection method reduce().
The reduce method reduces the collection to a single value, passing
the result of each iteration into the subsequent iteration:
The value for $carry on the first iteration is null; however, you
may specify its initial value by passing a second argument to
reduce:
$collection = coins::whereuser_id(Auth::user()->id)->get();
$total = $collection->reduce(function ($carry, $item) {
return $carry + (floatval($item->balance) * floatval($item->market_price));
}, 0);
Addendum
Alternatively, you may make use of Laravel's support collection method sum().
The sum method returns the sum of all items in the collection:
In addition, you may pass your own closure to determine which values
of the collection to sum:
$collection = coins::whereuser_id(Auth::user()->id)->get();
$total = $collection->sum(function ($item) {
return (floatval($item->balance) * floatval($item->market_price));
});
Edit:
In response to your new question changes, you could solve it this way.
$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$query = coins::whereuser_id(Auth::user()->id);
// Get symbols.
$symbols = (clone $query)->distinct('symbol')->pluck('symbol')->flip()->toArray();
// Fetch prices.
array_walk($symbols, function (&$value, $key) use ($api) {
$value = $api->price("{$key}USDT");
});
// Get total sum.
$total = $query->get()->reduce(function ($carry, $item) use ($symbols) {
return $carry + (floatval($item->balance) * floatval($symbols[$item->symbol]));
}, 0);

Make unique invoice numbers with mysql and use

At the moment this is my function to create a random unique invoice number which is stored in a form's hidden field
function generate_invoice_number() {
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'];
$nr = 501 + $nr_last;
$value = sprintf( '%04d', $nr );
$number = 'LEDEXPO'.date('Y').'-'.uniqid().'-'.$value;
return $number;
}
I have a problem when multiple people are using the form at the same time, say 3 people are using the form they all have the same number generate.
So i added uniqid(), so $value could be duplicated but $number should be unique? Is this correct or is there a better way?
How can i make test function to test this function on uniqueness?
regards
Try This:
function generate_invoice_number()
{
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'] + 1;
$number = date('Ymd') . $nr_last;
return $number;
}

getAllVisibleItems(), getAllItems returns items twice

I'm trying to do something really simple - get the items from an order. There seem to be three functions that Magento 1.7 provides for this.
getAllItems() : This returns all items twice. The items returned
are of type simple (not configurable)
getItemsCollection() : Ditto
getAllVisibleItems() : Ditto
Many of the answers that I've read elsewhere point to this problem being caused by 'parent' and 'child' products, but there are none in my DB. I've checked the tables that define the parent/child relationship and they are both empty.
Here's the code that I'm running :
$order = Mage::getModel("sales/order")->load($order_id, 'increment_id'); //load order by order id
$ordered_items = $order->getAllVisibleItems();
//$ordered_items = $order->getAllItems();
//$ordered_items = $order->getItemsCollection();
foreach($ordered_items as $item)
{
if($this->debug)
{
echo $item->getItemId()."</br>";
echo $item->getProductId()."</br>";
echo $item->getSku()."</br>";
echo $item->getQtyOrdered()."</br>";
echo $item->getName()."</br>";
}
echo("*************************************************</br>");
}
And the output is
6
934
1003
1.0000
ProductA
*************************************************
6
934
1003
1.0000
ProductA
*************************************************
As you can see the first figure outputted is the actual entity_id - so I'm getting real duplication of the same item?
You have to use this code
$order = Mage::getModel("sales/order")->load($order_id, 'increment_id');
$_items = $order->getItemsCollection();
foreach ($_items as $item) {
if ($item->getParentItem()) continue;
//do something
echo $item->getSku();
}

Magento: count products using stock quantity

I'm new in magento.
I'm wondering how I can count all products using stock quantity. For example, I have
category 1
product one - stock 10
product two - stock 5
category 2
product three - stock 10
The result of the sum of all products should be 25
Actually, I'm using
<?php
$prods = Mage::getModel('catalog/product')->getCollection();
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($prods);
$count = number_format(count($prods));
echo $count;
?>
but this counts the products without stock quantity.
Thanks for your help.
Untested but this should get you what you need…
$stockItemCollection = Mage::getModel('cataloginventory/stock_item')
->getCollection();
$stockTotal = array_sum($stockItemCollection->getColumnValues('qty'));
This should work, too. The reports collection joins together all the quote_items. But I'm not sure wether any order status is considered
$collection = Mage::getResourceModel('reports/product_sold_collection');
$collection->addOrderedQty();
// EDIT reading the question is all
$sum = 0;
foreach($collection as $product) {
$sum += $product->getOrderedQty();
}
echo $sum;

PHP - How to accomplish this if?

I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}

Resources