0% found this document useful (0 votes)
29 views8 pages

Example

Uploaded by

chrisnaorem12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views8 pages

Example

Uploaded by

chrisnaorem12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

import pymysql

from tabulate import tabulate

from datetime import datetime

# Connect to the database

def connect_to_db():

return pymysql.connect(host="localhost",

user="root",

password="chris123",

database="inventory")

# Add a new product

def add_product():

conn = connect_to_db()

cursor = conn.cursor()

name = input("Enter product name: ").strip()

category = input("Enter category: ").strip()

try:

price = float(input("Enter price: "))

stock = int(input("Enter stock quantity: "))

query = "INSERT INTO products (name, category, price, stock) VALUES (%s, %s, %s, %s)"

cursor.execute(query, (name, category, price, stock))

conn.commit()

print("✅ Product added successfully!")

except ValueError:
print("❌ Invalid input for price or stock.")

finally:

conn.close()

# View all products

def view_products():

conn = connect_to_db()

cursor = conn.cursor()

cursor.execute("SELECT * FROM products")

results = cursor.fetchall()

if results:

print(tabulate(results, headers=["ID", "Name", "Category", "Price", "Stock"], tablefmt="grid"))

else:

print("⚠️No products found.")

conn.close()

# Search for a product by name or category

def search_products():

conn = connect_to_db()

cursor = conn.cursor()

search_term = input("Enter product name or category to search: ").strip()

query = "SELECT * FROM products WHERE name LIKE %s OR category LIKE %s"

cursor.execute(query, (f"%{search_term}%", f"%{search_term}%"))

results = cursor.fetchall()

if results:
print(tabulate(results, headers=["ID", "Name", "Category", "Price", "Stock"], tablefmt="grid"))

else:

print("⚠️No matching products found.")

conn.close()

# Update product details

def update_product():

conn = connect_to_db()

cursor = conn.cursor()

try:

product_id = int(input("Enter product ID to update: "))

print("1. Update Name\n2. Update Category\n3. Update Price\n4. Update Stock")

choice = input("Enter your choice: ")

if choice == "1":

new_name = input("Enter new name: ")

cursor.execute("UPDATE products SET name = %s WHERE product_id = %s", (new_name,


product_id))

elif choice == "2":

new_category = input("Enter new category: ")

cursor.execute("UPDATE products SET category = %s WHERE product_id = %s", (new_category,


product_id))

elif choice == "3":

new_price = float(input("Enter new price: "))

cursor.execute("UPDATE products SET price = %s WHERE product_id = %s", (new_price,


product_id))

elif choice == "4":

new_stock = int(input("Enter new stock quantity: "))


cursor.execute("UPDATE products SET stock = %s WHERE product_id = %s", (new_stock,
product_id))

else:

print("❌ Invalid choice!")

conn.close()

return

conn.commit()

print("✅ Product updated successfully!")

except ValueError:

print("❌ Invalid input for ID, price, or stock.")

finally:

conn.close()

# Delete a product

def delete_product():

conn = connect_to_db()

cursor = conn.cursor()

try:

product_id = int(input("Enter product ID to delete: "))

cursor.execute("DELETE FROM products WHERE product_id = %s", (product_id,))

conn.commit()

print("✅ Product deleted successfully!")

except ValueError:

print("❌ Invalid input for product ID.")

finally:

conn.close()
# Record a sale

def record_sale():

conn = connect_to_db()

cursor = conn.cursor()

try:

product_id = int(input("Enter product ID: "))

quantity = int(input("Enter quantity sold: "))

sale_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

cursor.execute("SELECT stock FROM products WHERE product_id = %s", (product_id,))

result = cursor.fetchone()

if result and result[0] >= quantity:

cursor.execute("UPDATE products SET stock = stock - %s WHERE product_id = %s", (quantity,


product_id))

cursor.execute("INSERT INTO sales (product_id, quantity, sale_date) VALUES (%s, %s, %s)",
(product_id, quantity, sale_date))

conn.commit()

print("✅ Sale recorded successfully!")

else:

print("❌ Insufficient stock!")

except ValueError:

print("❌ Invalid input for product ID or quantity.")

finally:

conn.close()

# View sales history


def view_sales():

conn = connect_to_db()

cursor = conn.cursor()

cursor.execute("SELECT sales.sale_id, products.name, sales.quantity, sales.sale_date FROM sales JOIN


products ON sales.product_id = products.product_id")

results = cursor.fetchall()

if results:

print(tabulate(results, headers=["Sale ID", "Product Name", "Quantity", "Sale Date"],


tablefmt="grid"))

else:

print("⚠️No sales records found.")

conn.close()

# Generate sales report

def generate_report():

conn = connect_to_db()

cursor = conn.cursor()

cursor.execute("SELECT products.name, SUM(sales.quantity) AS total_quantity, SUM(sales.quantity *


products.price) AS total_revenue FROM sales JOIN products ON sales.product_id = products.product_id
GROUP BY products.name")

results = cursor.fetchall()

if results:

print(tabulate(results, headers=["Product Name", "Total Quantity Sold", "Total Revenue"],


tablefmt="grid"))

else:

print("⚠️No sales data available.")

conn.close()
# Main menu

def main_menu():

while True:

print("\t\t📦 INVENTORY MANAGEMENT SYSTEM 📦")

print("\t\t==================================\n")

print("\t\t\t\t MAIN MENU")

print("\t\t\t\t =========\n")

print("\t1. Add Product \t 2. View Products \n")

print("\t3. Search Products \t 4. Update Product \n")

print("\t5. Delete Product \t 6. Record Sale \n")

print("\t7. View Sales History \t8. Generate Sales Report \n")

print("\t9. Exit")

choice = input("\nEnter your choice: ")

if choice == "1":

add_product()

elif choice == "2":

view_products()

elif choice == "3":

search_products()

elif choice == "4":

update_product()

elif choice == "5":


delete_product()

elif choice == "6":

record_sale()

elif choice == "7":

view_sales()

elif choice == "8":

generate_report()

elif choice == "9":

print("Exiting system...")

break

else:

print("❌ Invalid choice! Please try again.")

if __name__ == "__main__":

main_menu()

You might also like