Import Pandas As Pd2
Import Pandas As Pd2
import mysql.connector
from datetime import datetime
from tabulate import tabulate
import matplotlib.pyplot as plt
header=['Item_Id','Category','Item_Name','Description','Pri
ce(₹)','Item Type']
print(tabulate(data,header,tablefmt='pretty'))
def menu_items():
while True:
print("\n")
print(" ~~~~~~~~~~~~~~~~~~
")
print("┍<<-------------->>| ITEMS MENU |
<<-------------->>┒ ")
print("| ~~~~~~~~~~~~~~~~~~
| ")
print("""
1.Whole Menu
2. By Item type (VEG/NON VEG)
3. By category(Appetizers/Main Courses/
Breads/Desserts/Beverages)
4. Exit""")
else:
print(" Invalid Item Type...")
elif userinput=="3":
print("\n Searching by category...")
category=input("--->>Enter Category: ").strip()
if category.lower() in
['appetizers','maincourses','main
courses','desserts','beverages','breads']:
q="""select
item_ID,Category,Item_name,description,price,item_type
from menu_items where category=%s and
available='yes';"""
mycursor.execute(q,(category,))
data=mycursor.fetchall()
cols=['Item_Id','Category','Item_Name','Description','Price(
₹)','Item_type']
print(tabulate(data,headers=cols,tablefmt='pretty'))
else:
print(" Invalid Category!!!")
elif userinput=="4":
print("-->>Exiting...")
break
else:
print(" Invalid Option!")
def place_order():
print(" Placing an Order...")
mobile_no = input(" >>Enter Your Mobile no. :")
if last_id is None:
print("Error: Failed to retrieve a valid order ID.
Please try again.")
while True:
item_id = int(input(" >>Enter the Item ID to order
(or 0 to finish): "))
if item_id == 0:
break
else:
quantity = int(input(" >>Enter
Quantity to order :"))
mycursor.execute("SELECT item_name,
ROUND(price, 2) FROM menu_items WHERE item_id
= %s and available='yes';", (item_id,))
item = mycursor.fetchone()
if item:
item_name, price = item
total_price = float(price) * quantity
order_details.append([item_name,
price, quantity, total_price])
order_total += total_price
mycursor.execute("""
INSERT INTO order_items (order_id,
item_id, quantity, price, total_price)
VALUES (%s, %s, %s, %s, %s);
""", (last_id, item_id, quantity, price,
total_price))
else:
print(""" Item ID not found. Please
enter a valid ID OR Item Not Available """)
mycursor.execute("UPDATE orders SET
total_amount = %s WHERE order_id = %s;",
(order_total, last_id))
mycursor.execute("""
SELECT SUM(total_amount),
COUNT(order_id)
FROM orders
WHERE DATE(order_date) = DATE(NOW());
""")
daily_total_sales, daily_total_orders =
mycursor.fetchone()
mycursor.execute("SELECT 1 FROM
sales_reports WHERE DATE(report_date) =
DATE(NOW());")
if mycursor.fetchone():
mycursor.execute("""
UPDATE sales_reports
SET total_sales = %s, total_orders = %s
WHERE DATE(report_date) =
DATE(NOW());
""", (daily_total_sales, daily_total_orders))
else:
mycursor.execute("""
INSERT INTO sales_reports (report_date,
total_sales, total_orders)
VALUES (NOW(), %s, %s);
""", (daily_total_sales, daily_total_orders))
mydb.commit()
else:
print("Invalid Mobile Number")
def generate_bill():
print("\n")
print("
~~~~~~~~~~~~~~~~~~~~~~~~ ")
print("┍<<-------------->>| BILL GENERATION |
<<-------------->>┒ ")
print("|
~~~~~~~~~~~~~~~~~~~~~~~~ | ")
while True:
if data:
print(" -------------------------------------- ")
print(" 1. Today's Bill 2. Previous Bill ")
print(" 3. Exit")
total_query = """
SELECT SUM(total_price)
FROM order_items o
JOIN orders r ON r.order_id = o.order_id
WHERE r.mobile = %s AND DATE(r.order_date)
= CURDATE();
"""
total_query = """
SELECT SUM(total_price)
FROM order_items o
JOIN orders r ON r.order_id = o.order_id
WHERE r.mobile = %s AND DATE(r.order_date)
< CURDATE();
"""
elif userinput=="3":
print(" >>Exiting Bill Generation...")
break
else:
print(" >>Invalid Choice. Try again later")
return
mycursor.execute(query, (mobileno,))
bill = mycursor.fetchall()
if bill:
mycursor.execute(total_query, (mobileno,))
subtotal = mycursor.fetchone()[0]
else:
print("No orders found for the selected date
range")
else:
print("No orders found for this mobile number.")
else:
print("No orders found for this mobile number.") #
This is the fallback if no data is returned
break
def add_item():
print("Adding new Menu item...")
category=input("Enter the category to be
entered :")
item_name=input("Enter Item Name :")
description=input("Enter Description :")
price=float(input("Enter Item Price :"))
if price<=0:
print("Price cannot be zero or negative.")
return
L = [{
'Category': category,
'Item_Name': item_name,
'Description': description,
'Price(₹)': price,
'Item_type': item_type,
'Available': availability
}]
df=pd.DataFrame(L,columns=['Category','Item_Nam
e','Description','Price(₹)','Item_type','Available'])
print(tabulate(df,headers='keys', tablefmt='grid',
showindex=False))
choice=input("Is this The Item to be Added
(Yes/No) :")
if choice.lower()=='yes':
query = "INSERT INTO menu_items (category,
item_name, description, price, item_type, available)
VALUES (%s, %s, %s, %s, %s, %s)"
val = (category, item_name, description, price,
item_type, availability)
mycursor.execute(query, val)
mydb.commit()
print("New item added successfully.")
elif choice.lower()=='no':
admin_menu()
else:
print("Invalid Option!!")
#defining updatation of item
def update_menu():
item_id=input("\nEnter Item Id to be updated :")
if userinput=="1":
category=input("Enter new category :")
if category.strip().lower() in
['appetizers','breads','beverages','desserts','main
courses']:
query="Select*from menu_items where
item_id=%s;"
val=(item_id,)
mycursor.execute(query,val)
data=mycursor.fetchone()
header=['Item_Id','Category','Item_Name','Descripti
on','Price(₹)','Item_type','Available']
df=pd.DataFrame([data],columns=header)
df['Category']=category
print(tabulate(df, headers='keys',
tablefmt='grid', showindex=False))
print("\nIs The data inserted correct.
(yes/no): ")
elif choice.lower()=='no':
update_menu()
else:
print("Not a valid Option!")
admin_menu()
else:
print("Invalid Category")
elif userinput=="2":
price=int(input("Enter New Price :"))
elif choice.lower()=='no':
update_menu()
else:
print("Price Cannot be Zero or Negative")
elif userinput=="3":
availability=input("Is it Available? (yes/no) :")
if availability.strip().lower() in ['yes','no']:
query="Select*from menu_items where
item_id=%s;"
val=(item_id,)
mycursor.execute(query,val)
data=mycursor.fetchone()
header=['Item_Id','Category','Item_Name','Description','Pri
ce(₹)','item_id','Available']
df=pd.DataFrame([data],columns=header)
df['Available']=availability
print(tabulate(df, headers='keys',
tablefmt='grid', showindex=False))
choice=input("Is The data inserted
correct.(yes/no): ")
if choice.lower()=='yes' and
availability.lower()=='yes':
query="update menu_items set
available='yes' where item_id=%s;"
val=(item_id,)
mycursor.execute(query,val)
mydb.commit()
print("\nUpdatation Completed...")
elif choice.lower()=='no':
update_menu()
else:
print("Invalid Item Type")
else:
print("Invalid Option!!")
else:
print("Invalid Item Id ...")
def remove_item():
item_id=int(input("Enter Item Id to be
deleted :"))
query="Select*from menu_items where item_id=
%s;"
val=(item_id,)
mycursor.execute(query,val)
data=mycursor.fetchone()
if data:
header=['Item_Id','Category','Item_Name','Descripti
on','Price(₹)','Available']
print(tabulate([data],header,tablefmt='pretty'))
if choice.lower()=='yes':
query="update menu_items set
available='no' where item_id=%s;"
val=(item_id,)
mycursor.execute(query,val) #Executing
the delete query
mydb.commit()
elif choice.lower()=='no':
admin_menu()
else:
print("Invalid Input")
else:
print("Invalid Item Id.")
def weekly_sales():
year= int(input(" -->>Enter Year : "))
mycursor.execute("select year(now());")
today=mycursor.fetchone()[0]
if int(year)>=today:
query = """
SELECT YEAR(report_date) AS sale_year,
WEEK(report_date) AS sale_week,
SUM(total_sales) AS weekly_total_sales
FROM sales_reports
where year(report_date) = %s
GROUP BY sale_year, sale_week
ORDER BY sale_year, sale_week;
"""
mycursor.execute(query,(year,))
weekly_sales = mycursor.fetchall()
if weekly_sales:
col = ['Sale_Year', 'Sale_Week', 'Total_Sales']
d_sales = pd.DataFrame(weekly_sales,
columns=col)
sale_dates = []
for i in range(len(d_sales)):
year = d_sales.loc[i, 'Sale_Year']
week = d_sales.loc[i, 'Sale_Week']
sale_date = datetime.strptime(f"{year}-
W{week}-1", "%Y-W%W-%w")
sale_dates.append(sale_date)
d_sales['Sale_Date'] = sale_dates
d_sales['Sale_Date_Str'] =
d_sales['Sale_Date'].dt.strftime('Week %U-%b-%Y')
print(tabulate(d_sales[['Sale_Date_Str',
'Total_Sales']], headers=['Sale Date', 'Total Sales'],
tablefmt='pretty'))
print("\n")
d_sales.plot(x='Sale_Date_Str',
y='Total_Sales', kind='bar', color='skyblue',
linewidth=2, rot=30)
plt.title('Weekly Sales')
plt.xlabel('Sale Date')
plt.ylabel('Total Sales')
plt.show()
else:
print("No Weekly Sales Record")
else:
print("Invalid Year")
return
def weekly_orders():
year= int(input(" -->>Enter Year : "))
mycursor.execute("select year(now());")
today=mycursor.fetchone()[0]
if int(year)>=today:
query="""select year(report_date) as
sale_year,week(report_date) as sale_week,
sum(total_orders) as total_orders
from sales_reports
where year(report_date) = %s
GROUP BY sale_year, sale_week
order by sale_year,sale_week;"""
mycursor.execute(query,(year,))
weekly_orders = mycursor.fetchall()
if weekly_orders:
col = ['Sale_Year', 'Sale_Week',
'Total_Orders']
d_sales = pd.DataFrame(weekly_orders,
columns=col)
d_sales['Total_Orders'] =
pd.to_numeric(d_sales['Total_Orders'])
sale_dates = []
for i in range(len(d_sales)):
year = d_sales.loc[i, 'Sale_Year']
week = d_sales.loc[i, 'Sale_Week']
sale_date = datetime.strptime(f"{year}-
W{week}-1", "%Y-W%U-%w")
sale_dates.append(sale_date)
d_sales['Sale_Date'] = sale_dates
d_sales['Sale_Date_Str'] =
d_sales['Sale_Date'].dt.strftime('Week %U-%b-%Y')
print(tabulate(d_sales[['Sale_Date_Str',
'Total_Orders']], headers=['Sale Date', 'Total
Orders'], tablefmt='pretty'))
print("\n")
d_sales.plot(x='Sale_Date_Str',
y='Total_Orders', kind='bar', color='skyblue',
linewidth=2, rot=30)
plt.title('Weekly Orders')
plt.xlabel('Sale Date')
plt.ylabel('Total Orders')
plt.show()
else:
print("No Weekly order Record")
else:
print("Invalid Year")
return
def monthly_sales():
year= int(input(" -->>Enter Year : "))
mycursor.execute("select year(now());")
today=mycursor.fetchone()[0]
if int(year)>=today:
query="""select year(report_date) as
sale_year,MONTH(report_date) as sale_month,
sum(total_sales) as total_sales
from sales_reports
where year(report_date) = %s
GROUP BY sale_year, sale_month
order by sale_year,sale_month;"""
mycursor.execute(query,(year,))
monthly_sales=mycursor.fetchall()
if monthly_sales:
col = ['Sale_Year', 'Sale_Month',
'Total_Sales']
d_sales = pd.DataFrame(monthly_sales,
columns=col)
d_sales['Total_Sales'] =
pd.to_numeric(d_sales['Total_Sales'])
sale_dates = []
for i in range(len(d_sales)):
year = d_sales.loc[i, 'Sale_Year']
month = d_sales.loc[i, 'Sale_Month']
sale_date = datetime.strptime(f"{year}-
{month}-1","%Y-%m-%d")
sale_dates.append(sale_date)
d_sales['Sale_Date'] = sale_dates
d_sales['Sale_Date_Str'] =
d_sales['Sale_Date'].dt.strftime('%b-%Y' )
print(tabulate(d_sales[['Sale_Date_Str',
'Total_Sales']], headers=['Sale Date', 'Total Sales'],
tablefmt='pretty'))
print("\n")
d_sales.plot(x='Sale_Date_Str',
y='Total_Sales', kind='bar', color='skyblue',
linewidth=2, rot=45)
plt.title('Monthly Sales')
plt.xlabel('Sales Date')
plt.ylabel('Total Sales(₹)')
plt.show()
else:
print("No Monthly Sales Record ")
else:
print("Invalid Year")
return
def monthly_orders():
year= int(input(" -->>Enter Year : "))
mycursor.execute("select year(now());")
today=mycursor.fetchone()[0]
if int(year)>=today:
query="""select Year(report_date) as
sale_year,month(report_date) as sale_month,
sum(total_orders) as total_orders
from sales_reports
where year(report_date) = %s
GROUP BY sale_year, sale_month
order by sale_year,sale_month;"""
mycursor.execute(query,(year,))
monthly_orders = mycursor.fetchall()
if monthly_orders:
col = ['Sale_Year', 'Sale_Month',
'Total_Orders']
d_sales = pd.DataFrame(monthly_orders,
columns=col)
d_sales['Total_Orders'] =
pd.to_numeric(d_sales['Total_Orders'])
sale_dates = []
for i in range(len(d_sales)):
year = d_sales.loc[i, 'Sale_Year']
month = d_sales.loc[i, 'Sale_Month']
sale_date = datetime.strptime(f"{year}-
{month}-1","%Y-%m-%d")
sale_dates.append(sale_date)
d_sales['Sale_Date'] = sale_dates
d_sales['Sale_Date_Str'] =
d_sales['Sale_Date'].dt.strftime('%b-%Y' )
print(tabulate(d_sales[['Sale_Date_Str',
'Total_Orders']], headers=['Sale Date', 'Total
Sales'], tablefmt='pretty'))
print("\n")
d_sales.plot(x='Sale_Date_Str',
y='Total_Orders', kind='bar', color='skyblue',
linewidth=2, rot=45)
plt.title('Monthly Orders')
plt.xlabel('Sales Date')
plt.ylabel('Total Orders')
plt.show()
else:
print("No Monthly Order Record")
else:
print("Invalid year")
return
def most_ordered():
query="SELECT m.item_name as name,\
sum(quantity) as total_Quantity\
from menu_items m,order_items o\
where m.item_id=o.item_id\
group by m.item_id;"
mycursor.execute(query)
data=mycursor.fetchall()
if data:
col=['Item_Name','Quantity_ordered']
df=pd.DataFrame(data,columns=col)
#plt.figure(figsize=(10, 8))
plt.pie(df['Quantity_ordered'],labels=df['Item_Name
'],autopct='%1.1f%
%',shadow=True,startangle=160,
textprops={'fontsize': 7,'weight':'bold'},
wedgeprops={'linewidth': 1, 'edgecolor': 'white'})
plt.title("Total Quantity Ordered for Each
Item")
#plt.axis('equal') # Equal aspect ratio ensures
the pie chart is circular.
plt.show()
else:
print("No Data Found")
def Daily_sales():
report_date=input("--->>| Enter Report
Date(YYYY-MM-DD) :" )
q="select*from sales_reports where
date(report_date)=%s;"
mycursor.execute(q,(report_date,))
data=mycursor.fetchall()
if data:
print(tabulate(data,headers=[‘Report
ID’,'Report Date','Total Sales(₹)','Total
Order'],tablefmt='pretty'))
else:
print(f"No data Found for report date:
{report_date}")
def Avg_revenue():
query="select
count(order_item_id),sum(total_price),round(avg(to
tal_price)) Average from order_items;"
mycursor.execute(query)
AVG=mycursor.fetchone()
if AVG:
print(f"Average Revenue Per Customer is:₹
{AVG}")
print(">> Details:")
print(tabulate([AVG],headers=['Total_orders','Total_
Sales','Average Revenue'],tablefmt='pretty'))
else:
print("No Data Found")
def Prime_hours():
query="SELECT HOUR(order_date) AS Hour,\
COUNT(order_id) AS total_orders\
FROM orders\
group by HOUR(order_date)\
order by Hour;"
mycursor.execute(query)
Hours=mycursor.fetchall()
if Hours:
header=['Prime Hours','Total orders']
print(tabulate(Hours,headers=header,tablefmt='pr
etty'))
for i in range(len(df)):
df.loc[i, 'Prime Hours'] = str(df.loc[i, 'Prime
Hours']) + " O' Clock"
df.plot(x='Prime Hours',y='Total
orders',kind='bar',linewidth=2,rot=0)
plt.title('Prime Hours and Total Orders')
plt.xlabel('Total Orders Orders')
plt.ylabel('Hours')
plt.show()
else:
print("NO DATA FOUND")
def Sales_report_menu():
while True:
print("\n1. Total Weekly Sales 2. Total
monthly Sales")
print("3. Daily sales 4. Exit")
elif userinput=="2":
monthly_sales()
elif userinput=="3":
Daily_sales()
elif userinput=="4":
print(" >>Exiting...")
break
else:
print(" >>Invalid Option")
def Orders_report_menu():
while True:
print("1.Total Weekly Orders 2.Total
Monthly Orders")
print("3.Most ordered Items 4.Exit")
if userinput=="1":
weekly_orders()
elif userinput=="2":
monthly_orders()
elif userinput=="3":
most_ordered()
elif userinput=="4":
print("\n >>Exiting...")
break
else:
print("\n >>Invalid Option")
def sales_report_menu():
while True:
print("\n")
print("
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
")
print("┍<<--------->>| REPORT MANAGEMENT
MENU |<<-------->>┒ ")
print("|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ")
print("| 1. Sales Report 2. Orders
Report | ")
print("| 3. Revenue per customer 4. Prime
Hours report | ")
print("| 5. Exit |\n
")
userinput=input("\n--->>| Enter your Selection:
")
if userinput=="1":
print("<<--->>| Sales Menu |<<--->>")
Sales_report_menu()
elif userinput=="2":
print("<<--->>| Orders Menu |<<--->>")
Orders_report_menu()
elif userinput=="3":
print("<<--->>| Average Revenue |<<---
>>")
Avg_revenue()
elif userinput=="4":
Prime_hours()
elif userinput=="5":
print("\nExiting Report Menu...")
break
else:
print("\nInvalid selection")
def Admin_login():
username=input(" >>Enter Username :")
password=input(" >>Enter Password :")
else:
print("\nInvalid credentials. Access denied.")
def admin_menu():
while True:
print("\n")
print(" ~~~~~~~~~~~~~~~~~~~~
")
print("┍<<----------->>| Admin Menu |
<<----------->>┒ ")
print("| ~~~~~~~~~~~~~~~~~~~~
| ")
print("| 1. View Menu 2.Add Menu
Item | ")
print("| 3. Update Menu Item 4. Delete
Menu Item | ")
print("| 5. View Sales Reports 6.Exit Admin
Menu | ")
if userinput=="1":
menu_items()
elif userinput=="2":
add_item()
elif userinput=="3":
update_menu()
elif userinput=="4":
remove_item()
elif userinput=="5":
sales_report_menu()
elif userinput=="6":
break
else:
print('Invalid Option')
if userinput=="1":
menu_items() #Function to display menu
items
elif userinput=="2":
place_order() #Function to Place order
elif userinput=="3":
generate_bill() #function for generating bill
elif userinput=="4":
Admin_login() #Function for Admin
menu(Restricted)
elif userinput=="5":
print("Exiting The System...")
break
else:
print("Invalid option. Please try again.")
main_menu()
MySQL Database and
Tables
Database Name: Restrnt102
Tables in Restrnt102:
Desc menu_items;
Desc Order_items;
Desc Orders ;
Desc Sales_reports;
Select*from orders;
Select*from menu_items;
Select*from order_items;
Select*from sales_reports;
MySQL CODEs
Code for creating ‘restrnt102’ Database --