I am creating a webshop for a rental company. I want to be able to change the price of items according to amount of days they rent the item. I was already able to get the amount of days, but not sure on how to change the price of an item.
This is my code so far in the cart controller.
The error I get is that $rowId is not defined.
public function getTime(Request $request){
$startD = Carbon::parse($request->input('dateOut'));
$endD = Carbon::parse($request->input('dateIn'));
$length = $endD->diffInDays($startD) + 1;
$total = Cart::subtotal();
$rows = Cart::count();
for ($i=0; $i <$rows ; $i++) {
$item = Cart::get($rowId);
Cart::update(
$rowId, [
'price' => $items->product_price*$length,
]);
}
echo $startD;
echo $endD;
echo $length;
echo $total;
}
If you are updating the price of a specific cart, then you can use such a query.
\DB::statement("update carts set price = ABS(`price` * datediff(?,?)) where id=?", [$dateOut, $dateIn, $cart_id]);
Related
I'm trying to exclude/ignore a specific item from a 'count' in an array which generates a CSV file.
I generate a daily CSV file of orders from Woocommerce;
Each Order is made up of a quantity of varying single products;
I define the CSV Headers manually -eg:
$csv_header = array('Order ID','Company Name','Contact Name','Address 1','Address 2','Suburb','Product 1', 'Product 2', 'Product 3','#Items')
I pull the metadata based on Order IDs:
$result = $wpdb->get_results('SELECT * FROM `'.$wpdb->prefix.'postmeta` WHERE post_id = '. (int)$order_id->ID);
I create an instance of each order and get the items:
$order = new WC_Order((int)$order_id->ID);
$items = $order->get_items();
After getting the details and setting the column for those - eg:
if( $res->meta_key == '_shipping_company'){
$order_line[2] = $res->meta_value;
I then loop to create the invidual item product count and the #items total
foreach ($items as $item ) {
$_count = array_search( $item['name'], $csv_header );
$order_line[$_count] = $item['item_meta']['_qty'][0];
$row_items += $order_line[$_count];
}
$order_line[10] = $row_items;
and add blanks to products not in the order:
for ($i = 0; $i < 37; $i++) {
if( !isset($order_line[$i]) && empty($order_line[$i]) ) {
$order_line[$i] = '';
}
This all works well, but now I need to EXCLUDE a product NOT defined in the $csv_header from the count - bearing in mind that the Order will contain defined products. eg: count products 1-3 but not Product 4.
At the moment if a Product is not defined in $csv-header, it will put a number in my first column in place of the order-id instead of ignoring it.
Any suggestions appreciated.
My client and I are trying to achieve something that we are maybe not supposed to do. We have a demanding set of non-standard products that include different types of product conditions, e.g. grade B ware etc. In addition product data is coming in in form of feeds from several suppliers. In order not to clutter up the product listing we would like to convert existing, manually edited simple products into grouped ones (or whatever is appropriate) with associated new simple products programmatically on the fly and vice versa whenever necessary, i.e. when there are at least two different sub products.
So far we managed to do this somehow, a test scenario produces the seemingly right product structure – correctly associated products are displayed in the backend, the quantities have been correct before. The problem occurs with the frontend check on 'isSaleable()' for both the grouped product and the associated products, it returns 'false' no matter what we do. When we enforce the display of the qty input boxes and add-to-cart button they will (naturally?) just product the error message 'Please specify the quantity of product(s)'. We tried to set 'is_salable' by different means throughout the code. What else is missing? Any little hint, any advice here would be appreciated!
The code is quite lengthy already, and probably there's already some redundancy in there because of our attempts to somehow fix this. There's a main script that fetches a product collection and compares each entry with the existing supplier feeds. The essential part then is the function call to convert the product:
if (sizeof($newProducts[$productsSku]) > 1 && $_product->getTypeId() == 'simple') {
$newProductQtys = createGroupedProduct($_product, $newProducts[$productsSku]);
}
There are 2 functions for the actual conversion process, one which creates duplicates of the master products (type = simple) and sets their values accordingly:
function createDuplicate($product, $values) {
global $suppliers, $conditions_arr;
$sku = $product->getSku();
$newSku = $sku.'-v'.$suppliers[$values['feed']]['id'];
$qty = $values['qty'];
$feed = $values['feed'];
$cost = $values['cost'];
$item_condition = $values['item_condition'];
$box_condition = $values['box_condition'];
$notes = stripslashes($values['notes']);
$newProduct = $product->duplicate();
$newProduct->setTypeId('simple');
$newProduct->setStoreId(0);
$newProduct->setWebsiteIds(array(1));
$newProduct->setVisibility(2);
$newProduct->setSku($newSku);
$newProduct->setData('media_gallery', array());
$newProduct->setStatus(Mage_Catalog_Model_Product_Status::smileyfrustrated:TATUS_ENABLED);
$newProduct->setPrice((real)($cost + $cost*$suppliers[$feed]['price_increase']));
$newProduct->setTaxClassId(2);
$newProduct->getResource()->save($newProduct);
$productId = $newProduct->getId();
// Check if there is a stock item object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemData = $stockItem->getData();
if (empty($stockItemData)) {
// Create the initial stock item object
$stockItem->setData('inventory_manage_stock_default', 1);
$stockItem->setData('manage_stock',1);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->setData('use_config_manage_stock', 1);
$stockItem->setData('stock_id',1);
$stockItem->setData('product_id',$productId);
$stockItem->setData('qty',$qty);
$stockItem->setTypeId( $newProduct->getTypeId() );
$stockItem->save();
// Init the object again after it has been saved so we get the full object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
}
// Set the quantity
$stockItem->setData('qty',$qty);
$stockItem->setData('is_salable', 1);
$stockItem->save();
// $newProduct->assignProduct($newProduct, 1, 1);
$newProduct->setIsSalable(1);
$newProduct->setStatus(Mage_Catalog_Model_Product_Status::smileyfrustrated:TATUS_ENABLED);
$newProduct->save();
$event = Mage::getSingleton('index/indexer')->logEvent($newProduct,$newProduct->getResource()->getType(),Mage_Index_Model_Event::TYPE_SAVE,false);
Mage::getSingleton('index/indexer')->getProcessByCode('cataloginventory_stock')->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->processEvent($event);
return $productId;
}
and
function createGroupedProduct($product, $newProductsArr) {
global $suppliers;
$origProductId = $product->getId();
$sku = $product->getSku();
$newProductId = array();
$newProductQtys = array();
$qty = 0;
$price = 999999;
$product->setTypeId('grouped');
$product->save();
foreach($newProductsArr as $key => $values) {
$id = createDuplicate($product, $values);
$newProductId[] = $id;
$newProductQtys[$id] = $values['qty'];
// add up all stock quantities of all slave products for master
$qty += $values['qty'];
// determine lowest price among all slave products
$subItemPrice = (real)($values['cost'] + $values['cost']*$suppliers[$values['feed']]['price_increase']);
if ($subItemPrice < $price) $price = $subItemPrice;
}
if (sizeof($newProductId) > 1) {
$products_links = Mage::getModel('catalog/product_link_api');
foreach($newProductId as $key => $id) {
$products_links->assign('grouped', $origProductId, $id);
}
}
// set new values for grouped product according to slave products values
$product->setPrice($price);
$product->getResource()->save($product);
// Check if there is a stock item object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($origProductId);
$stockItemData = $stockItem->getData();
if (empty($stockItemData)) {
// Create the initial stock item object
$stockItem->setData('manage_stock',1);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->setData('use_config_manage_stock', 1);
$stockItem->setData('stock_id',1);
$stockItem->setData('product_id',$origProductId);
$stockItem->setData('qty',$qty);
// $stockItem->setTypeId( $product->getTypeId() );
$stockItem->setTypeId('grouped');
$stockItem->save();
// Init the object again after it has been saved so we get the full object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($origProductId);
}
// Set the quantity
$stockItem->setData('qty',$qty);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->save();
$product->setStatus(Mage_Catalog_Model_Product_Status::smileyfrustrated:TATUS_ENABLED);
$product->save();
$event = Mage::getSingleton('index/indexer')->logEvent($product,$product->getResource()->getType(),Mage_Index_Model_Event::TYPE_SAVE,false);
Mage::getSingleton('index/indexer')->getProcessByCode('cataloginventory_stock')->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->processEvent($event);
$cache = Mage::getSingleton('core/cache');
$cache->flush();
return $newProductQtys;
}
We tried using the store ID '1' as well and had some success with the shopping cart when the front end used the same kind of mass-product-add-to-cart form that we integrated into the product listing. But the associated products then showed no product name and no image, and not in the admin at all.
If more code from the main script is necessary I will happily provide this.
I have the following simple code with a loop of products:
$_product->setCustomerGroupId(6);
$price = $_product->getFinalPrice();
I have a customer group (id of 6) that has a 50% discount applied to it.
The $price variable is always the full price. How can I get the discounted price?
This is in an API script I am writing, so there is no customer/session object. I can create one if required but would prefer to try and steer clear of creating temp sessions.
Check This:
<?php
$now = Mage::getSingleton('core/date')->timestamp(time());
$websiteId = 1;
$customerGroup = 4;
$productId = 9369;
$rules = Mage::getResourceModel('catalogrule/rule');
$rules->getRulePrice($now, $websiteId, $customerGroup, $productId));
?>
I'm working on a shipping calculator and i have a problem,let me tell you what i have and then i'll tell you my problem,
My array and foreach:
$array = unserialize($_SESSION['__vm']['vmcart']);
foreach($array->products as $product){
$price = $product->product_price;
$amount = $product->quantity;
$length = $product->product_length;
$width = $product->product_width;
$height = $product->product_height;
$weight = $product->product_weight;
$supplier = $product->product_unit;
}
and everything works with the above code (That's not my problem)
My problem is:
the calculator has to take all the weight from supplier 1 and add them together and then do the same for supplier 2 (see below)
Example:
Product1 - weight is 5kg and it's from supplier 1
Product2 - weight is 2kg and it's from supplier 1
Product3 - weight is 9kg and it's from supplier 2
supplier 1's weight = to 7kg
supplier 2's weight = to 9kg
The same thing if it's the other way around,
Now what i have tried is a if statement (see below) but all it's doing is adding every products weight together,
if ($supplier =='S1'){
$s1_total_weight += $product->product_weight;
} if ($supplier =='S2'){
$s2_total_weight += $product->product_weight;
}
echo 'Supplier 1 '.$s1_total_weight.'<br>';
echo 'Supplier 2 '.$s2_total_weight.'<br>';
i use the below code to get the supplier number (S1 = supplier 1 - S2 = supplier 2),
$supplier = $product->product_unit;
I'm new to php but i think it has to do with the below code or am i wrong? can it be the if statement?
$product->product_weight
Please let me know if you need any more information,
if you have a better title for this topic please change it :)
Thanks for any help.
$weights = array();
foreach ($array->products as $product) {
if (isset($weights[$product->product_unit])) {
// there was already some weight for this supplier, just add to it
$weights[$product->product_unit] += $product->product_weight;
}
else {
// first time we encounter this supplier, set weight
$weights[$product->product_unit] = $product->product_weight;
}
}
foreach ($weights as $supplier => $totalWeight) {
echo "Total weight for supplier {$supplier} is {$totalWeight}.";
}
below is the code am using to send product name and quantity, this works perfect I want to send a total cost at the same time that name and quantity get sent but am not sure how to go about doing this as am pretty new to php so thanks in advance
<?php
if (isset($_POST['form_products'])) {
$quantity=$_POST['quantity'];
$total = $the_price_is * $quantity; // want to be able to send $total at same time
$order = array($_POST['dryer']=>$_POST['quantity']);
if (!empty($_SESSION['products'])) {
foreach($_SESSION['products'] as $name => $quantity_value){
if (isset($order[$name])){
print "<br>Your order as been added to your cart";
$order[$name]+=$quantity_value;
}
}
$order = array_unique(array_merge($_SESSION['products'], $order));
}
$_SESSION['products'] = $order;
}
I've taken a very quick and slightly messy stab at it here. Fundamentally I disagree with the way you're doing things, you should really be thinking about using a more OO approach - but for the sake of getting things done, this should solve your problem and provide a bit more flexibility in future.
Oh and, check this out when you get a chance: http://php.net/manual/en/function.array-unique.php
Your array_unique(array_merge... code would have merged all products that had the same quantity and you would have lost products from the array. :)
Any questions, fire them over.
// im assuming you've called this somewhere already:
// session_start();
// store the initial details
$quantity = $_POST['quantity'];
$total = $the_price_is * $quantity; // want to be able to send $total at same time
// build multi-dimensional order array
$order = array(
$_POST['dryer'] => array('quantity' => $_POST['quantity'], 'total' => $total)
);
// merge any session products into the order array if necessary
if (isset($_SESSION['products']) && is_array($_SESSION['products']) ) foreach ($_SESSION['products'] as $name => $details) {
// add quantity and total if the 'product' is already in the session
if (isset($order[$name])) {
$order[$name]['quantity'] += $details['quantity'];
$order[$name]['total'] += $details['total'];
} else $order[$name] = $details;
}
// replace session products with newly built order array
$_SESSION['products'] = $order;