0% found this document useful (0 votes)
12 views42 pages

Document 1

Uploaded by

Aman Goda
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)
12 views42 pages

Document 1

Uploaded by

Aman Goda
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/ 42

1

1
2

TABLE OF CONTENTS

Sr. No. Chapters Page No.


1 Certificate
2 Declaration
3 Acknowledgement
4 Introduction
5 Problem Statement
6 Objective
7 Data Flow Diagram
8 Overview of Python
9 Overview of MySQL
10 Project Scope
11 Project Synopsis
12 Project Modules
13 Restaurant
Management System
14 MySQL Database and
Tables
15 MySQL Code
16 MySQL Source Code
17 Conclusion
18 Bibliography

2
3

CERTIFICATE
This is to certify that Ranveer Goda
of Class XII, Air Force School Jorhat,
has successfully completed the
Informatics Practices project titled
Restaurant Management System
during the academic session 2024-
25. This project has been submitted
in partial fulfillment of the
requirements for the Central Board
of Secondary Education AISSC
Examination 2025.
I further certify that the project has
been evaluated and is up to my
expectations and it adheres to the
guidelines provided by CBSE.

INTERNAL EXTERNAL
EXAMINER EXAMINER

(TAPOSH (SHASHANK JAIN)


KARMOKAR)
Examiner No. Examiner No.
639078 2122574

3
4

Date :
PRINCIPAL

4
5

DECLARATION
I, Ranveer Goda hereby declare that I
own the full responsibility for the all the
information and results provided in the
project titled - “Restaurant
Management System”. It has been
developed successfully by using data
handling concepts like data
management, data visualization, etc.
provided in python programming
language and along with its required
libraries such as Pandas, NumPy,
SQLAlchemy, MySQL Connector, etc. at
AIR FORCE SCHOOL JORHAT in complete
fulfillment of project (curriculum of
Central Board of Secondary Education
CBSE of Informatics Practices conducted
by CBSE) for the academic session 2024-
25.
I also hereby declare that this project
work has neither been submitted to any
other board nor published at any time by
me in the past.

5
6

Ranveer Goda
Roll No.
Class XII
AIR FORCE SCHOOL
JORHAT

6
7

ACKNOWLEDGEMENT

I would like to express my deep


sense of gratitude to all those who
supported me throughout the
completion of this project.
I am sincerely grateful to Mrs.
Moushumi Borbora, Principal of Air
Force School Jorhat, and Mr. Taposh
Karmakar, PGT Informatics
Practices, Air Force School Jorhat, for
their encouragement and excellent
guidance during the entire project.
I would also like to thank my parents
and friends for their wholehearted
support and encouragement, without
which this project would not have
been successful.
Lastly, I extend my gratitude to the
internet and textbooks, which
provided me with valuable reference
materials.

7
8

INTRODUCTION
The “Restaurant Management
System” is a comprehensive software
solution designed to streamline and
optimize the financial operations of
restaurant businesses. This system
automates payment processes, tracks
transactions, generates detailed
receipts, and maintains an extensive
record of customer orders and financial
history.
By simplifying financial and operational
processes, it minimizes administrative
workload, ensures accuracy in
transactions, and fosters clear
communication between the
management and customers. The
“Restaurant Management System”
plays a crucial role in enhancing the
operational efficiency of restaurants,
promoting accountability and ensuring a
smooth management experience.
Additionally, the “Restaurant
Management System”is designed with
an intuitive and user-friendly interface
tailored for both restaurant staff and

8
9

customers. It simplifies payment


processes, enabling customers to make
payments conveniently while
empowering staff to manage operations
seamlessly. This approach enhances
customer satisfaction and reduces the
administrative burden, contributing to
the overall success and smooth
functioning of restaurant businesses.

9
10

PROBLEM STATEMENT

The manual process of managing


restaurant operations, particularly
financial transactions and customer
orders, is inefficient, prone to errors,
and lacks transparency. This leads to
several challenges, including:
Time-Consuming and Labor-
Intensive:
Tasks such as manual order entry, bill
generation, and financial reconciliation
are slow and require significant effort
from staff, impacting overall efficiency.
Error-Prone Processes:
Manual data entry increases the risk of
human errors, leading to inaccuracies in
orders, billing, and transaction records,
which can result in customer
dissatisfaction.
Challenges in Data Analysis:
Without proper data handling and
management, generating insightful
reports and analyzing key metrics—such
as sales trends, popular menu items,

10
11

and revenue patterns—becomes difficult


and time-consuming.

