How can i make a stop if quantity is not enough? PHP - php

can anyone teach me how can i make a stop if the quantity is not enough? i'm trying to develop a pos and inventory system using codeigniter framework and here is my portion of code
if($prodid){
$inputQuantity = (int)$this->input->post('qty')[$x];
$this->db->where('id', $prodid);
$this->db->set('qty', "qty-$inputQuantity", false);
$this->db->update('products');
}
how can i make it stop if the quantity of the products reach 0 and when i process a new transaction with 0 qty of the products it will alert me of not enough stock can anyone help?

You may want check for availabe product stock
// in some model
public function check_stock($productId)
{
$product = $this->db->get_where($table_name, ['product_id' => $productId])->row();
if(isset($product))
{
if($product->stock == 0)
{
// There is no more products of this type
// For example
die("No more stock");
}
else
{
// Do other stuff is there is enought stock
// For example
// Let the user buy the product
}
}
}
I'm assuming you have a products table with stock and product_id columns

Related

How to update Prestashop product state programically?

I trying to learn PS and i want to simple update all Prestsahop products state by external script.
I have something like this to disable all products by the supplier (example):
<?php
include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');
$default_lang = Configuration::get('PS_LANG_DEFAULT');
$product = new Product();
if ($product->id_supplier = 2) {
$product->active = 0;
$product->update();
}
But it failed throwing PrestaShopDatabaseException
It seems that you create a new product and don't fill the required fields. If you want to change the existing product you need to set its id during a product object creation.
So your code should be like
$product = new Product($id_product, true, $default_lang); // if you want to get certain language, if ont skip the last parameter
if ($product->id_supplier = 2) {
$product->active = 0;
$product->update();
}
as i understood you want to disable all products for a specific supplier
first you want to get list of all product ids from table ps_product in database. then instantiate a product object by each id_product and disable it if it has the id_supplier condition that you mentioned
require(dirname(__FILE__).'/../config/config.inc.php');
// getting list of product_id
$product_ids = Db::getInstance()->executeS('select id_product from ps_product');
foreach($product_ids as $item) {
$product = new Product($item['id_product']);
if ($product->id_supplier == 2) {
$product->active = false;
$product->update();
}
}

Array item could not be found in php shopping cart

