0% found this document useful (0 votes)
5 views35 pages

GobhiMart: Retail Management System

GobhiMart is a retail management system designed for small to medium-sized stores, utilizing a Python-based CLI and a MySQL database for inventory and transaction management. It features a dual-mode architecture for managers and customers, with secure password authentication and a structured product categorization. The system includes various user-defined functions for operations such as stock management, price adjustments, and sales reporting.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views35 pages

GobhiMart: Retail Management System

GobhiMart is a retail management system designed for small to medium-sized stores, utilizing a Python-based CLI and a MySQL database for inventory and transaction management. It features a dual-mode architecture for managers and customers, with secure password authentication and a structured product categorization. The system includes various user-defined functions for operations such as stock management, price adjustments, and sales reporting.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION

GobhiMart is a robust retail management system designed to streamline


operations for small to medium-sized stores. It leverages a command-line
interface (CLI) built with Python to provide an accessible and functional user
experience, underpinned by a highly structured MySQL database for all
inventory, sales, and transaction records.

The system is fundamentally built on the Python programming language for


its application logic and user interface. For persistent data storage, MySQL is
employed, managing critical information such as product inventory and sales
history. The connectivity between the Python application and the MySQL
database is managed via the [Link] library, ensuring reliable and
secure data operations.
GobhiMart operates using a dual-mode architecture, catering to the two
primary users of a retail system: the Manager and the Customer. Access to
both modes is secured through a robust password authentication mechanism,
protecting sensitive management data and ensuring a personalized shopping
experience.
The product structure is organized into five distinct categories: Electronics,
Clothing, Books, Home & Garden, and Sports. A crucial architectural decision
was to create separate product and sales tables for each category (e.g.,
electronics_products, electronics_sales). This design choice optimizes query
performance, simplifies maintenance, and allows for category-specific data
management and reporting.
About PYTHON

Python is a high-level, general-purpose programming


language. Its design philosophy emphasizes code
readability with the use of significant indentation. Python
is dynamically type-checked and garbage-collected. It
supports multiple programming paradigms, including
structured ,object-oriented and functional programming.
Guido van Rossum began working on Python in the late
1980s as a successor to the ABC programming
language. Python 3.0, released in 2008, was a major
revision and not completely backward-compatible with
earlier versions.

Beginning with Python 3.5, capabilities and keywords


for typing were added to language, allowing optional
static typing. Currently only versions in the 3.x series
are supported. Python has gained widespread use in
the machine learning community. It is widely taught as
an introductory programming language. Since 2003,
Python has consistently ranked in the top ten of the
most popular programming languages in the TIOBE
Programming Community
About MySQL

MySQL is an open-source relational database


management system (RDBMS). Its name is a
combination of "My", the name of co-founder Michael
Widenius's daughter My, and "SQL", the acronym for
Structured Query Language. SQL is a language that
programmers use to create, modify and extract data
from the relational database, as well as control user
access to the database. In addition to relational
databases and SQL, an RDBMS like MySQL works with
an operating system to implement a relational database
in a computer's storage system, manages users, allows
for network access and facilitates testing database
integrity and creation of backups.
MySQL is free and open-source software under the
terms of the GNU General Public License, and is also
available under a variety of proprietary licenses. MySQL
is a component of the LAMP web application software
stack (and others), which is an acronym for Linux,
Apache, MySQL, Perl/PHP/Python. MySQL is used by
many database-driven web applications, and by many
popular websites
Hardware And Software Required

Hardware Requirements :-
1. Processor: Minimum Dual-core processor (Intel/AMD).
Recommended: Core i3 or higher.
2. RAM: At least 4 GB. Recommended: 8 GB for smooth execution of
Python + MySQL.
3. Storage: Minimum 1 GB free space. MySQL requires additional
space for databases.
4. Monitor: Any standard display to view the interface and output.
5. Keyboard & Mouse: For input operations during registration and
login.
The hardware requirements ensure that the system can handle both
Python execution and MySQL database operations without lag.

Software Requirements :-

2. 1. Operating System: Windows 10/11, Linux, or macOS.


2. Python Interpreter: Version 3.x installed.
3. MySQL Server: MySQL 5.7 or 8.0 for managing databases.
4. MySQL Connector/Python: Required for connecting Python
programs to MySQL.
5. Text Editor / IDE: VS Code, PyCharm, or IDLE for writing and
running the Python program.
All User-Defined Functions in GobhiMart

1.`slow_print(text, delay=0.05)`
- Prints text character by character with a delay

2. show_product_list(cursor, category_to_table)`
- Displays all products across all categories in a formatted
table

3. view_stock_and_sales(cursor, conn, category_to_table)`


- Displays stock levels, sales information, and profit for all
products

4. `manager_view_stock(cursor, category_to_table)`
- Displays stock inventory in tabular format for manager

5. `manager_change_password()`
- Allows manager to change the customer entry password

6. `manager_change_price(cursor, conn, category_to_table)


- Allows manager to change product prices

7. `authenticate_manager()`
- Authenticates manager and returns True if successful

8. authenticate_customer()`
- Authenticates customer and returns True if successful

