Get product qty using product id Prestashop - prestashop

I am not able to get qty using product id.
public function hookActionObjectProductUpdateAfter(array $params)
{
$vendproduct = $params['object'];
$lang_id = (int) Configuration::get('PS_LANG_DEFAULT');
$product = new Product($vendproduct->id, false, $lang_id);
print_r($product->quantity); exit;
}

You can get quantity by
$quantity = StockAvailable:: getQuantityAvailableByProduct($id_product = null, $id_product_attribute = null, $id_shop = null);

Related

Im using datatable in my project mvc , i want display Categorie name in place of categorye id foreign key in table courses

[HttpGet]
public JsonResult GetData()
{``
ApplicationDbContext db = new ApplicationDbContext();
var course = db.Courses
.Include(d=>d.Competences)
.Include(d=>d.Sequences)
.ToList().Select(p => new { Id = p.Id, Titre = p.Titre, ShortDescription = p.ShortDescription, Price = p.Price, CategorieId = p.CategorieId });
var query = from q in db.Courses
join cat in db.Categories.AsEnumerable()
on q.CategorieId equals cat.Libelle
enter code here
return Json(new { data = course },
JsonRequestBehavior.AllowGet);
}

Prestashop 1.7 check available stock at final order step

I had something working on Prestashop 1.6 to check cart quantities before the customer can buy. Here is my problem on Prestashop 1.7 :
If a customer put an item in his cart today, he comes back in 2 days and he is still logged in. The cart is still available while the product, in reality, became out of stock.
The customer can make the order and the quantity in my stock is -1. Since I upgraded to prestashop 1.7 it's a disaster, I have quantities at -5, -10...because if this non-checked scenario.
abstract class PaymentModule extends PaymentModuleCore
{
public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown',
$message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false,
$secure_key = false, Shop $shop = null)
{
if (!isset($this->context))
$this->context = Context::getContext();
$this->context->cart = new Cart($id_cart);
if (!$this->context->cart->checkQuantities()){
Tools::redirect(__PS_BASE_URI__.'order.php?step=0');
}
return parent::validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method, $message,
$extra_vars, $currency_special, $dont_touch_amount, $secure_key, $shop);
}
}
Actually the best solution is to use this addons : https://addons.prestashop.com/en/stock-supplier-management/21707-temporary-product-reservation-lonely-stock.html
Prestashop handles really bad cart stocks.
Anyway if you want to do it yourself and check stock available it's pretty simple :
<?php
$cart = $this->context->cart;
$cart_products = $cart->getProducts();
if (!empty($cart_products)) {
$db = Db::getInstance();
foreach ($cart_products as $key => $cart_product) {
$real_quantity = StockAvailable::getQuantityAvailableByProduct($cart_product['id_product'], $cart_product['id_product_attribute']);
if ( (int) $real_quantity < (int) $cart_product['quantity'] ) {
// If negative
$real_quantity = (int) $real_quantity < 0 ? 0 : $real_quantity;
$sql = '
UPDATE `'._DB_PREFIX_.'cart_product`
SET quantity = '.(int) $real_quantity.',`date_add` = NOW()
WHERE `id_product` = '.(int) $cart_product['id_product'].
(!empty($cart_product['id_product_attribute']) ? ' AND `id_product_attribute` = '.(int) $cart_product['id_product_attribute'] : '').'
AND `id_cart` = '.(int) $cart->id;
$db->execute($sql);
}
}
// Garbage collector
$db->execute('DELETE FROM '._DB_PREFIX_.'cart_product WHERE quantity < 1 ');
}

datediff with case statement in select query linq

select case statement in linq query.
Here is the query on sql:
select case when DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101)) = 0 then
Sum([Order].OrderSubtotal)
else
case when (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30) = 0 then Sum([Order].OrderSubtotal) else
Sum([Order].OrderSubtotal)/
(DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30)
end
end as 'Account Value' from [order] where And Account.ID = #Act_ID
I am trying the code here:
var query = _orderRepository.Table;
query = query.Where(o => o.AccountId == accountId);
In query i am getting my value.
After query statement what should i write??
how do i write for case statement using linq???
#Manoj, may be the below code helps you. This sample C# project may solve the problem you have.
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateDiffIssue
{
class Program
{
static void Main(string[] args)
{
// Preparing data
var data = new Order[] {
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 10:00"), OrderSubtotal = 100 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 12:00"), OrderSubtotal = 150 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 14:00"), OrderSubtotal = 150 }
};
// Selection
var selected = (from item in data
let accountData = data.Where(w => w.AccountID == 1)
let minDate = accountData.Min(m => m.CreatedOnUtc).Date
let maxDate = accountData.Where(w => w.AccountID == 1).Max(m => m.CreatedOnUtc).Date
let isSameDate = minDate == maxDate
let basedOn30Days = (maxDate - minDate).TotalDays / 30
let isInside30Days = (int)basedOn30Days == 0
let accountDataSum = accountData.Sum(s => s.OrderSubtotal)
select new
{
AccountValue = isSameDate ? accountDataSum :
isInside30Days ? accountDataSum :
accountDataSum / basedOn30Days
}).Distinct();
// Print each order
selected.ToList().ForEach(Console.WriteLine);
// Wait for key
Console.WriteLine("Please press key");
Console.ReadKey();
}
}
internal class Order
{
public int AccountID { get; set; }
public DateTime CreatedOnUtc { get; set; }
public int OrderSubtotal { get; set; }
}
}

