Displaying Coupons - php

So I have this MySQL table where an item has a field called isCoupon. The default is set to 0 if the seller does not make the item available for coupon use. Each item is ordered by ID and in the shop, there can be more than one coupon where the item is also available for discount. But how do I make it that those coupons display when the item is included? How do I make it that the buyer gets to pick which coupon to use? And how do I calculate the new price if I put "50% off" on the record instead of 0.5?
Table Coupon
couponCode | items | discount
------------------------------
SAMPLE123 | 1 | 50% off
SAMPLE234 | 2,3 | 40% off
SAMPLE345 | 1,5 | 25% off
Table Item
itemID | isCoupon
-----------------
1 | 1
2 | 1
3 | 1
4 | 0
5 | 1
Thanks!

Try the below. As for the buyer picking to choose which coupon, you should let the buyer select the item first and then go to the checkout page by selecting the coupon.
$num_items = 5;
// the below array is used to store the coupons you can use for the item so you can
// proceed with it to the checkout page, there you can make a select dropdown to let
// the buyer select which coupon to use
$coupon_use = array();
for($i = 0; $i < $num_items; $i++) {
// check for current item
$SQL = "SELECT * FROM item WHERE itemID = '$i'";
$result = mysqli_query($connect, $SQL);
$field = mysqli_fetch_assoc($result);
// check if there is a coupon for the current item
if($field['isCoupon'] == 1) {
$SQL2 = "SELECT * FROM coupon";
$result2 = mysqli_query($connect, $SQL2);
// while method to go through every single coupon
while($field2 = mysqli_fetch_assoc($result2)) {
// if you put commas, you can use the explode method
// to store all the items for that coupon and use it to
// check for that current item
$coupons = explode(',', $field2['items']);
if(in_array($i, $coupons)) {
// do your items have a price?
// salePrice is the new price
// thePrice is the old price you need to get with $field (not $field2)
if($field2['discount'] == '50% off') { $salePrice = $thePrice * 0.5; }
else if($field2['discount'] == '40% off') { $salePrice = $thePrice * 0.6; }
else if($field2['discount'] == '25% off') { $salePrice = $thePrice * 0.75; }
// add the coupon code to the array of coupons available for use
array_push($coupon_use, $field2['couponCode']);
// display the prices
echo 'ITEM #'.$i.'<br><s>$'.$thePrice.'</s><br>$'.$salePrice.'<br><br>';
}
}
}
else { echo 'ITEM #'.$i.'$'.$thePrice; }
}
Now you can store the values of the coupon_use array to the checkout page.

Related

Fifo inventory in codeigniter

