0% found this document useful (0 votes)
7 views38 pages

Computer Science Project - Copy

The Pharmacy Management System is a Python-based application designed for effective pharmacy management, focusing on inventory control and sales transactions, integrated with a MySQL database. Key features include adding and managing medications, billing, input validation, and monitoring stock levels, which enhance operational efficiency and reduce human error. The document outlines the software and modules used, along with source code and functionalities that support the system's objectives.

Uploaded by

kraniumjanagan
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)
7 views38 pages

Computer Science Project - Copy

The Pharmacy Management System is a Python-based application designed for effective pharmacy management, focusing on inventory control and sales transactions, integrated with a MySQL database. Key features include adding and managing medications, billing, input validation, and monitoring stock levels, which enhance operational efficiency and reduce human error. The document outlines the software and modules used, along with source code and functionalities that support the system's objectives.

Uploaded by

kraniumjanagan
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/ 38

PHARMACY MANAGEMENT SYSTEM

~~~
INDEX

S.NO. CONTENT PAGE NO.

1. Synopsis 2

2. Software’s used 3-5

3. Modulus used 6-8

4. Source code 9-22

5. Output 23-34

6. Conclusion 35

7. Bibliography 36

~1~
SYNOPSIS

The Pharmacy Management System is a comprehensive Python-based software


application designed to efficiently handle various aspects of pharmacy management,
including inventory control and sales transactions. Integrated with a MySQL database,
the system provides a user- friendly command-line interface, making it accessible for
pharmacy staff. Key features include the ability to add new pharmaceutical products to
the inventory, edit existing product information, and remove items when necessary. The
system supports rigorous input validation to ensure data integrity, allowing for real-time
updates, viewing available quantities, and listing low-stock alerts. Additionally, it
monitors medications nearing expiry to minimize waste and ensure patient safety.

Billing capabilities enable the generation of detailed bills for customer purchases, accurately
calculating totals while updating inventory levels. A search function facilitates quick
retrieval of medications by name or category, enhancing operational efficiency. The
application
incorporates robust error handling and logging mechanisms to track runtime issues,
making maintenance and debugging manageable. By automating routine pharmacy
processes and
providing timely insights into stock and sales, the system significantly reduces human error
and enhances customer satisfaction.

Developed using Python and MySQL, this solution offers an efficient and scalable
database for managing daily pharmacy operations. It aims to improve operational
efficiency, enhance inventory management, and streamline the billing process, providing
a valuable tool for
pharmacies to manage their resources effectively. The application lays a strong
foundation for future improvements, such as implementing user authentication,
graphical interfaces, and advanced reporting features, all aimed at adapting to evolving
healthcare needs and elevating pharmacy management standards. Overall, the Pharmacy
Management System serves as an essential resource for pharmacies, ensuring accurate

~2~
transactions and effective resource management.
SOFTWARES USED

1. Python:

Description

Python is a high-level programming language known for its simplicity and readability. It is widely
used for various applications, including web development, data analysis, artificial intelligence,
and automation.

Uses in the Program

In the Pharmacy Management System, Python serves as the primary programming language to
implement the application's logic, including user interactions, data processing, and database
management. The entire application is built using Python, allowing for easy maintenance and
scalability

2. MySQL:

Description

MySQL is an open-source relational database management system (RDBMS) that uses


Structured Query Language (SQL) for managing and manipulating data. It is widely used for web
applications and data storage.

Uses in the Program

In the Pharmacy Management System, MySQL is used to store and manage medication data,
including details such as name, quantity, rate, category, manufacturing date, and expiry date.
The application performs various SQL operations, such as inserting, updating, deleting, and
retrieving medication records.

~3~
3. MySQL Connector for Python:

Description

The MySQL Connector for Python is a library that allows Python applications to connect to
MySQL databases. It provides a Pythonic interface for executing SQL queries and managing
database connections.

Uses in the Program

In the Pharmacy Management System, the MySQL Connector is used to establish connections to
the MySQL database, execute SQL queries, and manage transactions. It facilitates all database
operations, including adding, viewing, updating, and deleting medication records.

4. Command Line Interface (CLI):

Description

A Command Line Interface (CLI) is a text-based interface used to interact with software and
operating systems. Users input commands through a console or terminal to perform specific
tasks.

Uses in the Program

In the Pharmacy Management System, the CLI is used to present a menu of options to the user,
allowing them to perform various operations such as adding medications, viewing stock, and
generating bills. User input is collected through the command line, and feedback is provided in
text format.