9. manager_mode(cursor, conn, category_to_table)`


- Manager mode menu and operations. Returns 'switch' to
switch mode, 'exit' to exit program, or None to continue

10. print_receipt(customer_name, phone_number, address,


cart, subtotal, payment_method, transaction_id)
- Prints a detailed receipt with cost breakdown and
customer information

11. `shopping(cursor, conn, category_to_table)`


- Handles the shopping flow (browse, add to cart, checkout,
payment)

12. `main()`
- Main entry point: initializes database, creates tables,
seeds data, and runs the main program loop

13. `cleanup(cursor, conn)`


- Closes database cursor and connection

Total: 13 user-defined functions


Modules Used in GobhiMart

1. sys
- Used for `[Link]()` and `[Link]()` in
`slow_print()`, and `[Link]()` for program termination

2. getpass
- Used for secure password input with `[Link]()` in
authentication functions

3. datetime)
- Used for `[Link]()` to get current date/time for
receipts and sales records

4. time
- Used for `[Link]()` to add delays in the `slow_print()`
function

5. [Link]
- Used for MySQL database connectivity
- Provides `[Link]()` for database
connections
- Handles database operations and error handling
Source Code

import sys
import getpass
from datetime import datetime
import [Link]
import time

# Global variable to store customer password (can be changed by manager)


CUSTOMER_PASSWORD = "omijebhabha"

def slow_print(text, delay=0.05):


"""Print text character by character with a delay"""
for char in text:
[Link](char)
[Link]()
[Link](delay)
print()

def show_product_list(cursor, category_to_table):


"""Display all products across all categories"""
print("\n" + "=" * 80)
print("PRODUCT LIST")
print("=" * 80)

for cat, table in category_to_table.items():


print(f"\n{cat}:")
print("-" * 80)

# Get all products in this category


[Link](f"SELECT id, name, price, stock FROM {table} ORDER BY name")
products = [Link]()

if not products:
print(" No products in this category.")
continue

print(f"{'Product Name':<30} {'Price':<15} {'Stock':<10}")


print("-" * 80)

for pid, name, price, stock in products:


print(f"{name:<30} ${price:<14.2f} {stock:<10}")
print("\n" + "=" * 80)

def view_stock_and_sales(cursor, conn, category_to_table):


"""Display stock levels, sales information, and profit for all products"""
print("\n" + "=" * 100)
print("STOCK, SALES AND PROFIT REPORT")
print("=" * 100)

total_revenue_all = 0.0
total_cost_all = 0.0
total_profit_all = 0.0

for cat, table in category_to_table.items():


print(f"\n{cat}:")
print("-" * 100)

# Get all products in this category with cost information


[Link](f"SELECT id, name, price, cost, stock FROM {table} ORDER BY
name")
products = [Link]()

if not products:
print(" No products in this category.")
continue

print(f"{'Product Name':<25} {'Price':<12} {'Cost':<12} {'Stock':<10} {'Sales':<10}


{'Revenue':<12} {'Profit':<12}")
print("-" * 100)

# Track category totals


cat_revenue = 0.0
cat_cost = 0.0
cat_qty_sold = 0
cat_transactions = 0

for pid, name, price, cost, stock in products:


# Get sales information for this product
sales_table = f"sales_{table}"
[Link](
f"SELECT SUM(quantity), SUM(total_price), COUNT(*) FROM
{sales_table} WHERE product_id = %s",
(pid,)
)
sales_result = [Link]()

if sales_result and sales_result[0]:


qty_sold = int(sales_result[0])
revenue = float(sales_result[1]) if sales_result[1] else 0.0
product_cost = float(cost) * qty_sold
profit = revenue - product_cost
transactions = int(sales_result[2]) if sales_result[2] else 0

# Update category totals


cat_qty_sold += qty_sold
cat_revenue += revenue
cat_cost += product_cost
cat_transactions += transactions
else:
qty_sold = 0
revenue = 0.0
profit = 0.0

total_revenue_all += revenue
total_cost_all += (float(cost) * qty_sold)
total_profit_all += profit

print(f"{name:<25} ${price:<11.2f} ${cost:<11.2f} {stock:<10} {qty_sold:<10}


${revenue:<11.2f} ${profit:<11.2f}")

# Display category summary


cat_profit = cat_revenue - cat_cost
if cat_transactions > 0:
print(f"\n Category Summary: {cat_transactions} transactions, {cat_qty_sold}
units sold, ${cat_revenue:.2f} revenue, ${cat_profit:.2f} profit")
else:
print(f"\n Category Summary: No sales recorded yet")

print("\n" + "=" * 100)


print(f"TOTAL SUMMARY:")
print(f" Total Revenue: ${total_revenue_all:.2f}")
print(f" Total Cost: ${total_cost_all:.2f}")
print(f" Total Profit: ${total_profit_all:.2f}")
print("=" * 100)

def manager_view_stock(cursor, category_to_table):


"""Display stock in tabular format for manager"""
print("\n" + "=" * 80)
print("CURRENT STOCK INVENTORY")
print("=" * 80)

for cat, table in category_to_table.items():


print(f"\n{cat}:")
print("-" * 80)

# Get all products in this category


[Link](f"SELECT id, name, price, stock FROM {table} ORDER BY name")
products = [Link]()

if not products:
print(" No products in this category.")
continue

print(f"{'ID':<5} {'Product Name':<30} {'Price':<15} {'Stock':<10}")


print("-" * 80)

for pid, name, price, stock in products:


print(f"{pid:<5} {name:<30} ${price:<14.2f} {stock:<10}")

print("\n" + "=" * 80)

def manager_change_password():
"""Allow manager to change the customer entry password"""
global CUSTOMER_PASSWORD
print("\n" + "=" * 60)
print("CHANGE CUSTOMER ENTRY PASSWORD")
print("=" * 60)
print(f"Current customer password: {'*' * len(CUSTOMER_PASSWORD)}")

while True:
new_password = [Link](prompt="Enter new customer password: ")
if not new_password:
print("* Password cannot be empty.")
continue
confirm_password = [Link](prompt="Confirm new customer password: ")
if new_password != confirm_password:
print("* Passwords do not match. Please try again.")
continue
CUSTOMER_PASSWORD = new_password
print("Customer password updated successfully!")
break

def manager_change_price(cursor, conn, category_to_table):


"""Allow manager to change product prices"""
print("\n" + "=" * 60)
print("CHANGE PRODUCT PRICE")
print("=" * 60)

# Show categories
categories = list(category_to_table.keys())
print("\nCategories:")
for i in range(len(categories)):
print(f" {i + 1}. {categories[i]}")
while True:
cat_choice = input("\nSelect category by number (0 to cancel): ").strip()
if not cat_choice.isdigit():
print("* Invalid input.")
continue
cat_num = int(cat_choice)
if cat_num == 0:
return
if cat_num < 1 or cat_num > len(categories):
print("* Invalid category number.")
continue
break

selected_category = categories[cat_num - 1]
table = category_to_table[selected_category]

# Show products in category


[Link](f"SELECT id, name, price, stock FROM {table} ORDER BY name")
products = [Link]()

if not products:
print("No products in this category.")
return

print(f"\nProducts in {selected_category}:")
print(f"{'ID':<5} {'Product Name':<30} {'Current Price':<15} {'Stock':<10}")
print("-" * 60)
for pid, name, price, stock in products:
print(f"{pid:<5} {name:<30} ${price:<14.2f} {stock:<10}")

while True:
prod_id = input("\nEnter product ID to change price (0 to cancel): ").strip()
if not prod_id.isdigit():
print("* Invalid input.")
continue
prod_id = int(prod_id)
if prod_id == 0:
return

# Verify product exists


[Link](f"SELECT id, name, price FROM {table} WHERE id = %s", (prod_id,))
product = [Link]()
if not product:
print("* Product ID not found.")
continue

pid, pname, current_price = product


print(f"\nSelected product: {pname}")
print(f"Current price: ${current_price:.2f}")
while True:
new_price = input("Enter new price: ").strip()
try:
new_price = float(new_price)
if new_price <= 0:
print("* Price must be positive.")
continue
break
except ValueError:
print("* Invalid price. Please enter a number.")

confirm = input(f"Update price from ${current_price:.2f} to ${new_price:.2f}? (y/n):


").strip().lower()
if confirm == 'y':
try:
[Link](f"UPDATE {table} SET price = %s WHERE id = %s",
(new_price, prod_id))
[Link]()
print(f"Price updated successfully! New price for {pname}: $
{new_price:.2f}")
except Exception as e:
[Link]()
print(f"Error updating price: {e}")
else:
print("Price update cancelled.")

another = input("\nChange another product price? (y/n): ").strip().lower()


if another != 'y':
break

def authenticate_manager():
"""Authenticate manager and return True if successful"""
manager_password = "gobhi"
attempts_left = 3
while attempts_left > 0:
entered = [Link](prompt="Enter manager password: ")
if entered == manager_password:
return True
attempts_left -= 1
print("* Incorrect password. Attempts left:", attempts_left)
print("Access denied.")
return False

def authenticate_customer():
"""Authenticate customer and return True if successful"""
global CUSTOMER_PASSWORD
attempts_left = 3
while attempts_left > 0:
entered = [Link](prompt="Enter customer password: ")
if entered == CUSTOMER_PASSWORD:
return True
attempts_left -= 1
print("* Incorrect password. Attempts left:", attempts_left)
print("Access denied.")
return False

def manager_mode(cursor, conn, category_to_table):


"""Manager mode menu and operations. Returns 'switch' to switch mode, 'exit' to exit program,
or None to continue."""
while True:
print("\n" + "=" * 60)
print("MANAGER MENU")
print("=" * 60)
print(" 1. View Stock (Tabular Format)")
print(" 2. Change Customer Entry Password")
print(" 3. Change Product Price")
print(" 4. Switch to Customer Mode")
print(" 5. Exit Program")

choice = input("\nEnter your choice (1-5): ").strip()

if choice == '1':
manager_view_stock(cursor, category_to_table)
elif choice == '2':
manager_change_password()
elif choice == '3':
manager_change_price(cursor, conn, category_to_table)
elif choice == '4':
return 'switch'
elif choice == '5':
return 'exit'
else:
print("* Invalid choice. Please enter 1-5.")

def print_receipt(customer_name, phone_number, address, cart, subtotal, payment_method,


transaction_id):
"""Print a detailed receipt with cost breakdown and customer information"""
print("\n" + "=" * 80)
print(" " * 25 + "GOBHIMART")
print(" " * 20 + "RECEIPT / INVOICE")
print("=" * 80)
print(f"Transaction ID: {transaction_id}")
print(f"Date: {[Link]().strftime('%Y-%m-%d %H:%M:%S')}")
print("-" * 80)
print("CUSTOMER INFORMATION:")
print(f" Name: {customer_name}")
print(f" Phone: {phone_number}")
print(f" Address: {address}")
print("-" * 80)
print("ITEMS PURCHASED:")
print(f"{'Item':<40} {'Qty':<8} {'Unit Price':<15} {'Total':<15}")
print("-" * 80)

for item in cart:


if len(item) == 6: # Has size (Clothing)
table, pid, pname, unit_price, qty, size = item
item_name = f"{pname} (Size: {size})"
else: # No size (Other categories)
table, pid, pname, unit_price, qty = item
item_name = pname

line_total = unit_price * qty


print(f"{item_name:<40} {qty:<8} ${unit_price:<14.2f} ${line_total:<14.2f}")

print("-" * 80)
print(f"{'SUBTOTAL:':<63} ${subtotal:.2f}")
print(f"{'PAYMENT METHOD:':<63} {payment_method}")
print("=" * 80)
print(" " * 25 + "THANK YOU FOR SHOPPING!")
print(" " * 20 + "Visit us again at GobhiMart")
print("=" * 80 + "\n")

def shopping(cursor, conn, category_to_table):


"""Handle the shopping flow"""
# Build categories list from mapping
categories = list(category_to_table.keys())
if not categories:
print("No categories available.")
return

cart = [] # list of tuples (product_id, name, unit_price, qty)

while True:
print("\nCategories:")
for i in range(len(categories)):
cat = categories[i]
print(f" {i + 1}. {cat}")
print(" 0. Proceed to payment")

choice = input("Select a category by number (0 to checkout): ").strip()


if not [Link]():
print("* Invalid input.")
continue
choice_num = int(choice)
if choice_num == 0:
break
if choice_num < 0 or choice_num > len(categories):
print("* Invalid category number.")
continue

selected_category = categories[choice_num - 1]
table = category_to_table[selected_category]
[Link](
f"SELECT id, name, price, stock FROM {table} ORDER BY name"
)
products = [Link]()
if not products:
print("No products in this category.")
continue

print(f"\nProducts in {selected_category}:")
for i in range(len(products)):
pid, name, price, stock = products[i]
print(f" {i + 1}. {name} - ${price} (Stock: {stock})")
print(" 0. Back to categories")

prod_choice = input("Select a product by number: ").strip()


if not prod_choice.isdigit():
print("* Invalid input.")
continue
prod_num = int(prod_choice)
if prod_num == 0:
continue
if prod_num < 0 or prod_num > len(products):
print("* Invalid product number.")
continue

pid, pname, pprice, pstock = products[prod_num - 1]


if pstock <= 0:
print("* Out of stock.")
continue

# Size selection for Clothing category


size = None
if selected_category == "Clothing":
sizes = ["XS", "S", "M", "L", "XL", "XXL"]
print("\nAvailable sizes:")
for i, sz in enumerate(sizes, 1):
print(f" {i}. {sz}")
while True:
size_choice = input("Select size by number: ").strip()
if not size_choice.isdigit():
print("* Invalid input. Please enter a number.")
continue
size_idx = int(size_choice)
if size_idx < 1 or size_idx > len(sizes):
print(f"* Invalid size. Please select between 1 and {len(sizes)}.")
continue
size = sizes[size_idx - 1]
print(f"Selected size: {size}")
break

qty_in = input("Enter quantity: ").strip()


if not qty_in.isdigit():
print("* Invalid quantity.")
continue
qty = int(qty_in)
if qty <= 0:
print("* Quantity must be positive.")
continue
if qty > pstock:
print(f"* Only {pstock} available.")
continue

# Assign a variable per product selection (category by category)


# Keep simple: build unique variable name hint and store in cart
selection_var_name = f"{selected_category.replace('a', 'e').lower()}_{[Link]('1',
'5').lower()}"
# We do not create dynamic variables; we display mapping and store in cart list
if size:
print(f"Selected -> var: {selection_var_name}, product: {pname}, size: {size},
qty: {qty}")
[Link]((table, pid, pname, float(pprice), qty, size)) # Include size for
clothing
else:
print(f"Selected -> var: {selection_var_name}, product: {pname}, qty: {qty}")
[Link]((table, pid, pname, float(pprice), qty)) # No size for other categories

if not cart:
print("Cart is empty. Returning to menu.")
return

print("\nCart:")
subtotal = 0.0
for i in range(len(cart)):
if len(cart[i]) == 6: # Has size (Clothing)
table, pid, pname, unit_price, qty, size = cart[i]
line_total = unit_price * qty
subtotal += line_total
print(f" {i + 1}. {pname} (Size: {size}) x {qty} @ ${unit_price:.2f} = $
{line_total:.2f}")
else: # No size (Other categories)
table, pid, pname, unit_price, qty = cart[i]
line_total = unit_price * qty
subtotal += line_total
print(f" {i + 1}. {pname} x {qty} @ ${unit_price:.2f} = ${line_total:.2f}")
print(f"Subtotal: ${subtotal:.2f}")

# Payment methods
methods = ["Cash", "Card", "UPI"]
while True:
print("Payment methods:")
for i in range(len(methods)):
m = methods[i]
print(f" {i + 1}. {m}")
pm_in = input("Choose payment method: ").strip()
if pm_in.isdigit() and 1 <= int(pm_in) <= len(methods):
payment_method = methods[int(pm_in) - 1]
break
print("* Invalid choice.")

print(f"Selected payment: {payment_method}")

# Get customer information


print("\n" + "-" * 60)
print("CUSTOMER INFORMATION")
print("-" * 60)

while True:
customer_name = input("Enter your name: ").strip()
if customer_name:
break
print("* Name cannot be empty. Please enter your name.")

while True:
phone_number = input("Enter your phone number: ").strip()
if phone_number:
# Basic validation - check if it contains digits
if any([Link]() for char in phone_number):
break
else:
print("* Please enter a valid phone number with digits.")
else:
print("* Phone number cannot be empty. Please enter your phone number.")

while True:
address = input("Enter delivery address: ").strip()
if address:
print(f"\nDelivery address: {address}")
break
print("* Address cannot be empty. Please enter a valid address.")

# Confirm
confirm = input("\nConfirm purchase? (y/n): ").strip().lower()
if confirm != "y":
print("Purchase cancelled.")
return

# Persist sales and update inventory atomically


try:
updated_items = [] # Track updated stock for purchased items
for item in cart:
if len(item) == 6: # Has size (Clothing)
table, pid, pname, unit_price, qty, size = item
else: # No size (Other categories)
table, pid, pname, unit_price, qty = item
size = None

[Link](
f"SELECT stock FROM {table} WHERE id=%s FOR UPDATE",
(pid,),
)
row = [Link]()
if not row:
raise ValueError("Product disappeared: " + str(pid))
current_stock = int(row[0])
if qty > current_stock:
raise ValueError(f"Insufficient stock for product {pname}")

new_stock = current_stock - qty


[Link](
f"UPDATE {table} SET stock=%s WHERE id=%s",
(new_stock, pid),
)
total_price = round(unit_price * qty, 2)
sales_table = f"sales_{table}"
[Link](
f"INSERT INTO {sales_table} (product_id, quantity, total_price,
sale_date) VALUES (%s, %s, %s, %s)",
(pid, qty, total_price, [Link]()),
)
# Store product name with size for clothing items
if size:
display_name = f"{pname} (Size: {size})"
else:
display_name = pname
updated_items.append((display_name, current_stock, new_stock))
[Link]()
print("Payment successful. Inventory and sales updated.")

# Ask for password after payment


global CUSTOMER_PASSWORD
attempts_left = 3
while attempts_left > 0:
password = [Link](prompt="Enter password to complete transaction: ")
if password == CUSTOMER_PASSWORD:
break
attempts_left -= 1
print("* Incorrect password. Attempts left:", attempts_left)
if attempts_left == 0:
print("Transaction verification failed. Please contact support.")
return

print("Transaction verified successfully!")

# Generate transaction ID
transaction_id = f"TXN{[Link]().strftime('%Y%m%d%H%M%S')}"

# Print receipt
print_receipt(customer_name, phone_number, address, cart, subtotal, payment_method,
transaction_id)

# Display updated stock for purchased items


print("\nUpdated Stock Levels:")
print("-" * 60)
for pname, old_stock, new_stock in updated_items:
print(f" {pname}: {old_stock} → {new_stock} (Sold: {old_stock -
new_stock})")
print("-" * 60)
except Exception as e:
[Link]()
print("Transaction failed:", e)

def main():
# Welcome message
welcome_message = "Welcome to GobhiMart - Your One-Stop Shopping Destination!"
slow_print(welcome_message)
slow_print("=" * len(welcome_message))
print()

# Connect to MySQL
try:
conn = [Link](
host="localhost",
user="root",
password="omijebhabha",
database="gobhimart",
)
except [Link] as e:
print("Database connection failed:", e)
[Link](2)

cursor = [Link]()

# Define per-category product tables and sales tables; ensure schema


category_to_table = {
"Electronics": "products_electronics",
"Clothing": "products_clothing",
"Books": "products_books",
"Home & Garden": "products_home_garden",
"Sports": "products_sports",
}

for cat, table in category_to_table.items():


[Link](
f"""
CREATE TABLE IF NOT EXISTS {table} (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL,
cost DECIMAL(10,2) NOT NULL,
stock INT NOT NULL
)
"""
)
[Link](
f"""
CREATE TABLE IF NOT EXISTS sales_{table} (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
quantity INT,
total_price DECIMAL(10,2),
sale_date DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (product_id) REFERENCES {table}(id)
)
"""
)

# Seed each category table if empty


seed_map = {
"Electronics": [
("Smartphone", 299.99, 200.00, 50),
("Laptop", 899.99, 600.00, 30),
("Headphones", 199.99, 120.00, 75),
("Smart Watch", 149.99, 90.00, 40),
("Tablet", 249.99, 150.00, 60),
],
"Clothing": [
("T-Shirt", 19.99, 8.00, 100),
("Jeans", 49.99, 25.00, 80),
("Jacket", 79.99, 40.00, 45),
("Shoes", 89.99, 45.00, 35),
("Dress", 39.99, 20.00, 55),
],
"Books": [
("Python Book", 29.99, 15.00, 200),
("Data Science", 39.99, 20.00, 150),
("Web Dev", 34.99, 18.00, 180),
("ML Guide", 44.99, 25.00, 120),
("Database", 24.99, 12.00, 160),
],
"Home & Garden": [
("Garden Hose", 24.99, 12.00, 90),
("Fertilizer", 14.99, 7.00, 120),
("Tools Set", 49.99, 25.00, 40),
("Outdoor Chair", 34.99, 18.00, 60),
("Solar Lights", 19.99, 10.00, 80),
],
"Sports": [
("Basketball", 29.99, 15.00, 70),
("Tennis Racket", 79.99, 40.00, 25),
("Yoga Mat", 24.99, 12.00, 85),
("Dumbbells", 99.99, 50.00, 30),
("Football", 34.99, 18.00, 50),
],
}

for cat, table in category_to_table.items():


[Link](f"SELECT COUNT(*) FROM {table}")
cnt = [Link]()[0]
if cnt == 0:
rows = seed_map[cat]
[Link](
f"INSERT INTO {table} (name, price, cost, stock) VALUES (%s, %s,
%s, %s)",
rows,
)
[Link]()

# Main loop - allows switching between modes


while True:
# Mode selection
print("\n" + "=" * 60)
print("MODE SELECTION")
print("=" * 60)
print("Select mode:")
print(" 1. Manager")
print(" 2. Customer")
print(" 3. Exit Program")
mode_choice = input("\nEnter mode (1-3): ").strip()

if mode_choice == '1':
# Manager mode authentication
if not authenticate_manager():
continue
print("Manager access granted!")

# Manager mode loop


while True:
result = manager_mode(cursor, conn, category_to_table)
if result == 'switch':
print("\nSwitching to customer mode...")
break # Break out of manager loop to show mode selection again
elif result == 'exit':
print("Thank you for using GobhiMart. Goodbye!")
cleanup(cursor, conn)
return

elif mode_choice == '2':


# Customer mode authentication
if not authenticate_customer():
continue
print("Customer access granted!")

# Customer mode loop


while True:
print("\nSelect an option:")
print(" s - Shopping")
print(" w - View Stock and Sales")
print(" m - Switch to Manager Mode")
print(" x - Exit Program")

option = input("\nEnter your choice (s/w/m/x): ").strip().lower()


if option == 's':
# Show product list before shopping
show_product_list(cursor, category_to_table)
shopping(cursor, conn, category_to_table)
# Show updated product list after shopping
print("\n")
show_product_list(cursor, category_to_table)
elif option == 'w':
view_stock_and_sales(cursor, conn, category_to_table)
elif option == 'm':
print("\nSwitching to manager mode...")
break # Break out of customer loop to show mode selection again
elif option == 'x':
print("Thank you for using GobhiMart. Goodbye!")
cleanup(cursor, conn)
return
else:
print("* Invalid choice. Please enter 's' for shopping, 'w' for stock
and sales, 'm' to switch mode, or 'x' to exit.")

elif mode_choice == '3':


print("Thank you for using GobhiMart. Goodbye!")
cleanup(cursor, conn)
break
else:
print("* Invalid mode selection. Please enter 1-3.")

cleanup(cursor, conn)

def cleanup(cursor, conn):


try:
[Link]()
except Exception:
pass
try:
[Link]()
except Exception:
pass

if __name__ == "__main__":
main()
OUTPUT

Customer :-

Welcome to GobhiMart - Your One-Stop Shopping Destination!


==========================================================

============================================================
MODE SELECTION
============================================================
Select mode:
1. Manager
2. Customer
3. Exit Program

Enter mode (1-3): 2

Enter customer password: omijebhabha


Customer access granted!

Select an option:
s - Shopping
w - View Stock and Sales
m - Switch to Manager Mode
x - Exit Program

Enter your choice (s/w/m/x): s

=========================================================================
=======
PRODUCT LIST
=========================================================================
=======

Electronics:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Headphones $199.99 74
Laptop $899.99 27
Smart Watch $149.99 40
Smartphone $299.99 50
Tablet $249.99 60

Clothing:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Dress $39.99 53
Jacket $79.99 45
Jeans $49.99 58
Shoes $89.99 35
T-Shirt $19.99 98

Books:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Data Science $24.21 145
Database $24.99 160
ML Guide $44.99 115
Python Book $29.99 199
Web Dev $34.99 175

Home & Garden:


--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Fertilizer $14.99 118
Garden Hose $24.99 89
Outdoor Chair $34.99 60
Solar Lights $19.99 80
Tools Set $49.99 40

Sports:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Basketball $29.99 70
Dumbbells $99.99 27
Football $34.99 46
Tennis Racket $79.99 25
Yoga Mat $24.99 81

=========================================================================
=======

Categories:
1. Electronics
2. Clothing
3. Books
4. Home & Garden
5. Sports
0. Proceed to payment
Select a category by number (0 to checkout): 2

Products in Clothing:
1. Dress - $39.99 (Stock: 53)
2. Jacket - $79.99 (Stock: 45)
3. Jeans - $49.99 (Stock: 58)
4. Shoes - $89.99 (Stock: 35)
5. T-Shirt - $19.99 (Stock: 98)
0. Back to categories
Select a product by number: 3

Available sizes:
1. XS
2. S
3. M
4. L
5. XL
6. XXL
Select size by number: 3
Selected size: M
Enter quantity: 2
Selected -> var: clothing_jeans, product: Jeans, size: M, qty: 2

Categories:
1. Electronics
2. Clothing
3. Books
4. Home & Garden
5. Sports
0. Proceed to payment
Select a category by number (0 to checkout): 0

Cart:
1. Jeans (Size: M) x 2 @ $49.99 = $99.98
Subtotal: $99.98
Payment methods:
1. Cash
2. Card
3. UPI
Choose payment method: 2
Selected payment: Card

------------------------------------------------------------
CUSTOMER INFORMATION
------------------------------------------------------------
Enter your name: haze
Enter your phone number: 6967595938
Enter delivery address: skp

Delivery address: skp

Confirm purchase? (y/n): y


Payment successful. Inventory and sales updated.
Warning: Password input may be echoed.
Enter password to complete transaction: omijebhabha
Transaction verified successfully!

=========================================================================
=======
GOBHIMART
RECEIPT / INVOICE
=========================================================================
=======
Transaction ID: TXN20251207170735
Date: 2025-12-07 17:07:35
--------------------------------------------------------------------------------
CUSTOMER INFORMATION:
Name: haze
Phone: 6967595938
Address: skp
--------------------------------------------------------------------------------
ITEMS PURCHASED:
Item Qty Unit Price Total
--------------------------------------------------------------------------------
Jeans (Size: M) 2 $49.99 $99.98
--------------------------------------------------------------------------------
SUBTOTAL: $99.98
PAYMENT METHOD: Card
=========================================================================
=======
THANK YOU FOR SHOPPING!
Visit us again at GobhiMart
=========================================================================
=======

Updated Stock Levels:


------------------------------------------------------------
Jeans (Size: M): 58 → 56 (Sold: 2)
------------------------------------------------------------

=========================================================================
=======
PRODUCT LIST
=========================================================================
=======

Electronics:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Headphones $199.99 74
Laptop $899.99 27
Smart Watch $149.99 40
Smartphone $299.99 50
Tablet $249.99 60

Clothing:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Dress $39.99 53
Jacket $79.99 45
Jeans $49.99 56
Shoes $89.99 35
T-Shirt $19.99 98

Books:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Data Science $24.21 145
Database $24.99 160
ML Guide $44.99 115
Python Book $29.99 199
Web Dev $34.99 175

Home & Garden:


--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Fertilizer $14.99 118
Garden Hose $24.99 89
Outdoor Chair $34.99 60
Solar Lights $19.99 80
Tools Set $49.99 40

Sports:
--------------------------------------------------------------------------------
Product Name Price Stock
--------------------------------------------------------------------------------
Basketball $29.99 70
Dumbbells $99.99 27
Football $34.99 46
Tennis Racket $79.99 25
Yoga Mat $24.99 81

=========================================================================
=======

Select an option:
s - Shopping
w - View Stock and Sales
m - Switch to Manager Mode
x - Exit Program

Enter your choice (s/w/m/x):

Manager :-
============================================================
MODE SELECTION
============================================================
Select mode:
1. Manager
2. Customer
3. Exit Program

Enter mode (1-3): 1

Warning (from warnings module):


File "C:\Users\Prakersh Srivastava\AppData\Local\Programs\Python\Python312\Lib\[Link]", line
100
return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
Enter manager password: omijebhabha
* Incorrect password. Attempts left: 2
Warning: Password input may be echoed.
Enter manager password: gobhi
Manager access granted!

============================================================
MANAGER MENU
============================================================
1. View Stock (Tabular Format)
2. Change Customer Entry Password
3. Change Product Price
4. Switch to Customer Mode
5. Exit Program

Enter your choice (1-5): 1

=========================================================================
=======
CURRENT STOCK INVENTORY
=========================================================================
=======

Electronics:
--------------------------------------------------------------------------------
ID Product Name Price Stock
--------------------------------------------------------------------------------
3 Headphones $199.99 74
2 Laptop $899.99 27
4 Smart Watch $149.99 40
1 Smartphone $299.99 50
5 Tablet $249.99 60

Clothing:
--------------------------------------------------------------------------------
ID Product Name Price Stock
--------------------------------------------------------------------------------
5 Dress $39.99 53
3 Jacket $79.99 45
2 Jeans $49.99 56
4 Shoes $69.99 35
1 T-Shirt $19.99 98

Books:
--------------------------------------------------------------------------------
ID Product Name Price Stock
--------------------------------------------------------------------------------
2 Data Science $24.21 145
5 Database $24.99 160
4 ML Guide $44.99 115
1 Python Book $29.99 199
3 Web Dev $34.99 175

Home & Garden:


--------------------------------------------------------------------------------
ID Product Name Price Stock
--------------------------------------------------------------------------------
2 Fertilizer $14.99 118
1 Garden Hose $24.99 89
4 Outdoor Chair $34.99 60
5 Solar Lights $19.99 80
3 Tools Set $49.99 40

Sports:
--------------------------------------------------------------------------------
ID Product Name Price Stock
--------------------------------------------------------------------------------
1 Basketball $29.99 70
4 Dumbbells $99.99 27
5 Football $34.99 46
2 Tennis Racket $79.99 25
3 Yoga Mat $24.99 81

=========================================================================
=======

============================================================
MANAGER MENU
============================================================
1. View Stock (Tabular Format)
2. Change Customer Entry Password
3. Change Product Price
4. Switch to Customer Mode
5. Exit Program

Enter your choice (1-5): 2

============================================================
CHANGE CUSTOMER ENTRY PASSWORD
============================================================
Current customer password: ***********
Warning: Password input may be echoed.
Enter new customer password: haze123
Warning: Password input may be echoed.
Confirm new customer password: haze123
Customer password updated successfully!

============================================================
MANAGER MENU
============================================================
1. View Stock (Tabular Format)
2. Change Customer Entry Password
3. Change Product Price
4. Switch to Customer Mode
5. Exit Program

Enter your choice (1-5): 4


Switching to customer mode...

============================================================
MODE SELECTION
============================================================
Select mode:
1. Manager
2. Customer
3. Exit Program

Enter mode (1-3): 2


Warning: Password input may be echoed.
Enter customer password: haze123
Customer access granted!

Select an option:
s - Shopping
w - View Stock and Sales
m - Switch to Manager Mode
x - Exit Program

Enter your choice (s/w/m/x): m

Switching to manager mode...

============================================================
MODE SELECTION
============================================================
Select mode:
1. Manager
2. Customer
3. Exit Program

Enter mode (1-3): 1


Warning: Password input may be echoed.
Enter manager password: haze123
* Incorrect password. Attempts left: 2
Warning: Password input may be echoed.
Enter manager password: gobhi
Manager access granted!

============================================================
MANAGER MENU
============================================================
1. View Stock (Tabular Format)
2. Change Customer Entry Password
3. Change Product Price
4. Switch to Customer Mode
5. Exit Program
Enter your choice (1-5): 3

============================================================
CHANGE PRODUCT PRICE
============================================================

Categories:
1. Electronics
2. Clothing
3. Books
4. Home & Garden
5. Sports

Select category by number (0 to cancel): 5

Products in Sports:
ID Product Name Current Price Stock
------------------------------------------------------------
1 Basketball $29.99 70
4 Dumbbells $99.99 27
5 Football $34.99 46
2 Tennis Racket $79.99 25
3 Yoga Mat $24.99 81

Enter product ID to change price (0 to cancel): 3

Selected product: Yoga Mat


Current price: $24.99
Enter new price: 50.99
Update price from $24.99 to $50.99? (y/n): y
Price updated successfully! New price for Yoga Mat: $50.99

Change another product price? (y/n): n

============================================================
MANAGER MENU
============================================================
1. View Stock (Tabular Format)
2. Change Customer Entry Password
3. Change Product Price
4. Switch to Customer Mode
5. Exit Program

Enter your choice (1-5): 5

Thank you for using GobhiMart. Goodbye!


Bibliography

[Link], Sumita. Computer Science with Python –


Textbook for Class XII. Dhanpat Rai & Co., 2025.

[Link], Sumita. Computer Science with Python –


Practical Book for Class XII. Dhanpat Rai & Co.,
2025.

[Link]. “Database Management System.”


[Link]

[Link]. “Python Project Ideas and


Examples.” [Link]
projects

5. W3Schools. “Python MySQL Database Tutorial.”


[Link]
ql_getstarted.asp

You might also like