I'm new to CodeIgniter. I'm trying to update the quantity of the table based on FIFO. I'm making a stock take page, if we count the physical item less than what the table has, we will reconcile and this will update the inventory table and the discard table. Updating inventory table is easy and I've done but I want to update the discard table's quantity based on FIFO. What I want is for example the quantity of item A in inventory table is 50 but when we count it physically it's 35, so when we reconcile, it should minus 15 from the discard table quantity.
Items
Qty
Date
Item A
5
2022-8-22
Item A
4
2022-8-22
Item A
9
2022-8-22
After update it should be like:
| Items | Qty | Date |
|:--------|:------:| --------:|
| Item A | 0 | 2022-8-22|
| Item A | 0 | 2022-8-22|
| Item A | 3 | 2022-8-22|
Please help me. If you need further clarification, do let me know. Thanks in advance
public function update_complete(){
$stock_diff = $this->input->post('stock_diff');
$counted_stock_value = $this->input->post('counted_stock_value');
$cost_diff = $this->input->post('cost_diff');
$reconcile = $this->input->post('reconcile');
$barcode = $this->input->post('barcode');
$stk_id = $this->input->post('stk_id');
for ($i = 0; $i < count($barcode); $i++)
{
$data = array(
'stocktake_value' => $counted_stock_value[$i],
'stock_diff' => $stock_diff[$i],
'cost_diff' => $cost_diff[$i],
'status' => $reconcile[$i]
);
// Commented for testing
$this->db->where('stk_id', $stk_id);
$this->db->where('barcode', $barcode[$i]);
$this->db->update('stocktake_trans', $data);
$itemResult = $this->item_model->getStockdiscardTransByBarcodeNew($barcode[$i]);
foreach($itemResult as $item)
{
$rest = $stock_diff[$i];
if($rest > 0)
{
if($item['quantity'] >= $rest)
{
$rest = $item['quantity']-=$rest;
//$rest = 0;
echo $rest;
}
else
{
$item['quantity'] = 0;
$rest = $rest - $item['quantity'];
}
$this->db->where('barcode', $barcode[$i]);
$this->db->update('stockdiscard_trans', array('quantity' => $rest));
}
}
}
// Update Stock Take
$data1 = array(
'reconciled_by' => $this->session->userdata('name'),
'reconciled_at' => date('Y-m-d')
);
$this->db->where('id', $stk_id);
$this->db->update('stocktake', $data1);
// Set message
$this->session->set_flashdata('stocktake_reconciled', 'Stock Take has been Reconciled!');
//redirect('stocktake/complete');
}
I understand you want to store the difference between the old stock and the new stock.
You can store the original quantity in a variable, update the product with the new value, and then do the difference between the original quantity and the new quantity. Finally, you store the difference in the discard table.
Is what I understood correct?
Edit 1:
Something like this?
$itemsModel = model('App\Models\itemsModel');
$totalDB = $itemsModel->where('Items', 'Item A')->select('sum(Qty)')->first(); // let say 50
$totalMag = 35;
$rest = $totalDB - $totalMag; // rest 50-35 = 15
$itemResult = $itemsModel->where('Items', 'Item A')->findAll();
foreach($itemResult as $item)
{
if($rest > 0)
{
if($item->Qty >= $rest)
{
$item->Qty -= $rest;
$rest = 0;
}
else
{
$item->Qty = 0;
$rest = $rest - $item->Qty;
}
$item->save();
}
}
Backtesting:
-remaining qty 15
5 >= 15? - FALSE
Qty = 0
Rest = 10
4 >= 10 FALSE
Qty = 0
Rest = 6
9 >= 6 TRUE
Qty = 9-6 = 3
Rest = 0
But you need to manage, for what will happen if the remaining stock of products will be more than 0 and the quantity of products A will be 0.
Lets say we have remaining qty to 19
5 >= 19? False
Qty = 0
Rest = 14
4 >= 14? False
Qty = 0
Rest = 10
9 >= 10? False
Qty = 0
Rest = 1
What will happen for the rest = 1 when all item in our table have 0 Qty?

How to check every row of a table to continue my loop?

I'm stuck with this problem because my loop stops at only the first row of the table. Every customer has a set budget for purchasing products which resets every week to purchase items if ever the qty is not equal to 0. The admin is the one who can process the order for the customer. Customers have a budget = 1000 from customers table. Then customer_product table has the qty of products to be purchased by the customer. For example product_id = 1 has a price of 20 and has the qty of 10 so 20 x 10 = 200. Budget would be deducted by 200, remaining budget would be 800 after looping through the first row. Now i want to continue looping through the 2nd row with the remaining 800 budget instead of the 1000. It continues to loop as long as he still has a budget.
Database tables
customer
id | name | budget
customer_product
product_id | cus_id | qty | status
products
id | name | price
Controller
public function processOrder($id)
{
$customers = Customer::find($id);
foreach ($customers->products as $product)
{
$status = $product->pivot->status;
$budget = $product-budget;
$price = $product->price;
$qty = $product->pivot->qty;
if ($status == 1) {
$i = $qty;
for ($i; $i > 0; $i--) {
if ($budget < 1) {
break;
} else {
$budget-=$price;
}
}
};
echo "Status 0";
}
}
Routes
Route::get('processOrder/{id}', ['as' => 'processOrder',
'uses' => 'AdminController#processOrder']);
I can process the first row of the table and when it reaches 0 qty with my for loop, it stops there and doesn't continue to process the next row even though his budget is still enough to purchase products from the next row. Can someone please help me with this problem?
You should save the customer's budget before going into the loop, then update it while you iterate through the products.
public function processOrder($id)
{
$customer = Customer::find($id);
$remainingBudget = $customer->budget;
foreach ($customer->products as $product) {
// Calculate the total price to get the desired qty of product
$cost = $product->price * $product->pivot->qty;
// If we have enough remaining budget go ahead with the purchase
if ($product->pivot->status == 1 && $remainingBudget >= $cost) {
// Decrease the remaining budget
$remainingBudget -= $cost;
}
}
}
You are forcing the loop to break at the very first index
echo "Status 0"; break;
So remove break; at the end.
update:
foreach($customers->products as $product){
$status = $product->pivot->status;
$budget = $product-budget;
$price = $product->price;
$qty = $product->pivot->qty;
if($status == 1){
do {
if($budget < 1) break;
$budget -=$price;
} while ($qty != 0);
}
}