5. Datetime:

Description

~4~
The datetime module in Python provides classes for manipulating dates and times. It allows for
easy handling of date and time operations.

Uses in the Program

In the Pharmacy Management System, the datetime module is used to handle and validate
manufacturing and expiry dates of medications. It ensures that dates are correctly formatted
and allows for comparisons between dates.

6. File I/O

Description

File Input/Output (I/O) refers to the operations of reading from and writing to files on a storage
medium. It is essential for data persistence and management.

Uses in the Program

In the Pharmacy Management System, file I/O is used to export medication reports to text files
and JSON files. This allows for easy data backup and sharing, ensuring that medication records
can be preserved outside the database.

7. Error Handling

Description

Error handling refers to the process of responding to and managing errors that occur during the
execution of a program. It is essential for maintaining the stability and reliability of an
application.

Uses in the Program

In the Pharmacy Management System, error handling is implemented to manage database


connection failures, input validation errors, and other exceptions. The application logs errors to
a file, allowing developers to review and address issues as they arise.

~5~
MODULUS USED

1. mysql.connector:
 Purpose: Connects Python applications to MySQL databases.

 Key Features:

 Manages database connections.

 Supports executing SQL queries and fetching results.

 Usage: Used throughout the program to perform CRUD (Create, Read, Update, Delete)
operations on medication records.

2. datetime:
 Purpose: Handles date and time operations.

 Key Features:

 Provides classes for manipulating dates and times.

 Supports formatting and parsing of date strings.

 Usage: Validates and processes manufacturing and expiry dates of medications to ensure
correct data entry.

3. logging:
 Purpose: Provides a framework for logging events and errors.

 Key Features:

 Supports multiple log levels (DEBUG, INFO, ERROR).

 Configurable output options (e.g., log to files).

~6~
 Usage: Logs errors and important events to a file (pharmacy_errors.log) for
troubleshooting and monitoring.

4. re (Regular Expressions):
 Purpose: Supports pattern matching and string manipulation.

 Key Features:

 Allows complex string matching using patterns.

 Provides functions for searching and replacing substrings.

 Usage: Validates user input in the search_medication function to ensure it contains only
valid charac:ters.

5. json:
 Purpose: Handles JSON data for serialization and deserialization.

 Key Features:

 Provides methods for converting Python objects to JSON format and vice versa.

 Usage: Exports medication data to a JSON file for backup purposes.

6. os:
 Purpose: Provides a way to use operating system-dependent functionality.

 Key Features:

 Supports file and directory management.

 Allows interaction with the operating system.

 Usage: While not explicitly used in the provided code, it can be useful for file operations
and environment management.

7. sys:
 Purpose: Provides access to system-specific parameters and functions.

 Key Features:

 Allows interaction with the Python interpreter.

 Provides functions for manipulating the Python runtime environment.

 Usage: Used to exit the program gracefully with sys.exit().


~7~
8. time:
 Purpose: Provides time-related functions.

 Key Features:

 Supports time manipulation and delays.

 Usage: Used in the generate_bill function to simulate processing delays.

9. copy:
 Purpose: Supports shallow and deep copy operations.

 Key Features:

 Allows duplication of objects.

 Usage: Used to create a backup of medication data before exporting to ensure the
original data remains unchanged.

10. decimal:
 Purpose: Provides support for decimal floating-point arithmetic.

 Key Features:

 Ensures precise decimal representation and arithmetic.

 Usage: Handles monetary values (medication rates) accurately to avoid floating-point


errors.

11. collections:
 Purpose: Implements specialized container datatypes.

 Key Features:

 Provides data structures like named tuples, deques, and counters.

 Usage: Used to create a named tuple for medication records, making it easier to manage
and display medication data.

12. math:
 Purpose: Provides mathematical functions.

 Key Features:

~8~
 Includes functions for mathematical operations like rounding, trigonometry, etc.

 Usage: Used in the generate_bill function to calculate the total cost of medications,
ensuring proper rounding.

CODING

import mysql.connector
from mysql.connector import Error
from datetime import datetime, timedelta
import logging
import re
import json
import time
import copy
import decimal
import collections
import sys

# Setup error logging


logging.basicConfig(filename="pharmacy_errors.log", level=logging.ERROR)

# Named tuple for display (used in view)