These inefficiencies highlight the


need for a robust, automated
restaurant management system to
address these challenges effectively.

11
12

OBJECTIVE
The objective of the project is to build an application
program to:
 Facilitate accurate tracking of financial transactions,
ensuring timely payments and minimizing the risk of
discrepancies in restaurant operations.
 Provide reporting tools and analytics to help
administrators analyze sales trends, revenue data, and
customer preferences.
 Offer a robust search facility based on various factors,
such as order details, transaction history, and customer
data.
 Reduce paperwork and manual labor by automating
essential tasks such as billing, order management, and
report generation.
 Enhance transparency in financial and operational
transactions for both staff and customers.
 Ensure increased accuracy and reliability of operational
data through automated processes.
 Promote data consistency across various operational
workflows.
 Strengthen financial and operational data security to
safeguard sensitive information.
 Minimize data redundancy by integrating and managing
information efficiently within the system.

This application program is designed to be user-friendly


and can be easily operated by non-technical personnel,
making it accessible and practical for restaurant staff.

12
13

13
14

OVERVIEW OF PYTHON
Python is a general purpose, dynamic, high-
level, and interpreted programming
language. It supports Object-Oriented
Programming approach to developed
applications. It is simple and easy to learn
and provides lots of high- level data
structures. Guido Van Rossum is known as
the founder of Python programming.

Features of Python:

 Python is a high-level programming


language. It is a free and open- source
language.
 It is an interpreted language, as Python
programs are executed by an interpreter.
 Python programs are easy to understand
as they have a clearly defined syntax and
relatively simple structure.
 Python is case-sensitive. For example,
NUMBER and number are not the same in
Python.
 Python has a rich library of pre-defined
functions.
 Python is portable and platform
independently, means it can run on
various operating systems and hardware
platforms.

14
15

 Python is also helpful in web


development. Many popular web services
and applications are built using python.
 Python uses indentation for blocks and
nested blocks.

15
16

OVERVIEW OF MYSQL
MySQL is a relational database
management system (RDBMS). It is
pronounced as “My Sequel”. MySQL was
originally founded and developed in
Sweden by David Axmark, Allan Larsson
and Michael Widenius, who had worked
together since the 1980s.
Characteristics of MySQL:
 MySQL is released under an open-
source license, so it is customizable.
 It requires no cost or payment for its
usage.
 MySQL has superior speed, is easy to
use and is reliable.
 MySQL uses a standard form of the
well-known ANSI-SQL standards.
 MySQL is a platform independent
application which works on many
operating systems like Windows,
UNIX, LINUX, etc. and has
compatibility with many languages
including JAVA, C++, PHP, PERL, etc.
 MySQL is an easy to install RDBMS
and is capable of handling large data
sets. Since MySQL is released under
any open-source license, it does not

16
17

require any cost or payment for its


usage. Anyone can download and
use this software from specific
location on Internet.

17
18

PROJECT SCOPE
The Restaurant Management System project aims to
revolutionize and streamline restaurant operations by
automating key processes and improving efficiency. The
application offers the following scope:

 Develop a comprehensive system that automates order


management, billing, and financial tracking within
restaurants.
 Integrate diverse payment methods, including online
transactions, credit/debit cards, and cash payments.
 Implement automated algorithms for accurate bill
generation based on menu items, taxes, and discounts.
 Include mechanisms for tracking and managing
cancellations, refunds, and adjustments.
 Facilitate real-time tracking of sales, inventory, and
operational metrics.
 Design a user-friendly interface to ensure ease of use for
both staff and customers.
 Provide a highly secure system to protect sensitive
customer and financial data.
 Ensure no redundancy in data storage by optimizing
database management.
 Significantly reduce manual labor by automating
repetitive tasks.
 Enhance operational efficiency, making processes time-
efficient and accurate.

This project scope ensures that the system addresses the


operational needs of restaurants while being easy to use and
secure for all stakeholders involved.

18
19

AIR FORCE SCHOOL JORHAT


INFORMATICS PRACTICES (065)
PARTIAL PRACTICAL PROJECT FOR XII - AISSCE 2025
PROJECT SPECIFICATION AND SYNOPSIS
Restaurant Management System

1. Title: Restaurant Management System using Python, Pandas, Matplotlib, and MySQL

2. Objective:

The aim of this project is to create a Restaurant Management System that allows users to
manage restaurant operations, including order management, menu display, billing, and sales
reporting. This project will utilize Python for the core logic and interface, Pandas for
handling data manipulation, Matplotlib for generating visual reports, and MySQL as the
database for storing information such as menu items, orders, and sales.