Sku not working in magento product update API

$result = $client->call($session, 'catalog_product.update', array('123', array(
'name' => 'Product333222'
)
)
);
Here '123' is the Sku of product. Sku is not working here in update Api.
If i give Product ID in place of Sku it is working fine.
So what is the Issue behind that.
If anyone Knows please let me know.
Thanks.
Magento is a bit dull here.
Long story short:
If you are using a numeric value without specifying an identification type its assuming you are doing your works on a product id. If you where to insert "abc" as a value (not numeric) it will be treated as if it were a SKU.
Best way to solve this is to use an identification type (in your case "SKU") in your api call.
Please see this for more info on using the identification type. http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalog_product.update.html
Or see: Magento 1.5, numeric SKUs and productIdentifierType
Short story long:
The following function gets called trough the api
app/code/core/Mage/Catalog/Model/Api/Resource.php
protected function _getProduct($productId, $store = null, $identifierType = null)
{
$product = Mage::helper('catalog/product')->getProduct($productId, $this->_getStoreId($store), $identifierType);
if (is_null($product->getId())) {
$this->_fault('product_not_exists');
}
return $product;
}
As you can see that function is calling the following function in the product helper:
public function getProduct($productId, $store, $identifierType = null) {
$loadByIdOnFalse = false;
if ($identifierType == null) {
if (is_string($productId) && !preg_match("/^[+-]?[1-9][0-9]*$|^0$/", $productId)) {
$identifierType = 'sku';
$loadByIdOnFalse = true;
} else {
$identifierType = 'id';
}
}
/** #var $product Mage_Catalog_Model_Product */
$product = Mage::getModel('catalog/product');
if ($store !== null) {
$product->setStoreId($store);
}
if ($identifierType == 'sku') {
$idBySku = $product->getIdBySku($productId);
if ($idBySku) {
$productId = $idBySku;
}
if ($loadByIdOnFalse) {
$identifierType = 'id';
}
}
if ($identifierType == 'id' && is_numeric($productId)) {
$productId = !is_float($productId) ? (int) $productId : 0;
$product->load($productId);
}
return $product;
}
Without specifying an $identifierType here and using a sku like '123' the thrid line is going to do a preg match with will result in true. Thus using its else function threating it as an ID in stead of sku.
In the end:
So, do your call like:
$result = $client->call($session, 'catalog_product.update', array('123', array(
'name' => 'Product333222'
), null, 'sku'));

How do i write update number of download bought function in controller of magento

i want to update number_of_download_bougt. So How will SQL be in a controllers?
i wrote:
public function updatedownloadAction($db_magento, $id, $numberdownload)
{
// $id = $this->getRequest()->getParam('id', 0);
$db_magento = Mage::getModel('downloadable/link_purchased_item')->load($id);
$db_magento->query("UPDATE downloadable_link_purchased_item d
SET d.number_of_downloads_bought = '$numberdownload'
WHERE d.item_id = '$id'");
}
but it's error
Use the setNumberOfDownloadsUsed function to set the number purchased.
$id = $this->getRequest()->getParam('id', 0);
$linkPurchasedItem = Mage::getModel('downloadable/link_purchased_item')->load($id, 'link_hash');
$linkPurchasedItem->setNumberOfDownloadsUsed($linkPurchasedItem->getNumberOfDownloadsUsed()+1);
if ($linkPurchasedItem->getNumberOfDownloadsBought() != 0 &&
!($linkPurchasedItem->getNumberOfDownloadsBought() - $linkPurchasedItem->getNumberOfDownloadsUsed())) {
$linkPurchasedItem->setStatus(Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_EXPIRED);
}
$linkPurchasedItem->save();