Medication = collections.namedtuple("Medication", "id name quantity rate category
manufacturing_date expiry_date")

# ---------- DB Connection ----------


def create_connection():

~9~
try:
return mysql.connector.connect(
host='localhost',
user='root',
password='SSS@1416', # Update with your MySQL password if any
database='pharmacy_db' # Ensure this database exists
)
except Error as e:
logging.error(f"DB connection failed: {e}")
return None

# ---------- Add Medication ----------


def add_medication():
try:
name = input("Enter medication name: ").strip()
category = input("Enter category: ").strip()
quantity_str = input("Enter quantity: ").strip()
rate_str = input("Enter rate: ").strip()
mfg_date_str = input("Enter manufacturing date (YYYY-MM-DD): ").strip()
exp_date_str = input("Enter expiry date (YYYY-MM-DD): ").strip()

# Validate quantity
if not quantity_str.isdigit() or int(quantity_str) < 0:
print("Quantity must be a positive integer.")
return
quantity = int(quantity_str)

# Validate rate
try:

~ 10 ~
rate = decimal.Decimal(rate_str)
if rate < 0:
print("Rate must be a positive number.")
return
except:
print("Invalid rate format.")
return

# Validate dates format


try:
mfg_date = datetime.strptime(mfg_date_str, "%Y-%m-%d").date()
exp_date = datetime.strptime(exp_date_str, "%Y-%m-%d").date()
except ValueError:
print("Invalid date format. Please enter dates in YYYY-MM-DD format.")
return

# Check expiry date not earlier than manufacturing date


if exp_date < mfg_date:
print("Error: Expiry date cannot be earlier than manufacturing date.")
return

connection = create_connection()
if connection:
cursor = connection.cursor()
cursor.execute(
"INSERT INTO medications (name, quantity, rate, category, manufacturing_date,
expiry_date) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(name, quantity, rate, category, mfg_date_str, exp_date_str)

~ 11 ~
)
connection.commit()
print(f"Medication '{name}' added successfully.")
cursor.close()
connection.close()
else:
print("Database connection error.")
except Exception as e:
logging.error(f"Add failed: {e}")
print(f"Failed to add medication: {e}")

# ---------- View All Medications ----------