3. Project Description:

The Restaurant Management System is a menu-driven application that helps manage


various restaurant operations. The system allows users to perform tasks such as viewing the
menu, placing orders, generating bills, and visualizing sales data through graphs. It will also
have an admin interface to update the menu and view sales trends. The application will
feature integration with a MySQL database to store information about the restaurant’s menu,
orders, and billing, while Pandas will be used to process the data and Matplotlib to generate
visual reports (e.g., sales trends).

4. Technology Tools:

 Front-end: Python (Console-based, menu-driven interface)


 Back-end: MySQL (for storing restaurant data)
 Data Handling: Pandas (for managing and manipulating data)
 Data Visualization: Matplotlib (for generating charts and graphs)
 Database Connection: MySQL Connector for Python (to interact with the MySQL
database)
 Other Tools: Python libraries like Pandas (for reporting and
data handling)

5. Features:

 Menu Display: The user can view the available dishes with prices and categories.
 Order Placement: Customers can place orders by selecting items from the menu.
 Billing System: A bill is generated after placing an order, calculating the total with
taxes.

19
20

 Admin Panel: The admin can manage the menu (add, remove, or update items) and
view sales data.
 Sales Reports: Using Matplotlib, the admin can generate sales reports, including total
revenue, most ordered items, and daily/weekly sales trends.

6. Functional Requirements:

 User Functions:
o View menu items with details (price, category)
o Place orders by selecting items
o View the bill with itemized details and total cost
 Admin Functions:
o Add new menu items
o Remove or update existing menu items
o View sales reports (total orders, revenue, top-selling items) through graphical
representations

7. Non-Functional Requirements:

 Performance: The system must quickly process orders and handle multiple
transactions without delay.
 Security: Admin access to menu updates and sales reports must be restricted.
 User Experience: The interface should be easy to navigate, providing clear menu-
driven options.

Suggested Menus for the Restaurant Management System :

1. Main Menu:

 View Menu
o Display all available dishes along with their prices and categories
(e.g., appetizers, main courses, desserts, drinks).
 Place Order
o Select items from the menu by item ID
o Enter quantity for each item
o Display the order summary
 Generate Bill
o Display the final bill with a breakdown of items, quantity, individual prices,
and total cost including tax.
 Admin Login
o Enter admin credentials to access the admin menu.
 Generate Report
 Data Visualisation
 Export/Import Data
 User & Password Management
 Exit

2. Admin Menu:

20
21

 Add Menu Item


o Add new dishes to the menu by entering the dish name, category, price, and
availability status.
 Update Menu Item
o Modify details of an existing menu item (price, availability, category).
 Remove Menu Item
o Delete an item from the menu if it is no longer available.
 View Sales Reports (using Matplotlib)
o Generate and display graphical reports on:
 Daily/weekly sales totals
 Most ordered items
 Total revenue generated

Suggested Database Design and Table Details :

1. Table: menu_items

This table stores details of the restaurant's available menu items.

Column
Data Type Constraints Description
Name
PRIMARY KEY, Unique ID for each menu
item_id INT
AUTO_INCREMENT item.
item_name VARCHAR(100) NOT NULL Name of the dish.
The category of the dish (e.g.,
category VARCHAR(50) NOT NULL
appetizer, main course).
DECIMAL(10,
price NOT NULL Price of the dish.
2)
Indicates if the item is
available BOOLEAN DEFAULT 1
available.

2. Table: orders

This table stores the details of each order placed by customers.

Column
Data Type Constraints Description
Name
PRIMARY KEY,
order_id INT Unique ID for each order.
AUTO_INCREMENT
Date and time when the
order_date DATETIME NOT NULL
order was placed.
Contact Number of a
Mobile CHAR(10) NOT NULL
Customer
Total amount for the
total_amount DECIMAL(10, 2) NOT NULL
order.

21
22

3. Table: order_items

This table stores individual items within each order, representing the many-to-many
relationship between orders and menu items.

Column Name Data Type Constraints Description


PRIMARY KEY, Unique ID for each
order_item_id INT
AUTO_INCREMENT order item.
FOREIGN KEY REFERENCES The order to which this
order_id INT
orders(order_id) item belongs.
FOREIGN KEY REFERENCES
item_id INT The menu item ordered.
menu_items(item_id)
Quantity of the item
quantity INT NOT NULL
ordered.
DECIMAL(10, Price of the item at the
price NOT NULL
2) time of the order.
DECIMAL(10, Total price (quantity *
total_price NOT NULL
2) price).

