Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Grocery_Management_System_using_Python[1]

python project source code grocery management

Uploaded by

roydeadmanx
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Grocery_Management_System_using_Python[1]

python project source code grocery management

Uploaded by

roydeadmanx
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Creating a using Python, MySQL, and CSV file handling is an excellent way to handle

inventory management, track customer purchases, and generate reports. Below is a step-by-
step guide to building such a system.

Steps to Implement the Grocery Management System:

1. Setting up MySQL Database:


o Create a MySQL database to store grocery product details, customer orders,
and payment records.
o Example schema for the Grocery Management System:

sql
Copy code
CREATE DATABASE grocery_management;

USE grocery_management;

CREATE TABLE products (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
category VARCHAR(100),
price DECIMAL(10, 2),
stock_quantity INT
);

CREATE TABLE customer_orders (


id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255),
product_id INT,
quantity INT,
order_time DATETIME,
payment_status VARCHAR(50),
total_amount DECIMAL(10, 2),
FOREIGN KEY (product_id) REFERENCES products(id)
);

2. Install Required Python Packages:


o Install mysql-connector for MySQL connectivity and pandas for handling
CSV files.

bash
Copy code
pip install mysql-connector pandas

3. Python Script:
o The following Python script handles MySQL connectivity, CSV file
reading/writing, and managing products and customer orders.

Python Code
python
Copy code
import mysql.connector
import pandas as pd
from datetime import datetime
# MySQL Connection
def connect_to_database():
try:
conn = mysql.connector.connect(
host="localhost", # MySQL host
user="root", # MySQL user
password="password", # MySQL password
database="grocery_management" # Database name
)
if conn.is_connected():
print("Successfully connected to the database.")
return conn
except mysql.connector.Error as err:
print(f"Error: {err}")
return None

# Create and Insert Sample Data (Products and Orders)


def create_and_insert_sample_data():
conn = connect_to_database()
if conn is not None:
cursor = conn.cursor()

# Create products table and customer_orders table if they don't


exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
category VARCHAR(100),
price DECIMAL(10, 2),
stock_quantity INT
);
""")

cursor.execute("""
CREATE TABLE IF NOT EXISTS customer_orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255),
product_id INT,
quantity INT,
order_time DATETIME,
payment_status VARCHAR(50),
total_amount DECIMAL(10, 2),
FOREIGN KEY (product_id) REFERENCES products(id)
);
""")

# Insert sample products


cursor.execute("""
INSERT INTO products (name, category, price, stock_quantity)
VALUES
('Milk', 'Dairy', 1.50, 100),
('Bread', 'Bakery', 2.00, 150),
('Eggs', 'Dairy', 3.00, 50),
('Apple', 'Fruits', 2.50, 200),
('Tomato', 'Vegetables', 1.20, 80);
""")

conn.commit()
print("Sample data inserted.")
cursor.close()
conn.close()

# Fetch data from MySQL (Products and Orders)


def fetch_data_from_db():
conn = connect_to_database()
if conn is not None:
cursor = conn.cursor(dictionary=True)

# Fetch products
cursor.execute("SELECT * FROM products;")
products = cursor.fetchall()

print("\nProducts:")
for product in products:
print(product)

# Fetch customer orders


cursor.execute("SELECT * FROM customer_orders;")
orders = cursor.fetchall()

print("\nCustomer Orders:")
for order in orders:
print(order)

cursor.close()
conn.close()

# Export Product and Order Data to CSV


def export_to_csv():
conn = connect_to_database()
if conn is not None:
cursor = conn.cursor(dictionary=True)

# Export Products Data


cursor.execute("SELECT * FROM products;")
products = cursor.fetchall()
products_df = pd.DataFrame(products)
products_df.to_csv("products.csv", index=False)
print("Products data exported to 'products.csv'.")

# Export Orders Data


cursor.execute("SELECT * FROM customer_orders;")
orders = cursor.fetchall()
orders_df = pd.DataFrame(orders)
orders_df.to_csv("orders.csv", index=False)
print("Orders data exported to 'orders.csv'.")

cursor.close()
conn.close()

# Import Data from CSV to MySQL


def import_from_csv():
try:
# Read CSV files
products_df = pd.read_csv('products.csv')
orders_df = pd.read_csv('orders.csv')

# Connect to MySQL database


conn = connect_to_database()
if conn is not None:
cursor = conn.cursor()

# Insert products from CSV


for index, row in products_df.iterrows():
cursor.execute("""
INSERT INTO products (name, category, price,
stock_quantity)
VALUES (%s, %s, %s, %s)
""", (row['name'], row['category'], row['price'],
row['stock_quantity']))

# Insert orders from CSV


for index, row in orders_df.iterrows():
cursor.execute("""
INSERT INTO customer_orders (customer_name, product_id,
quantity, order_time, payment_status, total_amount)
VALUES (%s, %s, %s, %s, %s, %s)
""", (row['customer_name'], row['product_id'],
row['quantity'], row['order_time'], row['payment_status'],
row['total_amount']))

conn.commit()
print("Data imported from CSV to MySQL.")
cursor.close()
conn.close()
except FileNotFoundError:
print("CSV file not found.")
except Exception as e:
print(f"Error: {e}")

# Place a Customer Order


def place_order(customer_name, product_name, quantity):
conn = connect_to_database()
if conn is not None:
cursor = conn.cursor()

# Check if the product is available


cursor.execute("SELECT * FROM products WHERE name = %s;",
(product_name,))
product = cursor.fetchone()

if product and product['stock_quantity'] >= quantity:


# Calculate total amount
total_amount = product['price'] * quantity
order_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

# Insert the customer order into the database


cursor.execute("""
INSERT INTO customer_orders (customer_name, product_id,
quantity, order_time, payment_status, total_amount)
VALUES (%s, %s, %s, %s, %s, %s)
""", (customer_name, product['id'], quantity, order_time,
'Pending', total_amount))

# Update product stock


new_stock_quantity = product['stock_quantity'] - quantity
cursor.execute("""
UPDATE products
SET stock_quantity = %s
WHERE id = %s
""", (new_stock_quantity, product['id']))
conn.commit()
print(f"Order placed for {customer_name}: {quantity} x
{product_name} - Total: {total_amount:.2f}")
else:
print(f"Product '{product_name}' not available in sufficient
quantity.")

cursor.close()
conn.close()

# Update Payment Status after Payment


def update_payment_status(order_id, payment_status):
conn = connect_to_database()
if conn is not None:
cursor = conn.cursor()

# Update the payment status of the order


cursor.execute("UPDATE customer_orders SET payment_status = %s
WHERE id = %s;", (payment_status, order_id))
conn.commit()

if payment_status == "Paid":
print(f"Order {order_id} marked as paid.")
else:
print(f"Payment for order {order_id} is pending.")

cursor.close()
conn.close()

# Main Menu to execute functions


def main():
while True:
print("\nGrocery Management System")
print("1. Place an Order")
print("2. Update Payment Status")
print("3. Fetch Data from Database")
print("4. Export Data to CSV")
print("5. Import Data from CSV")
print("6. Create and Insert Sample Data")
print("7. Exit")

choice = input("Enter your choice: ")

if choice == '1':
customer_name = input("Enter customer name: ")
product_name = input("Enter product name: ")
quantity = int(input("Enter quantity: "))
place_order(customer_name, product_name, quantity)
elif choice == '2':
order_id = int(input("Enter order ID: "))
payment_status = input("Enter payment status (Paid/Pending): ")
update_payment_status(order_id, payment_status)
elif choice == '3':
fetch_data_from_db()
elif choice == '4':
export_to_csv()
elif choice == '5':
import_from_csv()
elif choice == '6':
create_and_insert_sample_data()
elif choice == '7':
break
else:
print("Invalid choice! Please try again.")

if __name__ == "__main__":
main()

Explanation:

1. Database Setup:
o The script creates a grocery_management database with products and
customer_orders tables.
o products stores information about grocery items such as name, category,
price, and stock quantity.
o customer_orders stores customer orders, including the customer’s name,
product ID, quantity, order time, payment status, and total amount.
2. Features:
o Place an Order: Customers can place orders for grocery items. The system
checks for stock availability and updates the stock quantity accordingly.
o Update Payment Status: The system allows updating the payment status for
orders (e.g., "Paid" or "Pending").
o Export/Import Data: The system can export product and order data to CSV
files and import data from CSV files.
o Sample Data: The script can insert sample product data into the database for
testing purposes.
3. CSV Handling:
o The system supports exporting and importing product and order data to/from
CSV files using pandas.

Example Output:

1. Place an Order:

mathematica
Copy code
Order placed for John Doe: 3 x Milk - Total: 4.50

2. Export Data:

kotlin
Copy code
Products data exported to 'products.csv'.
Orders data exported to 'orders.csv'.

3. Fetch Data from Database:

css
Copy code
Products:
{'id': 1, 'name': 'Milk', 'category': 'Dairy', 'price': 1.5,
'stock_quantity': 100}
Customer Orders:
{'id': 1, 'customer_name': 'John Doe', 'product_id': 1, 'quantity':
3, 'order_time': '2024-11-09 10:00:00', 'payment_status': 'Pending',
'total_amount': 4.50}

How to Test:

1. Database Setup: Create the grocery_management database and tables in MySQL.


2. Run the Script: Run the script and interact with the menu.
3. Place Orders: Test placing orders and updating payment statuses.
4. Export and Import: Test exporting and importing data to/from CSV.

This grocery management system can effectively handle inventory and customer orders, and
allows easy integration with CSV files for reporting and backups.

You might also like