COURIER SERVICE MANAGEMENT
S.NO. TOPIC PAGE NO.
1. OBJECTIVE OF THE PROJECT
2. HARDWARE / SOFTWARE
REQUIREMENT
3. FUNCTIONS
4. MODULES
SOURCE CODE
5.
OUTPUT
6.
7. BIBLIOGRAPHY
OBJECTIVE OF THE PROJECT:
The objective of this project is to develop a
Python-based application for courier services. The
project aims to automate and streamline the process of
managing courier deliveries, tracking shipments, and
improving customer service. It seeks to leverage
Python's capabilities to create an efficient, user-friendly
system that enhances operational efficiency, reduces
errors, and provides real-time updates to customers.
The project also aims to apply theoretical knowledge of
programming and data analysis to solve real-world
business problems in the courier industry.
HARDWARE REQUIRMENTS:
Processor: Intel core i3 or later or compatible
Hard disk: 410GB or more
RAM: 1GB or more
Printer: Any
Monitor: SVGA colour monitor (touch
screen or simple)
Pointing Device: Touch pad or keys
SOFTWARE REQUIREMENTS:
Python 3.9.0 or higher
MYSQL 8.0
FUNCTION:
A function isa block of code, which only runs when
it is called. You can pass data, known as
parameters, into a function. A function can return
data as a result.
1. Built-in functions: These predefined
functions are always available for use. Eg:-
len(),int() etc.
2. Functions defined in modules: These are
predefined functions available in specific
modules and can be used only when that
module is imported. Eg:- random. randit()
gives a random integer value in a given
interval. This is available in the random
module.
3. User defined functions: the user defines
these function
functions used in this project:
Cursor ()
Execute ()
Print ()
Fetchall ()
Commit ()
Fetchone ()
Connect ()
MODULE:
A python module is a file containing python
definitions and statements. A module can define
functions, classes, and variables.
MODULES USED IN THIS PROJECT:
MySQl. connector: this method sets up a connection,
establishing a session with the MySQl server. If no
arguments are given, it uses the already configured or
default values. A connection with the MySQl server can
be established using either
the mysql.connector. connect()method or
the mysql.connector. MySQLConnection()
Source Code:
import mysql.connector
import random
from datetime import datetime, date
# Establish the database connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Tiger"
)
cursor = conn.cursor()
# Create Database and Tables if they don't exist
def create_tables():
cursor.execute('''
CREATE DATABASE IF NOT EXISTS courier_service;
''')
cursor.execute('''
USE courier_service;
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL
);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS customers (
customer_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
name VARCHAR(100) NOT NULL,
address VARCHAR(255) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(15) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS couriers (
courier_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
contact_info VARCHAR(255) NOT NULL
);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
origin VARCHAR(255) NOT NULL,
destination VARCHAR(255) NOT NULL,
ship_date DATE NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS shipments (
shipment_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
order_id INT,
courier_id INT,
origin VARCHAR(255) NOT NULL,
destination VARCHAR(255) NOT NULL,
ship_date DATE NOT NULL,
delivery_date DATE,
FOREIGN KEY (customer_id) REFERENCES
customers(customer_id),
FOREIGN KEY (courier_id) REFERENCES
couriers(courier_id),
FOREIGN KEY (order_id) REFERENCES orders(order_id)
);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS tracking (
tracking_id INT AUTO_INCREMENT PRIMARY KEY,
shipment_id INT,
status VARCHAR(255) NOT NULL,
location VARCHAR(255) NOT NULL,
timestamp DATETIME NOT NULL,
FOREIGN KEY (shipment_id) REFERENCES
shipments(shipment_id)
);
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS billing (
bill_id INT AUTO_INCREMENT PRIMARY KEY,
shipment_id INT,
amount DECIMAL(10, 2) NOT NULL,
billing_date DATE NOT NULL,
FOREIGN KEY (shipment_id) REFERENCES
shipments(shipment_id)
);
''')
# Call create_tables() function to set up database and tables
create_tables()
# Function to generate a random ID
def generate_random_id():
return random.randint(1000, 9999)
# Function to register a new user
def register_user(username, password):
query = "INSERT INTO users (username, password) VALUES
(%s, %s)"
values = (username, password)
cursor.execute(query, values)
conn.commit()
print("********** User registered successfully! ***********")
# Function to log in an existing user
def login_user(username, password):
query = "SELECT user_id FROM users WHERE username = %s
AND password = %s"
values = (username, password)
cursor.execute(query, values)
result = cursor.fetchone()
if result:
print("###### Login successful! ########")
return result[0] # Return the user_id
else:
print("XXXXXXX Invalid username or password.
XXXXXXXX")
return None
# Function to add a customer's details
def add_customer(user_id, name, address, email, phone):
customer_id = generate_random_id() # Generate a random
customer ID
query = "INSERT INTO customers (customer_id, user_id, name,
address, email, phone) VALUES (%s, %s, %s, %s, %s, %s)"
values = (customer_id, user_id, name, address, email, phone)
cursor.execute(query, values)
conn.commit()
print(f"@@@@@@@@@ Customer added successfully!
\nCustomer ID: {customer_id} @@@@@@@@@@")
# Function to add a courier's details
def add_courier(name, contact_info):
query = "INSERT INTO couriers (name, contact_info) VALUES
(%s, %s)"
values = (name, contact_info)
cursor.execute(query, values)
conn.commit()
courier_id = cursor.lastrowid
print(f"Courier added successfully! \nCourier ID: {courier_id}")
return courier_id
# Function to add a shipment
def add_shipment(customer_id, order_id, courier_id, origin,
destination, ship_date, delivery_date=None):
query = "INSERT INTO shipments (customer_id, order_id,
courier_id, origin, destination, ship_date, delivery_date) VALUES
(%s, %s, %s, %s, %s, %s, %s)"
values = (customer_id, order_id, courier_id, origin, destination,
ship_date, delivery_date)
cursor.execute(query, values)
conn.commit()
shipment_id = cursor.lastrowid
print(f"Shipment added successfully! \nShipment ID:
{shipment_id}")
return shipment_id
# Function to generate a bill for a shipment
def generate_bill(shipment_id, distance):
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Tiger"
)
cursor = conn.cursor()
rate_per_km = 10 # Define a rate per kilometer
amount = distance * rate_per_km
billing_date = date.today()
query = "INSERT INTO billing (shipment_id, amount,
billing_date) VALUES (%s, %s, %s)"
values = (shipment_id, amount, billing_date)
cursor.execute(query, values)
conn.commit()
print("Bill generated successfully!")
# Function to validate date format
def validate_date(date_text):
try:
datetime.strptime(date_text, '%Y-%m-%d')
return True
except ValueError:
return False
# Function to place an order and view its details
def place_order(user_id, origin, destination, ship_date):
# Validate date format before proceeding
if not validate_date(ship_date):
print("Error: Enter the date in the format given (YYYY-MM-
DD).")
return
try:
cursor = conn.cursor(buffered=True)
# Insert the order into the database
query = "INSERT INTO orders (user_id, origin, destination,
ship_date) VALUES (%s, %s, %s, %s)"
values = (user_id, origin, destination, ship_date)
cursor.execute(query, values)
conn.commit()
order_id = cursor.lastrowid
print(f">>>>> Order placed successfully! Your order ID is:
{order_id} <<<<<")
return order_id
except mysql.connector.Error as err:
print(f"Error: {err}")
conn.rollback() # Rollback in case of error
finally:
# Ensure any unread results are handled
if cursor and cursor.with_rows:
cursor.fetchall()
# Ensure cursor and connection are closed
if cursor:
cursor.close()
if conn.is_connected():
conn.close()
def view_order(order_id):
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Tiger"
)
cursor = conn.cursor()
try:
# Ensure the connection is available
if not conn.is_connected():
conn.reconnect(attempts=3, delay=5) # Reconnect if the
connection is not available
cursor = conn.cursor(buffered=True)
# View the order details
query = '''
SELECT o.order_id, s.shipment_id, o.origin,
o.destination, o.ship_date, s.delivery_date, b.amount,
b.billing_date
FROM orders o
LEFT JOIN shipments s ON o.order_id = s.order_id
LEFT JOIN billing b ON s.shipment_id = b.shipment_id
WHERE o.order_id = %s
'''
cursor.execute(query, (order_id,))
result = cursor.fetchone()
if result:
print(f"\nOrder ID: {result[0]}, \nShipment ID: {result[1]},
\nOrigin: {result[2]}, \nDestination: {result[3]}, \nShip Date:
{result[4]}, \nDelivery Date: {result[5]}, \nAmount: {result[6]},
\nBilling Date: {result[7]}\n")
else:
print("\nNo order found with the specified ID.\n")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
# Ensure any unread results are handled
if cursor and cursor.with_rows:
cursor.fetchall()
# Ensure cursor and connection are closed
if cursor:
cursor.close()
if conn.is_connected():
conn.close()
def calculate_distance(origin, destination):
# In a real-world scenario, you would replace this with actual
distance calculation logic
return random.randint(1, 500)
def generate_bill(order_id):
#cursor = None
try:
# Ensure the connection is available
if not conn.is_connected():
conn.reconnect(attempts=3, delay=5) # Reconnect if the
connection is not available
cursor = conn.cursor(buffered=True)
# Retrieve the shipment_id, origin, and destination for the
given order ID
query = "SELECT s.shipment_id, o.origin, o.destination
FROM shipments s JOIN orders o ON s.order_id = o.order_id
WHERE s.order_id = %s"
cursor.execute(query, (order_id,))
result = cursor.fetchone()
if result:
shipment_id, origin, destination = result
# Calculate the distance
distance = calculate_distance(origin, destination)
# Define a billing rate per unit distance
rate_per_km = 5 # Example rate
# Calculate the amount
amount = distance * rate_per_km
# Insert the bill into the billing table
billing_date = datetime.now().strftime('%Y-%m-%d
%H:%M:%S')
query = "INSERT INTO billing (shipment_id, amount,
billing_date) VALUES (%s, %s, %s)"
values = (shipment_id, amount, billing_date)
cursor.execute(query, values)
conn.commit()
print(f"Bill generated successfully!\nAmount:
{amount}\nBilling Date: {billing_date}")
else:
print("Order ID not found.")
except mysql.connector.Error as err:
print(f"Error: {err}")
conn.rollback() # Rollback in case of error
finally:
# Ensure any unread results are handled
if cursor and cursor.with_rows:
cursor.fetchall()
# Ensure cursor and connection are closed
if cursor:
cursor.close()
if conn.is_connected():
conn.close()
def main():
user_id = None # Ensure user_id is defined before usage
while True:
print("\nCourier Service Management System - Customer
Interface")
print("1. Register")
print("2. Login")
print("3. Add Customer Details")
print("4. Place Order")
print("5. View Order")
print("6. Generate Bill")
print("7. Exit")
choice = int(input("\nEnter your choice: "))
if choice == 1:
username = input("Enter username: ")
password = input("Enter password: ")
register_user(username, password)
elif choice == 2:
username = input("Enter username: ")
password = input("Enter password: ")
user_id = login_user(username, password)
elif choice == 3:
if user_id:
name = input("Enter name: ")
address = input("Enter address: ")
email = input("Enter email: ")
phone = input("Enter phone: ")
add_customer(user_id, name, address, email, phone)
else:
print("You need to log in first.")
elif choice == 4:
if user_id:
origin = input("Enter origin: ")
destination = input("Enter destination: ")
ship_date = input("Enter ship date (YYYY-MM-DD): ")
order_id = place_order(user_id, origin, destination,
ship_date)
# Display only the order ID after placing the order
if order_id:
print(f"Order placed successfully! Your order ID is:
{order_id}")
else:
print("You need to log in first.")
elif choice == 5:
order_id = int(input("Enter the order ID: "))
view_order(order_id) # View order details
elif choice == 6:
order_id = int(input("Enter the Order ID: "))
generate_bill(order_id) # Generate bill based on order ID
elif choice == 7:
print("Exiting the system.")
break
else:
print("Invalid choice. Please try again.")
# Run the main function
main()
output:
BIBLIOGRAPHY:
NCERT class XI &XII Text books
Sumita Arora Computer Textbook
http://ncert.nic.in
www.google.com
Learning MySQL and MariaDB by Russell J. T.Dyer “Head First SQl”Lynn