def view_medications():
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
cursor.execute("SELECT id, name, quantity, rate, category, manufacturing_date,
expiry_date FROM medications")
rows = cursor.fetchall()
if rows:
print("\nMedications in database:")
for row in rows:
med = Medication(*row)
print(f"ID: {med.id}, Name: {med.name}, Qty: {med.quantity}, Rate: ₹
{med.rate}, Category: {med.category},Mfg Date: {med.manufacturing_date}, Expiry Date:
{med.expiry_date}")
else:
print("No medications found.")

~ 12 ~
cursor.close()
connection.close()
except Exception as e:
logging.error(f"View medications failed: {e}")
print(f"Failed to retrieve medications: {e}")
else:
print("Database connection error.")

# ---------- Delete Medication ----------


def delete_medication():
try:
med_id_str = input("Enter medication ID to delete: ").strip()
if not med_id_str.isdigit():
print("Medication ID must be an integer.")
return
med_id = int(med_id_str)
connection = create_connection()
if connection:
cursor = connection.cursor()
cursor.execute("DELETE FROM medications WHERE id = %s", (med_id,))
connection.commit()
if cursor.rowcount > 0:
print("Medication deleted successfully.")
else:
print("Medication not found.")
cursor.close()
connection.close()
else:
print("Database connection error.")

~ 13 ~
except Exception as e:
logging.error(f"Delete failed: {e}")
print(f"Delete operation failed: {e}")

# ---------- Update Stock ----------


def update_stock():
try:
msssSssssed_id_str = input("Enter medication ID: ").strip()
csshange_str = input("Enter quantity change (+/-): ").strip()
if not med_id_str.isdigit():
print("Medication ID must be an integer.")
return
if not re.match(r"^-?\d+$", change_str):
print("Quantity change must be an integer.")
return
med_id = int(med_id_str)
change = int(change_str)

connection = create_connection()
if connection:
cursor = connection.cursor()
cursor.execute("SELECT quantity FROM medications WHERE id = %s", (med_id,))
result = cursor.fetchone()
if result:
new_qty = result[0] + change
if new_qty < 0:
print("Stock can't go below 0.")
cursor.close()
connection.close()

~ 14 ~
return
cursor.execute("UPDATE medications SET quantity = %s WHERE id = %s",
(new_qty, med_id))
connection.commit()
print(f"Stock updated successfully. New quantity: {new_qty}")
else:
print("Medication not found.")
cursor.close()
connection.close()
else:
print("Database connection error.")
except Exception as e:
logging.error(f"Stock update failed: {e}")
print(f"Failed to update stock: {e}")

# ---------- View Stock ----------


def view_stock():
med_id_str = input("Enter medication ID: ").strip()
if not med_id_str.isdigit():
print("Invalid ID.")
return
med_id = int(med_id_str)
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
cursor.execute("SELECT quantity FROM medications WHERE id = %s", (med_id,))
result = cursor.fetchone()
if result:

~ 15 ~
print(f"Stock available: {result[0]}")
else:
print("Medication not found.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"View stock failed: {e}")
print(f"Failed to view stock: {e}")
else:
print("Database connection error.")

# ---------- Generate Bill ----------


def generate_bill():
try:
items = [] # List to hold tuples of (med_id, quantity)
while True:
med_id_str = input("Enter medication ID (or type 'done' to finish): ").strip()
if med_id_str.lower() == 'done':
break
if not med_id_str.isdigit():
print("Medication ID must be a positive integer.")
continue
med_id = int(med_id_str)

quantity_str = input("Enter quantity to purchase: ").strip()


if not quantity_str.isdigit() or int(quantity_str) <= 0:
print("Quantity must be a positive integer.")
continue
quantity = int(quantity_str)

~ 16 ~
items.append((med_id, quantity)) # Add the item to the list

if not items:
print("No items entered for purchase.")
return

total_cost = decimal.Decimal('0.00')
bill_details = [] # To hold details for the bill

connection = create_connection()
if connection:
cursor = connection.cursor()
for med_id, quantity in items:
cursor.execute("SELECT name, rate, quantity FROM medications WHERE id =
%s", (med_id,))
result = cursor.fetchone()
if result:
name, rate, available = result
if quantity > available:
print(f"Insufficient stock for '{name}'. Available quantity: {available}. Item
skipped.")
continue
total = decimal.Decimal(rate) * quantity
total_cost += total
bill_details.append((name, quantity, rate, total))
cursor.execute("UPDATE medications SET quantity = quantity - %s WHERE id =
%s", (quantity, med_id))
else:

~ 17 ~
print(f"Medication ID {med_id} not found. Item skipped.")

connection.commit()
cursor.close()
connection.close()

if bill_details:
print("\n--- BILL ---")
print(f"{'Medication':<20} {'Qty':>5} {'Rate':>10} {'Total':>12}")
print("-" * 50)
for name, qty, rate, total in bill_details:
print(f"{name:<20} {qty:>5} {rate:>10.2f} {total:>12.2f}")
print("-" * 50)
print(f"{'Grand Total':<20} {'':>5} {'':>10} {total_cost:>12.2f}")
print("Thank you for your purchase!")
else:
print("No valid items purchased.")
else:
print("Database connection error.")
except Exception as e:
logging.error(f"Billing error: {e}")
print(f"Failed to generate bill: {e}")

# ---------- Search Medication ----------


def search_medication():
keyword = input("Search by name or category: ").strip()
if not re.match(r"^[a-zA-Z0-9\s]+$", keyword):
print("Invalid characters in search keyword.")
return

~ 18 ~
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
like_keyword = f"%{keyword}%"
cursor.execute("SELECT id, name, quantity FROM medications WHERE name LIKE
%s OR category LIKE %s", (like_keyword, like_keyword))
rows = cursor.fetchall()
if rows:
print(f"Search results for '{keyword}':")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Quantity: {row[2]}")
else:
print("No matching medications found.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Search failed: {e}")
print(f"Failed to search medications: {e}")
else:
print("Database connection error.")

# ---------- List Expiring Medications ----------


def list_expiring_medications():
days_str = input("Enter number of days to check for expiry (default 7): ").strip()
days = int(days_str) if days_str.isdigit() else 7
check_date = datetime.today().date() + timedelta(days=days)

~ 19 ~
connection = create_connection()
if connection:
try:
cursor = connection.cursor()
cursor.execute("SELECT id, name, expiry_date FROM medications WHERE
expiry_date <= %s", (check_date,))
rows = cursor.fetchall()
if rows:
print(f"Medications expiring within {days} day(s):")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Expiry Date: {row[2]}")
else:
print("No medications expiring soon.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Listing expiring medications failed: {e}")
print(f"Failed to list expiring medications: {e}")
else:
print("Database connection error.")

# ---------- Low Stock Alert ----------


def low_stock_alert():
threshold_str = input("Enter low stock threshold (default 10): ").strip()
threshold = int(threshold_str) if threshold_str.isdigit() else 10

connection = create_connection()
if connection:
try:

~ 20 ~
cursor = connection.cursor()
cursor.execute("SELECT id, name, quantity FROM medications WHERE quantity <
%s", (threshold,))
rows = cursor.fetchall()
if rows:
print(f"Medications with stock below {threshold}:")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Quantity: {row[2]}")
else:
print("All medications have sufficient stock.")
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Low stock alert failed: {e}")
print(f"Failed to fetch low stock medications: {e}")
else:
print("Database connection error.")

# ---------- Main Menu ----------


def main():
while True:
print("""
Pharmacy Management System
1. Add Medication
2. View Medications
3. Delete Medication
4. Update Stock
5. View Stock Availability
6. Generate Bill

~ 21 ~
7. Search Medication
8. List Expiring Medications
9. Low Stock Alert
10. Exit
""")
choice = input("Choose an option: ").strip()
if choice == '1':
add_medication()
elif choice == '2':
view_medications()
elif choice == '3':
delete_medication()
elif choice == '4':
update_stock()
elif choice == '5':
view_stock()
elif choice == '6':
generate_bill()
elif choice == '7':
search_medication()
elif choice == '8':
list_expiring_medications()
elif choice == '9':
low_stock_alert()
elif choice == '10':
print("Thank you! Exiting the system.")
sys.exit()
else:
print("Invalid choice. Please try again.")

~ 22 ~
if __name__== "__main__":
main()

OUTPUT

1.Adding a medication:
CASE 1:

~ 23 ~
CASE 2:

~ 24 ~
~ 25 ~
2.Viewing the medications available in the stock:

~ 26 ~
3.Deleting a medication:

CASE 1:

~ 27 ~
CASE 2:

4.Update the stock availability:


CASE 1:

~ 28 ~
CASE 2:

5.View stock availability:


~ 29 ~
CASE 1:

CASE 2:

6.Generating bill:

~ 30 ~
CASE 1:

CASE 2:

~ 31 ~
7.Searching a medication:

~ 32 ~
8.List of expiring medications according to number of days:

CASE 1:

~ 33 ~
CASE 2:

9.Low stock alert according to the number of stocks entered:

~ 34 ~
10.Exiting the system:

~ 35 ~
CONCLUSION

The Pharmacy Management System is a comprehensive Python-based software


application designed to efficiently handle various aspects of pharmacy management,
including inventory control and sales transactions. Integrated with a MySQL database,
the system provides a user- friendly command-line interface, making it accessible for
pharmacy staff. Key features include the ability to add new pharmaceutical products to
the inventory, edit existing product information, and remove items when necessary. The
system supports rigorous input validation to ensure data integrity, allowing for real-time
updates, viewing available quantities, and listing low-stock alerts. Additionally, it
monitors medications nearing expiry to minimize waste and
ensure patient safety.
Billing capabilities enable the generation of detailed bills for customer purchases, accurately
calculating totals while updating inventory levels. A search function facilitates quick retrieval of
medications by name or category, enhancing operational efficiency. The application
incorporates robust error handling and logging mechanisms to track runtime issues,
making maintenance and debugging manageable. By automating routine pharmacy
processes and
providing timely insights into stock and sales, the system significantly reduces human error
and enhances customer satisfaction.

Developed using Python and MySQL, this solution offers an efficient and scalable
database for managing daily pharmacy operations. It aims to improve operational
efficiency, enhance inventory management, and streamline the billing process, providing
a valuable tool for
pharmacies to manage their resources effectively. The application lays a strong
foundation for future improvements, such as implementing user authentication,
graphical interfaces, and advanced reporting features, all aimed at adapting to evolving
healthcare needs and elevating pharmacy management standards. Overall, the Pharmacy
Management System serves as an essential resource for pharmacies, ensuring accurate
transactions and effective resource management.

~ 36 ~
BIBLIOGRAPHY

 W3schools
 sqlzoo.net
 Simplilearn.net
 BLACKBOX.AI
 YouTube: Amit Thinks Channel
 https://onecompiler.com/python

~ 37 ~

You might also like