Skip to content

fix the bug #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 0 additions & 18 deletions backend/orders_dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,21 +81,3 @@ def get_all_orders(connection):
if __name__ == '__main__':
connection = get_sql_connection()
print(get_all_orders(connection))
# print(get_order_details(connection,4))
# print(insert_order(connection, {
# 'customer_name': 'dhaval',
# 'total': '500',
# 'datetime': datetime.now(),
# 'order_details': [
# {
# 'product_id': 1,
# 'quantity': 2,
# 'total_price': 50
# },
# {
# 'product_id': 3,
# 'quantity': 1,
# 'total_price': 30
# }
# ]
# }))
14 changes: 13 additions & 1 deletion backend/products_dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@

def get_all_products(connection):
cursor = connection.cursor()
query = ("select products.product_id, products.name, products.uom_id, products.price_per_unit, uom.uom_name from products inner join uom on products.uom_id=uom.uom_id")
query = """
SELECT
p.product_id,
p.name AS product_name,
p.uom_id,
p.price_per_unit,
u.uom_name
FROM
products AS p
INNER JOIN
uom AS u ON p.uom_id = u.uom_id
"""
cursor.execute(query)
response = []
for (product_id, name, uom_id, price_per_unit, uom_name) in cursor:
Expand All @@ -13,6 +24,7 @@ def get_all_products(connection):
'price_per_unit': price_per_unit,
'uom_name': uom_name
})
cursor.close()
return response

def insert_new_product(connection, product):
Expand Down
90 changes: 53 additions & 37 deletions backend/server.py
Original file line number Diff line number Diff line change
@@ -1,67 +1,83 @@
from flask import Flask, request, jsonify
from flask import Flask, request, jsonify , render_template
from flask_cors import CORS
from sql_connection import get_sql_connection
import mysql.connector
import json

import products_dao
import orders_dao
import uom_dao

app = Flask(__name__)
CORS(app)

connection = get_sql_connection()

@app.route('/getUOM', methods=['GET'])
def get_uom():
response = uom_dao.get_uoms(connection)
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin', '*')
return response
try:
response = uom_dao.get_uoms(connection)
return jsonify(response)
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/getProducts', methods=['GET'])
def get_products():
response = products_dao.get_all_products(connection)
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin', '*')
return response
try:
response = products_dao.get_all_products(connection)
return jsonify(response)
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/insertProduct', methods=['POST'])
def insert_product():
request_payload = json.loads(request.form['data'])
product_id = products_dao.insert_new_product(connection, request_payload)
response = jsonify({
'product_id': product_id
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
try:
request_payload = json.loads(request.form['data'])
product_id = products_dao.insert_new_product(connection, request_payload)
return jsonify({'product_id': product_id})
except Exception as e:
return jsonify({'error': str(e)}), 500

# @app.route('/getAllOrders', methods=['GET'])
# def get_all_orders():
# try:
# response = orders_dao.get_all_orders(connection)
# return jsonify(response)
# except Exception as e:
# return jsonify({'error': str(e)}), 500

@app.route('/getAllOrders', methods=['GET'])
def get_all_orders():
response = orders_dao.get_all_orders(connection)
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin', '*')
return response
try:
cursor = connection.cursor()
cursor.execute("SELECT * FROM orders") # Example query
orders = cursor.fetchall()
return jsonify(orders)
except Exception as e:
print(f"Error: {e}") # Log the error for debugging
return jsonify({'error': str(e)}), 500
finally:
cursor.close()

@app.route('/insertOrder', methods=['POST'])
def insert_order():
request_payload = json.loads(request.form['data'])
order_id = orders_dao.insert_order(connection, request_payload)
response = jsonify({
'order_id': order_id
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
try:
request_payload = json.loads(request.form['data'])
order_id = orders_dao.insert_order(connection, request_payload)
return jsonify({'order_id': order_id})
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/deleteProduct', methods=['POST'])
def delete_product():
return_id = products_dao.delete_product(connection, request.form['product_id'])
response = jsonify({
'product_id': return_id
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
try:
return_id = products_dao.delete_product(connection, request.form['product_id'])
return jsonify({'product_id': return_id})
except Exception as e:
return jsonify({'error': str(e)}), 500

@app.route('/ui/manage-product')
def manage_product():
return render_template('manage-product.html')

if __name__ == "__main__":
print("Starting Python Flask Server For Grocery Store Management System")
app.run(port=5000)

app.run(port=5000)
17 changes: 6 additions & 11 deletions backend/sql_connection.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import datetime
import mysql.connector

__cnx = None

def get_sql_connection():
print("Opening mysql connection")
global __cnx

if __cnx is None:
__cnx = mysql.connector.connect(user='root', password='root', database='grocery_store')

return __cnx

try:
__cnx = mysql.connector.connect(user='root', password='H@rshit5093', host='localhost', database='grocery_store') # Update password if necessary
return __cnx
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
45 changes: 34 additions & 11 deletions ui/js/custom/dashboard.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,41 @@
$(function () {
//Json data by api call for order table
// Json data by API call for order table
$.get(orderListApiUrl, function (response) {
if(response) {
var table = '';
var totalCost = 0;
if (response) {
let table = '';
let totalCost = 0;

$.each(response, function(index, order) {
totalCost += parseFloat(order.total);
table += '<tr>' +
'<td>'+ order.datetime +'</td>'+
'<td>'+ order.order_id +'</td>'+
'<td>'+ order.customer_name +'</td>'+
'<td>'+ order.total.toFixed(2) +' Rs</td></tr>';
let totalValue = 0.00;

// Assuming order is an array: [id, customer_name, total, datetime]
if (Array.isArray(order) && order.length >= 4) {
const totalFromArray = order[2]; // Total is the third element
totalValue = parseFloat(totalFromArray); // Convert the string to a number

// Check if totalValue is valid
if (isNaN(totalValue)) {
console.error("Invalid 'total' value for order:", order);
return; // Skip this order if total is invalid
}

// Only add to totalCost if totalValue is valid
if (totalValue > 0) {
totalCost += totalValue;
}

table += `<tr>
<td>${order[3] || ''}</td> <!-- datetime -->
<td>${order[0] || ''}</td> <!-- order_id -->
<td>${order[1] || ''}</td> <!-- customer_name -->
<td>${totalValue.toFixed(2)} Rs</td>
</tr>`;
} else {
console.error("Invalid order format:", order);
}
});
table += '<tr><td colspan="3" style="text-align: end"><b>Total</b></td><td><b>'+ totalCost.toFixed(2) +' Rs</b></td></tr>';

table += `<tr><td colspan="3" style="text-align: end"><b>Total</b></td><td><b>${totalCost.toFixed(2)} Rs</b></td></tr>`;
$("table").find('tbody').empty().html(table);
}
});
Expand Down
5 changes: 5 additions & 0 deletions ui/js/custom/manage-product.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,17 @@ var productModal = $("#productModal");
productModal.on('show.bs.modal', function(){
//JSON data by API call
$.get(uomListApiUrl, function (response) {
console.log(response);
if(response) {
var options = '<option value="">--Select--</option>';
$.each(response, function(index, uom) {
options += '<option value="'+ uom.uom_id +'">'+ uom.uom_name +'</option>';
});
$("#uoms").empty().html(options);
} else {
console.error("No response data received for UOMs.");
}
}).fail(function() {
console.error("Error fetching UOMs from the API.");
});
});