Buy/Sell profit tracking via FIFO stack in PHP

I need to implement an algorythm that can keep track of profits for a list of individual item transactions and update the 'profit' table. The idea is to fetch items bought and cross-reference them with items sold, purely by order (i.e no individual instancing of individual items exists, there are only IDs for item types). So, say we have a table with this data:
items:
item id item type
1 red box
2 blue box
3 white box
transactions:
item id -- quantity -- transaction_type -- price_unit($) -- time
1 3 buy 20 2015-10-10
3 1 buy 10 2015-10-11
1 1 sell 25 2015-10-12
1 1 sell 20 2015-11-14
3 1 sell 15 2015-11-13
For this example my profit table should look like:
item_id -- quantity -- profit -- timestamp_bought ---timestamp_sold
1 1 (25-20)=5 2015-10-10 2015-10-12
1 1 (20-20)=0 2015-10-10 2015-11-14
3 1 (15-10)=5 2015-10-11 2015-11-13
This is what I have so far. It works until several different buy/sell quantities come into play...
$buy_list = mysqli_query($con, "SELECT * FROM transaction WHERE
transaction_type = 'Buy' ORDER BY time DESC");
$sell_list = mysqli_query($con, "SELECT * FROM transaction WHERE
transaction_type = 'Sell' ORDER BY time DESC");
while($row = mysqli_fetch_array($buy_list))
{
array_push($buy_stack, array(
$row['idtrans'],
$row['iditem'],
$row['quantity'],
$row['time'],
$row['price_unit']));
}
while($row = mysqli_fetch_array($sell_list))
{
array_push($sell_stack, array(
$row['idtrans'],
$row['iditem'],
$row['quantity'],
$row['time'],
$row['price_unit']));
}
$size_buy = sizeof($buy_stack);
$size_sell = sizeof($sell_stack);
for($i=0; $i<=$size_buy-1; $i++) //iterate BUY orders
{
$idtrans_b = $buy_stack[$i][0];
$itemid_b = $buy_stack[$i][1];
$quantity_b = $buy_stack[$i][2];
$time_b = $buy_stack[$i][3];
$price_unit_b = $buy_stack[$i][4];
$quantity_b_calc = $buy_stack[$i][2];
for($k=0; $k<=$size_sell-1; $k++)
{
$idtrans_s = $sell_stack[$k][0];
$itemid_s = $sell_stack[$k][1];
$quantity_s = $sell_stack[$k][2];
$time_s = $sell_stack[$k][3];
$price_unit_s = $sell_stack[$k][4];
if($itemid_s == $itemid_b &&
$time_s > $time_b &&
$quantity_b > 0
&& $quantity_s >= $quantity_b) //match
{
$sell_stack[$k][1] = "done_sell";
$buy_stack[$i][1] = "done_buy";
$profit_unit = $price_unit_s - $price_unit_b;
$profit_ quantity = min($quantity_s, $quantity_b);
$quantity_b = $quantity_b - $profit_quantity;
$time_bought = $buy_stack[$i][3];
$time_sold = $sell_stack[$k][3];
$add_profit = mysqli_query
($con, "INSERT INTO profit (id, transaction_buy, transaction_sell, profit_unit, quantity, timestamp_buy, timestamp_sell)
VALUES ( 'null', '$idtrans_b', '$idtrans_s', '$profit_unit', '$profit_quantity', $time_bought, $time_sold));
}
}
}
I'm stuck to get this working properly. Should I scrap this and do it with stacks instead?

Retrieve shopping cart items from database

I'm trying to implement a shopping cart for my website. My page loops through products in my database and displays them on the page with an 'Add' button. You can only add an item if you are logged in.
Products Table
| ID | Name | Price | Quantity | description | image_name |
Once you add an item it stores this in my cart table. The 'CartProduct int' is the same as the 'ID' in my products table.
Cart table
| CartID | CartProduct | ProductCount | UniqueID | Username | Date
If you click Add on the same product, the ProductCount will increment.
So if TestUser adds CartProduct 1 & 2 and 2 again.
I'm really unsure on how to display all products WHERE username 'TestUser' and I also need ProductCount * Price.
At the moment I'm trying to loop through each CartProduct for the logged in user, then select the ID from products table WHERE ID = CartProduct (as they are the same). I can then grab the price and details of that product.
At the moment I am selecting from cart where username = username that is logged in. Just so I can see the outcome, I am displaying it.
$sql = "SELECT cartProduct FROM cart WHERE username ='" . $name . "'";
$result = mysql_query($sql);
$c = 0;
$n = 2; // Each Nth iteration would be a new table row
while ($db_field = mysql_fetch_assoc($result)) {
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$productNo = $row['cartProduct'];
if ($c % $n == 0 && $c != 0) { // If $c is divisible by $n...
echo '<div class="row" ></div>';
}
$c++;
echo "<br>Count: " .$c;
?>
<h2> <?php echo "Product No: " . $productNo ?> </a></h2>
<?php
I add 3 items to the cart. CartProduct 1, 2, 2 :- for the output I keep getting:
Product No: 1
Product No: 1
I should see Product 1 and then Product 2?
Am I making this more complicated than it should be, and are my tables correct?
Is there an easier way?
Many thanks for any replies!
First, in Cart Table change Username to UserId.
The next one step is modify sql query at "JOIN products" to get connect with Products Table and easly get a product price.
But in general, use PDO driver to get more safeties and clearlies queries and PHP code. Read about relations in DB (RDBM).

Need help on some logic to perform mysql insert query?

I'm developing a shopping cart using php, now I stuck at some point as follow.
There are tables like: customers, products, orders, order_detail
products table:
id | name | quantity
order_detail table:
order_id | product_id | quantity
I completely done for add product to cart and customer can submit the order to database, admin can remove or delete orders from backend and customers can remove orders list or delete orders from frontend if that ordered still not confirm payment.
Example:
"customer1" order 10 products, order ID is #907987899 and "product1" customer1 order quantity = 2, "product2" customer1 order quantity = 5 and so on.....
if the ordered still not confirm then customer still can remove product from the ordered list, and also can delete the entire ordered.
My problem now is: if Customers or Admin cancel or delete the ordered that still not confirm payment then I want to return product quantity from order_detail table list back to products table. by the time when customer submitted the order then product quantity is subtract from product table.
Here is my code that return quantity back to products:
require '../../init.php';
require $ROOT . '/functions/basic.php';
if(isset($_POST['id']))
{
$id = htmlspecialchars($_POST['id']);
$delete = dbQuery("DELETE FROM orders WHERE order_id = '$id'");
if($delete == true)
{
//unlink($ROOT . '/upload/products/' . $image);
$select_product = dbAll("SELECT product_id, quantity FROM order_detail WHERE order_id = '$id'");
foreach($select_product as $product)
{
$quantity = $product['quantity'];
$product_id = $product['product_id'];
$return_product_quantity = dbQuery("UPDATE products SET quantity = (quantity + $quantity) WHERE product_id = $product_id");
}
if($return_product_quantity == true)
{
$delete_order_detail = dbQuery("DELETE FROM order_detail WHERE order_id = '$id'");
if($delete_order_detail == true)
{
echo "OK";
}
else
{
echo "Can't delete order detail information";
}
}
}
else
{
echo "Can't delete order row";
}
}
but the query it seem not work as my required, so please help me how to handle this kind of logic to perform my required.
Thanks in advance.
You are trying to use the variable quantity in your UPDATE even though it has no value. Try this instead:
$return_product_quantity = dbQuery("UPDATE products
SET quantity = ((SELECT quantity FROM products WHERE product_id = $product_id) + $quantity)
WHERE product_id = $product_id");

Categories