4. Table: sales_reports

This table stores daily sales data for reporting purposes.

Column
Data Type Constraints Description
Name
PRIMARY KEY, Unique ID for each
report_id INT
AUTO_INCREMENT report.
report_date DATE NOT NULL Date of the report.
DECIMAL(10, Total revenue for the
total_sales NOT NULL
2) day.
Total number of orders
total_orders INT NOT NULL
for the day.

Data Handling with Pandas

 Menu DataFrame: Pandas will be used to create and manipulate a menu DataFrame,
which can be queried and filtered by category, price, and availability.
 Orders DataFrame: An orders DataFrame will be used to store orders temporarily
before committing them to the database, and to perform quick analyses (e.g., total
revenue per customer).
 Sales Reports: Daily sales data will be stored in a Pandas DataFrame, allowing for
easy analysis and visualization using Matplotlib.

Visual Reporting with Matplotlib

22
23

 Sales Trends: Matplotlib will be used to generate graphs for


daily, weekly, and monthly sales, showing revenue trends.
 Popular Dishes: A bar chart will show the most ordered items in the
restaurant.
 Revenue by Category: Pie charts will visualize the contribution
of different dish categories (e.g., appetizers, main course, dessert)
to the overall revenue.

Conclusion:

The Restaurant Management System is designed to streamline the daily


operations of a restaurant by automating order processing, menu
management, and billing. By integrating Python, Pandas, Matplotlib, and
MySQL, this project provides an efficient solution for handling restaurant
data, generating sales reports, and maintaining a secure admin panel for
updating menu items. The system offers a simple and user-friendly interface,
making it accessible for both staff and management. This project
demonstrates the practical application of programming and database skills,
showcasing how technology can simplify and enhance business operations in
the food service industry.

Good luck with your project!

23
24

PYTHON
MODULES
import pandas as pd
import mysql.connector
from datetime import datetime
from tabulate import tabulate
import matplotlib.pyplot as plt

24
25

Restaurant Management
System (PYTHON)
import pandas as pd
import mysql.connector
from datetime import datetime
from tabulate import tabulate
import matplotlib.pyplot as plt

#Connecting to MySQL database