I am struggling with a weird situation here with arrays in PHP. I am trying to create a simple cart using a session variable.
Problem:
When the cart is empty, the program creates a new product with the itemid and qty variables when a product is added to cart (as required). It also does same when other new products are added.
It also is able to update the quantity of products if added again (as required).
But the problem here is it never finds the 1st product I add, so whenever I add that product again, it stacks the product every time and does not update the quantity of the product. Whereas for other products other than 1st, it acts as expected.
eg. when product A is added to empty cart, it adds itemid as A and qty = 1. When the product A is added again to an empty cart, it adds the itemid as A and qty=1 again (does not do qty=2). If I add B, C or others repeatedly it updates their qty as required
<?php
public function addinTable($id){
$this->loadModel('Carts');
/////////inserting into the cart table//////////7
$item = $this->Products->get($id);
$session = $this->request->session();
$allProducts = $session->read('Cart');
if(null!=$allProducts){
echo "<br>if(allProducts is NOT EMPTY)<br>";
if(array_search($id,array_column($allProducts, 'itemid'))){
//if the id is already in list
echo "<br><b>ITEM Is IN the list already</b>";
$key = array_search($id,array_column($allProducts, 'itemid'));
echo "<br> key is ", $key;
$newqty = debug($allProducts[$key]['qty']);
echo "<br> new qty +1 = ".$newqty+=1;
debug($allProducts[$key]['qty']++);
$session->write('Cart',$allProducts);
debug( $session->read('Cart'));
}
else{
echo"<br><b>The id is not found but cart is not empty</b>";
$allProducts[] = array('itemid'=>$id,
'qty' => 1
);
debug( $session->read('Cart'));
}
}
else{///////////if cart is empty at first
echo"<br><b>The cart is empty</b>";
$allProducts[] = array('itemid'=>$id,'qty' => 1);
debug($allProducts[0]);
debug($allProducts);
debug($allProducts[0]['itemid']);
// if(array_search($id,array_column($allProducts, 'itemid'))==true){echo "hello";}
$session->write('Cart',$allProducts);
debug($session->read('Cart'));
}
$session->write('Cart',$allProducts);//save the item
}
?>
array_search() returns the index, which is 0 for the first product. 0 evaluates to false.
You need a comparison against false here.
Change
if(array_search($id,array_column($allProducts, 'itemid'))) { //...
to
if(array_search($id,array_column($allProducts, 'itemid')) !== false) { //...
here's a fiddle that demonstrates this change: https://3v4l.org/m62Ya

Magento 1.9.3 Won't save customer group prices

I was assigned a Magento 1.9.3 project that would take in products in JSON format, and save customer group prices. However, even though there are no errors, nothing gets saved. The group prices won't show in the admin panel nor in the catalogue as expected.
Why is this? I've looked up every single article or stackexchange cases concerning group prices, but none of these seem to solve my problem.
Currently using the catalog_block_product_list_collection event.
$group_prices = $theProduct->getData('group_price');
if (is_null($group_prices)) {
$attribute = $theProduct->getResource()->getAttribute('group_price');
if ($attribute) {
$attribute->getBackend()->afterLoad($theProduct);
$group_prices = $theProduct->getData('group_price');
}
}
if(!is_array($group_prices)){
$group_prices = array();
$theProduct->addData(array('group_price' => $group_prices));
$theProduct->save();
}
$new_price = array(array (
'website_id'=>Mage_Core_Model_App::ADMIN_STORE_ID,
'customer_group_id'=>$customerGroupId,
'price'=> $singleProduct->Price));
$group_prices = array_merge($group_prices, $new_price);
$currentStore = Mage::app()->getStore()->getId();
try{
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
// First Delete all the group prices of product
$theProduct->setData('group_price', array());
$theProduct->save();
// Again save the old prices and new prices
$theProduct->setData('group_price', $group_prices);
$theProduct->save();
} catch(Exception $e) {
echo $e->getMessage();
}
Mage::app()->getStore()->setId($currentStore);
And yet, no group prices are saved when checking in the admin panel. Any help is appreciated.
For customer group field use cust_group instead of customer_group_id.
$new_price = array(array (
'website_id'=>Mage_Core_Model_App::ADMIN_STORE_ID,
'cust_group'=>$customerGroupId,
'price'=> $singleProduct->Price));
For details see:
app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Groupprice/Abstract.php line 299
there is condition:
if ($hasEmptyData || !isset($data['cust_group']) || !empty($data['delete'])) {
continue;}

Debugging foreach

I know this is a dump/basic question but I'm stuck and could use some help being a newbie.
What I'm Trying to Achieve: I want to have a foreach loop to get all of the product names in my users cart.
Problem: The foreach loop stops after the second iteration (if there are three things in the cart and I dump, only 2 are shown(the first and second)).
I know what a foreach loop does. I think my problem lays in my variable names but I tried messin around with them to no avail.
if (is_null($cart) || $cart->getSubmitted(true)) {
$cart = new UserCart();
// since new cart no need to check for duplicate product quantity
// add product to cart
$this->addFlash('notice', 'Creating a new cart because one didnt exist for the user before.');
}
else {
$quantity = new Quantity();
//If the cart is set
$getProductsInCurrentUsersCart = $cart->getQuantities(); //All Products In Users Cart (ARRAY COLLECTION/PERSITENT COLLECTION)
foreach ($getProductsInCurrentUsersCart as $key => $value) {
dump($getProductsInCurrentUsersCart);
$getProductsInCurrentUsersCart = $value->getProduct()->getName(); //SHOULD BE ALL PRODUCTS IN CART
if ($getProductsInCurrentUsersCart === $quantity->setProduct($productBeingAddedToCart)->getProduct()->getName()) {
$this->addFlash('notice', 'Comparission was TRUE.');
$quantity->setQuantity($quantity->getQuantity() + 1);
}
else {
$quantity->setQuantity(1);
$quantity->setProduct($productBeingAddedToCart);
$this->addFlash('notice', 'Comparisson was FALSE.');
} //ENDS IF/ELSE
} //EXECUTING ONCE??????????
$cart->setTimestamp(new \DateTime()); // Set Time Product was Added
// $quantity->setQuantity(1); // Set Quantity Purchased
$cart->setSubmitted(false); // Set Submitted
$cart->setUser($this->getUser()); // Sets the User ONCE
$cart->addQuantity($quantity); // Add Quantity ONCE
$quantity->setUserCart($cart); // Create a UserCart ONCE
$em->persist($productBeingAddedToCart);
$em->persist($cart);
$em->persist($quantity);
$em->flush();
$this->addFlash('notice', 'The product: '.$productBeingAddedToCart->getName().' has been added to the cart!');
}
Any help is really appreciated!
$getProductsInCurrentUsersCart = $value->getProduct()->getName();
Here you are redefining the list variable inside the loop. Try with $getProductsInCurrentUsersCart2 and also change it below this line. See if that solves it or not. Then come up with a better name :)

Restrict users to join competition if they buy products that are on special on magento

Restrict users to join competition if they buy products that are on sale
I want to create a condition where by if a customer buys a product that is on special he will get a message that says you got 10% discount else if a customer buys a product that's not on special he will get a message that says thank you for purchasing with us.
I checked the magento forum but no luck.
/*********************************************************************************************/
//how many vouchers the user wants to add
$voucher_products = 0;
//how many products vouchers can be used on
$vouchers_added = 0;
//grabbing the quote object from session
$quote = Mage::getSingleton('checkout/session')->getQuote();
//fetching all cart items from the quote
$items = $quote->getAllVisibleItems('name');
//We need to load the category for infantmilks
$category = Mage::getModel('catalog/category')->loadByAttribute('name', 'Infant Milks');
/* We need to perform a check to ensure that this category exists, by name. if it is not found using
* the name, the feature will not work. return an error message.
*/
if(!$category)
{
$this->addErrorMessage('There is an issue with the Voucher System. Please contact the site administrator.');
return;
}
//grab the production collection
$products_list = $category->getProductCollection();
/* Loop over all cart items, checking how many are
* part of the infantsmilk category. if an item is found
* that is part of the category, increment voucher_products.
*/
foreach ($items as $item) {
foreach ($products_list as $product){
if($item['product_id'] === $product->getId()){
$voucher_products = $voucher_products + 1;
}
}
}
//load the entires from the healthy start entity
$vouchers = Mage::getResourceModel('healthystart/voucher_collection');
//loop over all vouchers and checks if there are any vouchers in the current quote
foreach($vouchers as $voucher){
if ($voucher['quote_id'] === $item['quote_id']){
$vouchers_added = $vouchers_added + 1;
}
}
if ($voucher_products === 0){
$this->addErrorMessage('Healthy Start Vouchers can only be used on Infant Milks.
Please add an Infant Milks product to your basket to redeem your voucher.');
return;
}
else {
if($vouchers_added >= $voucher_products){
$this->addErrorMessage('You can not add another voucher.');
return;
}
}
/*****************************************************/

Categories