mydb=mysql.connector.connect(host='localhost',
user='root',
password='root',
database='restrnt102'
);
mycursor=mydb.cursor()
#Only for the menu table/ displaying it
def only_item_menu():
query="""select item_ID,Category,Item_name,description,price,item_type
from menu_items where available='yes';"""
mycursor.execute(query)
data=mycursor.fetchall()
header=['Item_Id','Category','Item_Name','Description','Price(₹)','Item Type']
print(tabulate(data,header,tablefmt='pretty'))
#View Menu:
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""")
userinput=input("\n-->>| Enter Your Choice: ")
if userinput=="1":
only_item_menu()
elif userinput=="2":
preference=input("Enter Your Preference (Veg/Non veg): ").strip()
if preference.lower() in ['veg','non veg','nonveg']:
query="""select item_ID,Category,Item_name,description,price,item_type
from menu_items where item_type=%s and available='yes';"""
mycursor.execute(query,(preference,))
data=mycursor.fetchall()
header=['Item_Id','Category','Item_Name','Description','Price(₹)','Item
Type']
print(tabulate(data,header,tablefmt='pretty'))
else:
25
print("Invalid Item Type...")
elif userinput=="3": 1
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!")

#Place Orders:

def place_order():
print(" Placing an Order...")
mobile_no = input(" >>Enter Your Mobile no. :")

if mobile_no.isdigit() and len(mobile_no) == 10:


print("Mobile Number Valid")
only_item_menu()

order_details = []
order_total = 0

mycursor.execute("""
SELECT order_id, total_amount
FROM orders
WHERE mobile = %s AND DATE(order_date) = DATE(NOW())
""", (mobile_no,))
existing_order = mycursor.fetchone()
if existing_order:
last_id = existing_order[0]
order_total = existing_order[1]
else:
mycursor.execute("""
INSERT INTO orders (order_date, mobile, total_amount)
VALUES (NOW(), %s, 0);
""", (mobile_no,))
mydb.commit()
last_id = mycursor.lastrowid

if last_id is None:
print("Error: Failed to retrieve a valid order ID. Please try again.")

1
while True: 2
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()

# Displaying the order summary


if order_details:
print("\n >>Order Summary:")
headers = ['Item Name', 'Price (₹)', 'Quantity', 'Total Price (₹)']
print(tabulate(order_details, headers, tablefmt='pretty'))
else:
print(" >>No item ordered!")
else:
print("Invalid Mobile Number")

2
#Bill Generation: 3

def generate_bill():
print("\n")
print(" ~~~~~~~~~~~~~~~~~~ ")
print("┍<<-------------->>| ITEMS MENU |<<-------------->>┒ ")
print("| ~~~~~~~~~~~~~~~~~~ | ")
mobileno = int(input("--->>| Enter Mobile no.: "))
if len(str(mobileno)) != 10 :
print("!!| Invalid phone number! It must be a 10-digit number.|!!")
Return
mycursor.execute("SELECT mobile FROM orders WHERE mobile = %s;", (mobileno,))
data = mycursor.fetchall()
while True:
if data:
print(" -------------------------------------- ")
print(" 1. Today's Bill 2. Previous Bill ")
print(" 3. Exit")
userinput = input("--->>| Enter Your choice : ")
# Define the common query to fetch bill details for today's or previous orders
if userinput == "1":
query = """
SELECT m.item_name, o.quantity, m.price, o.total_price, DATE(r.order_date)
FROM order_items o
JOIN orders r ON r.order_id = o.order_id
JOIN menu_items m ON m.item_id = o.item_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 == "2":
query = """
SELECT m.item_name, o.quantity, m.price, o.total_price, DATE(r.order_date)
FROM order_items o
JOIN orders r ON r.order_id = o.order_id
JOIN menu_items m ON m.item_id = o.item_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]

3
if subtotal is not None: 4
gst_amt = subtotal * 5 / 100 # Standard GST imposed on billing: 5%
subtotal += gst_amt # Total amount after GST
# Get the current date
mycursor.execute("SELECT DATE(NOW());")
current_date = mycursor.fetchone()[0]
formatted_date = current_date.strftime("%d-%m-%Y")
print("-------- TAX INVOICE ---------")
print("\nDate:", formatted_date)
# Print the bill summary
print(tabulate(bill, headers=['Particulars', 'Qty', 'Rate', 'Amount',
'Order date'], tablefmt='plain'))
print(' ---------------------')
print(" Sub Total: ₹", subtotal - gst_amt)
print(" GST @5%: ₹", gst_amt)
print("----------------------------------------------")
print(f" Total amount : ₹{subtotal}\n")
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

#Adding new item to Menu:

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 :"))
item_type=input("Is This Item Vegetarian? (yes/no) :")
availability="Yes" #default to available
#item_type=item_type.lower()
if price<=0:
print("Price cannot be zero or negative.")

if item_type.lower()=='yes':
item_type='VEG'
elif item_type.lower()=='no':
item_type='NON VEG'
else:
print('Invalid Choice.try again later')

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.")

4
#defining updatation of item 5
def update_menu():
item_id=input("\nEnter Item Id to be updated :")
mycursor.execute("Select *from menu_items where item_id= %s", (item_id,))
check1= mycursor.fetchone()
if check1:
print("\nWhat Do You want to Update")
print("\n1.Category")
print("2.Price")
print("3.Availability")
userinput=input("Select an Option :")
if userinput=="1":
category=input("Enter new category :")
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','Price(₹)','Available']
print(tabulate([data],header,tablefmt='pretty'))
print("\nIs The data inserted correct.(yes/no): ")
choice=input("Enter a Choice: ")
if choice.lower()=='yes':
query="update menu_items set category=%s where item_id=%s;"
val=(category,item_id)
mycursor.execute(query,val)
mydb.commit()
print("Updatation Completed...")
elif choice.lower()=='no':
update_menu()
else:
print("Not a valid Option!")
admin_menu()
elif userinput=="2":
price=int(input("Enter New Price :"))
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','Price(₹)','Available']
print(tabulate([data],header,tablefmt='pretty'))
print("\nIs The data inserted correct.(yes/no): ")
choice=input("Enter a Choice: ")
if choice.lower()=='yes' and price>0:
query="update menu_items set price=%s where item_id=%s;"
val=(price,item_id)
mycursor.execute(query,val)
mydb.commit()
print("Updatation Completed...")
elif choice.lower()=='no':
update_menu()

else:
print("Price Cannot be Zero or Negative")

5
elif userinput=="3":
availability=input("Is it Available? (yes/no)6 :")
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','Price(₹)','Available']
print(tabulate([data],header,tablefmt='pretty'))
print("\nIs The data inserted correct.(yes/no): ")
choice=input("Enter a Choice: ")
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()=='yes' and availability.lower()=='no':
query="update menu_items set available='no' 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 choice!!")
else:
print("Invalid Option!!")
else:
print("Invalid Item Id ...")

#Remove Item from Menu List:


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','Description','Price(₹)','Available']
print(tabulate([data],header,tablefmt='pretty'))

choice=input("\nIs The data to be deleted is correct.\nEnter a Choice


(yes/no): ")
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.")
6
#weekly sales plot: 7
def weekly_sales():
year= int(input(" -->>Enter Year : "))
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")

#weekly Orders Plot:

def weekly_orders():
query="""select year(report_date) as sale_year,week(report_date) as
sale_week,
sum(total_orders) as total_orders
from sales_reports
GROUP BY sale_year, sale_week
order by sale_year,sale_week;"""
mycursor.execute(query)
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)

7
d_sales['Sale_Date'] = sale_dates
d_sales['Sale_Date_Str'] = d_sales['Sale_Date'].dt.strftime('Week
8
%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")

#Monthly Sales Plot:

def monthly_sales():
query="""select year(report_date) as
sale_year,MONTH(report_date) as sale_month,
sum(total_sales) as total_sales
from sales_reports
GROUP BY sale_year, sale_month
order by sale_year,sale_month;"""
mycursor.execute(query)
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: 8
print("No Monthly Sales Record ")
#Monthly Orders Plot: 9

def monthly_orders():
query="""select Year(report_date) as sale_year,month(report_date)
as sale_month,
sum(total_orders) as total_orders
from sales_reports
GROUP BY sale_year, sale_month
order by sale_year,sale_month;"""
mycursor.execute(query)
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")

#Most Ordered Plot (pie):

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)
9
plt.pie(df['Quantity_ordered'],labels=df['Item_Name'],autopct='%1.1f
10
%%',shadow=True,startangle=160,
textprops={'fontsize': 7,'weight':'bold'},
wedgeprops={'linewidth': 1, 'edgecolor': 'white'})
plt.title("Total Quantity Ordered for Each Item")
plt.show()
else:
print("No Data Found")

#Daily Sales (Using Date):


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 Date','Total Sales(₹)','Total
Order'],tablefmt='pretty'))
else:
print(f"No data Found for report date:{report_date}")

#Average Revenue:
def Avg_revenue():
query="select
count(order_item_id),sum(total_price),round(avg(total_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")
#Prime Hours:
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='pretty'))
10
for i in range(len(df)): 11
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")

#overall Sales Report Menu:


def Sales_report_menu():
while True:
print("\n1. Total Weekly Sales 2. Total monthly Sales")
print("3. Daily sales 4. Exit")
userinput=input("\nEnter your Selection: ")
if userinput=="1":
weekly_sales()
elif userinput=="2":
monthly_sales()
elif userinput=="3":
Daily_sales()
elif userinput=="4":
print(" >>Exiting...")
break
else:
print(" >>Invalid Option")

#Overall Orders Menu:


def Orders_report_menu():
while True:
print("1.Total Weekly Orders 2.Total Monthly Orders")
print("3.Most ordered Items 4.Exit")
userinput=input("\n >>Enter your Selection: ")
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")
11
#Report Menu: 12

def 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")

#Admin Login
def Admin_login():
username=input(" >>Enter Username :")
password=input(" >>Enter Password :")
if username=='abc' and password=='abc123':
print("Login successfull")
admin_menu()
else:
print("\nInvalid credentials. Access denied.")

12
#Admin menu: 13

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 | ")
userinput=input("--->>| Select an Option :")
if userinput=="1":
menu_items()
elif userinput=="2":
add_item()
elif userinput=="3":
update_menu()
elif userinput=="4":
remove_item()
elif userinput=="5":
report_menu()
elif userinput=="6":
break
else:
print('Invalid Option')

#Function to display main menu!!


def main_menu():
while True:
print("\n")
print("
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ")
print("┍<<------------->>| Welcome to ROYAL RASOI |
<<------------->>┒ ")
print("|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ")
print("| 1. View Item Menu 2. Place Order | ")
print("| 3.Generate Bill 4.Admin Login | ")
print("| 5.Exit | ")
userinput=input("|---->>| Please enter Your choice :")
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

13
elif userinput=="4": 14
Admin_login() #Function for Admin
menu(Restricted)
elif userinput=="5":
print("Exiting The System...")
break
else:
print("Invalid option. Please try again.")
main_menu()

14
15

15
16

16
17

17

You might also like